text stringlengths 8 4.13M |
|---|
use redox::Vec;
use super::from_bytes::FromBytes;
use super::metaslab::{Metaslab, MetaslabGroup};
use super::nvpair::{NvList, NvValue};
use super::zfs;
#[repr(packed)]
pub struct VdevLabel {
pub blank: [u8; 8 * 1024],
pub boot_header: [u8; 8 * 1024],
pub nv_pairs: [u8; 112 * 1024],
pub uberblocks: [u8; 128 * 1024],
}
impl FromBytes for VdevLabel { }
////////////////////////////////////////////////////////////////////////////////////////////////////
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum AllocType {
Load = 0,
Add,
Spare,
L2Cache,
RootPool,
Split,
Attach,
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// States are ordered from least to most healthy.
/// Vdevs `CannotOpen` and worse are considered unusable.
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum State {
Unknown, // Uninitialized vdev
Closed, // Not currently open
Offline, // Not allowed to open
Removed, // Explicitly removed from the system
CannotOpen, // Tried top open, but failed
Faulted, // External request to fault device
Degraded, // Replicated vdev with unhealthy kids
Healthy, // Presumed good
}
////////////////////////////////////////////////////////////////////////////////////////////////////
pub struct Vdev {
id: u64, // child number in vdev parent
guid: u64, // unique ID for this vdev
guid_sum: u64, // self guid + all child guids
orig_guid: u64, // orig. guid prior to remove
asize: u64, // allocatable device capacity
min_asize: u64, // min acceptable asize
max_asize: u64, // max acceptable asize
ashift: u64, // block alignment shift
state: State,
prev_state: State,
//ops: VdevOps,
// Top level only
ms_array_object: u64,
ms_group: MetaslabGroup,
metaslabs: Vec<Metaslab>,
is_hole: bool,
// Leaf only
}
impl Vdev {
pub fn new(id: u64, guid: u64) -> Self {
Vdev {
id: id,
guid: guid,
guid_sum: guid, // No children yet, so guid_sum is just my guid
orig_guid: 0,
asize: 0,
min_asize: 0,
max_asize: 0,
ashift: 0,
state: State::Closed,
prev_state: State::Unknown,
// Top level only
ms_array_object: 0,
ms_group: MetaslabGroup,
metaslabs: vec![],
is_hole: false, // TODO: zol checks vdev_ops for this, but idk what to do yet
}
}
pub fn load(nv: &NvList, id: u64, alloc_type: AllocType) -> zfs::Result<Self> {
if alloc_type == AllocType::Load {
// Verify the provided id matches the id written in the MOS
let label_id = try!(nv.find("id").ok_or(zfs::Error::Invalid));
match *label_id {
NvValue::Uint64(label_id) => {
if label_id != id { return Err(zfs::Error::Invalid); }
},
_ => { },
}
}
/*let guid =
match alloc_type {
AllocType::Load | AllocType::Spare | AllocType::L2Cache | AllocType::RootPool => {
Some(try!(nv.find("guid").ok_or(zfs::Error::Invalid)))
},
_ => { None },
};*/
//Ok(Self::new(id, guid))
Ok(Self::new(id, 0))
}
}
|
//! Tests auto-converted from "sass-spec/spec/libsass-closed-issues/issue_1418"
#[allow(unused)]
use super::rsass;
// From "sass-spec/spec/libsass-closed-issues/issue_1418/dynamic.hrx"
// Ignoring "dynamic", error tests are not supported yet.
// From "sass-spec/spec/libsass-closed-issues/issue_1418/static.hrx"
// Ignoring "test_static", error tests are not supported yet.
|
use std::error;
use std::fmt;
use redis::RedisError;
mod redis_connection;
pub mod memory;
pub mod session;
pub mod text;
pub mod object_table;
pub mod state;
pub mod instruction;
pub mod interface;
pub mod dictionary;
#[derive(Debug)]
pub enum InfocomError {
Memory(String),
ReadViolation(usize, usize),
WriteViolation(usize, usize),
Text(String),
API(String),
Session(String),
Version(memory::Version),
Redis(RedisError)
}
impl fmt::Display for InfocomError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
InfocomError::ReadViolation(ref a, ref b) => f.write_fmt(format_args!("Invalid read from ${:06x} beyond end of static memory ${:06x}", a, std::cmp::min(0xFFFF, *b))),
InfocomError::WriteViolation(ref a, ref b) => f.write_fmt(format_args!("Invalid write to ${:06x} beyond end of dynamic memory ${:06x}", a, b)),
InfocomError::Version(ref e) => f.write_fmt(format_args!("Unsupported Z-Machine version: {:?}", e)),
InfocomError::Redis(ref e) => e.fmt(f),
InfocomError::Memory(ref e) => e.fmt(f),
InfocomError::Text(ref e) => e.fmt(f),
InfocomError::API(ref e) => e.fmt(f),
InfocomError::Session(ref e) => e.fmt(f)
}
}
}
impl error::Error for InfocomError {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
match *self {
InfocomError::Redis(ref e) => Some(e),
_ => None
}
}
}
impl From<RedisError> for InfocomError {
fn from(err: RedisError) -> InfocomError {
InfocomError::Redis(err)
}
} |
/*
Rust permutations library
Copyright (C) 2017 Jeremy Salwen
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
use std;
use std::cmp::Ordering;
use std::ops::Deref;
#[derive(Clone, Debug, Default)]
pub struct Permutation {
inv: bool,
indices: Vec<usize>,
}
impl std::cmp::PartialEq for Permutation {
/// This method compares two Permutations for equality, and is uses by `==`
fn eq(&self, other: &Permutation) -> bool {
if self.inv == other.inv {
self.indices == other.indices
} else {
self.indices
.iter()
.enumerate()
.all(|(i, &j)| other.indices[j] == i)
}
}
}
impl std::cmp::Eq for Permutation {}
impl<'a, 'b> std::ops::Mul<&'b Permutation> for &'a Permutation {
type Output = Permutation;
/// Multiply permutations, in the mathematical sense.
///
/// Given two permutations `a`, and `b`, `a * b` is defined as
/// the permutation created by first applying b, then applying a.
///
/// # Examples
///
/// ```
/// # use permutation::Permutation;
/// let p1 = Permutation::from_vec(vec![1, 0, 2]);
/// let p2 = Permutation::from_vec(vec![0, 2, 1]);
/// assert!(&p1 * &p2 == Permutation::from_vec(vec![2,0,1]));
/// ```
fn mul(self, rhs: &'b Permutation) -> Self::Output {
match (self.inv, rhs.inv) {
(_, false) => Permutation::from_vec(self.apply_slice(&rhs.indices[..])),
(false, true) => return self * &(rhs * &Permutation::one(self.len())),
(true, true) => {
Permutation {
inv: true,
indices: rhs.apply_inv_slice(&self.indices[..]),
}
}
}
}
}
impl Permutation {
/// Create a permutation from a vector of indices.
///
/// from_vec(v) returns the permutation P such that P applied to [1,2,...,N] is v.
/// Note that this notation is the inverse of the usual [one-line notation](https://en.wikipedia.org/wiki/Permutation#Definition_and_notations)
/// used in mathematics. This is a known issue and may change in a newer release.
///
/// # Examples
///
/// ```
/// # use permutation::Permutation;
/// let vec = vec!['a','b','c','d'];
/// let permutation = Permutation::from_vec(vec![0,2,3,1]);
/// assert!(permutation.apply_slice(&vec[..]) == vec!['a','c','d','b']);
/// ```
pub fn from_vec(vec: Vec<usize>) -> Permutation {
let result = Permutation {
inv: false,
indices: vec,
};
debug_assert!(result.valid());
return result;
}
/// Return the identity permutation of size N.
///
/// This returns the identity permutation of N elements.
///
/// # Examples
/// ```
/// # use permutation::Permutation;
/// let vec = vec!['a','b','c','d'];
/// let permutation = Permutation::one(4);
/// assert!(permutation.apply_slice(&vec[..]) == vec!['a','b','c','d']);
/// ```
pub fn one(len: usize) -> Permutation {
Permutation {
inv: false,
indices: (0..len).collect(),
}
}
/// Return the size of a permutation.
///
/// This is the number of elements that the permutation acts on.
///
/// # Examples
/// ```
/// use permutation::Permutation;
/// let permutation = Permutation::one(4);
/// assert!(permutation.len() == 4);
/// ```
pub fn len(&self) -> usize {
return self.indices.len();
}
/// Check whether a permutation is valid.
///
/// A permutation can be invalid if it was constructed with an
/// incorrect vector using ``::from_vec()``. Debug assertions will
/// catch this on construction, so it should never return true.
///
pub fn valid(&self) -> bool {
let mut sorted = self.indices.clone();
sorted.sort();
return sorted.iter().enumerate().all(|(i, &j)| i == j);
}
/// Returns whether the forward permutation is fast
///
/// ```
/// # use permutation::Permutation;
/// let permutation = Permutation::from_vec(vec![0,2,3,1]);
/// let permutation = permutation.normalize(false);
/// assert!(permutation.is_apply_fast());
/// ```
pub fn is_apply_fast(&self) -> bool {
self.inv
}
/// Returns whether the backwards permutation is fast
///
/// ```
/// # use permutation::Permutation;
/// let permutation = Permutation::from_vec(vec![0,2,3,1]);
/// let permutation = permutation.normalize(true);
/// assert!(permutation.is_apply_inv_fast());
/// ```
pub fn is_apply_inv_fast(&self) -> bool {
!self.inv
}
/// Return the inverse of a permutation.
///
/// This returns a permutation that will undo a given permutation.
/// Internally, this does not compute the inverse, but just flips a bit.
///
/// ```
/// # use permutation::Permutation;
/// let permutation = Permutation::from_vec(vec![0,2,3,1]);
/// assert!(permutation.inverse() == Permutation::from_vec(vec![0,3,1,2]));
/// ```
pub fn inverse(mut self) -> Permutation {
self.inv ^= true;
return self;
}
/// Normalize the internal storage of the `Permutation`, optimizing it for forward or inverse application.
///
/// Internally, the permutation has a bit to indicate whether it is inverted.
/// This is because given a permutation P, it is just as easy to compute `P^-1 * Q`
/// as it is to compute `P * Q`. However, computing the entries of `P^-1` requires some computation.
/// However, when applying to the permutation to an index, the permutation has a "preferred" direction, which
/// is much quicker to compute.
///
/// The `normalize()` method does not change the value of the permutation, but
/// it converts it into the preferred form for applying `P` or its inverse, respectively.
///
/// If `backward` is `false`, it will be in the preferred form for applying `P`,
/// if `backward` is `true`, it will be in the preferred form for appling `P^-1`
///
/// # Examples
///
/// ```
/// # use permutation::Permutation;
/// let permutation = Permutation::from_vec(vec![0, 3, 2, 5, 1, 4]);
/// let reversed = permutation.inverse().normalize(true);
/// assert!(reversed.apply_inv_idx(3) == 1);
/// ```
pub fn normalize(self, backward: bool) -> Permutation {
// Note that "reverse" index lookups are easier, so we actually
// want reversed == true for forward normalization,
// and reverse == false for backward normalization.
if self.inv ^ backward {
self
} else {
let len = self.len();
if backward {
&self * &Permutation::one(len)
} else {
(&self.inverse() * &Permutation::one(len)).inverse()
}
}
}
pub fn as_vec(self) -> Vec<usize> {
self.normalize(true).indices
}
fn apply_idx_fwd(&self, idx: usize) -> usize {
self.indices
.iter()
.position(|&v| v == idx)
.unwrap()
}
fn apply_idx_bkwd(&self, idx: usize) -> usize {
self.indices[idx]
}
/// Apply the permutation to an index.
///
/// Given an index of an element, this will return the new index
/// of that element after applying the permutation.
///
/// # Examples
///
/// ```
/// # use permutation::Permutation;
/// let permutation = Permutation::from_vec(vec![0,2,1]);
/// assert!(permutation.apply_idx(2) == 1);
pub fn apply_idx(&self, idx: usize) -> usize {
match self.inv {
false => self.apply_idx_fwd(idx),
true => self.apply_idx_bkwd(idx),
}
}
/// Apply the inverse of a permutation to an index.
///
/// Given an index of an element, this will return the new index
/// of that element after applying 'P^-1'.
///
/// Equivalently, if `P.apply_idx(i) == j`, then `P.apply_inv_idx(j) == i`.
///
/// # Examples
///
/// ```
/// # use permutation::Permutation;
/// let permutation = Permutation::from_vec(vec![0,2,1]);
/// assert!(permutation.apply_inv_idx(1) == 2);
/// ```
pub fn apply_inv_idx(&self, idx: usize) -> usize {
match self.inv {
true => self.apply_idx_fwd(idx),
false => self.apply_idx_bkwd(idx),
}
}
fn apply_slice_fwd<T: Clone, D>(&self, vec: D) -> Vec<T>
where D: Deref<Target = [T]>
{
self.indices
.iter()
.map(|&idx| vec[idx].clone())
.collect()
}
fn apply_slice_bkwd<T: Clone, D>(&self, vec: D) -> Vec<T>
where D: Deref<Target = [T]>
{
let mut other: Vec<T> = vec.to_vec();
for (i, idx) in self.indices.iter().enumerate() {
other[*idx] = vec[i].clone();
}
return other;
}
/// Apply a permutation to a slice of elements
///
/// Given a slice of elements, this will permute the elements in place according
/// to this permutation.
///
/// # Examples
///
/// ```
/// # use permutation::Permutation;
/// let permutation = Permutation::from_vec(vec![0,3,1,2]);
/// let vec = vec!['a','b','c','d'];
/// assert!(permutation.apply_slice(&vec[..]) == vec!['a', 'd', 'b', 'c']);
/// ```
pub fn apply_slice<T: Clone, D>(&self, vec: D) -> Vec<T>
where D: Deref<Target = [T]>
{
assert!(vec.len() == self.len());
match self.inv {
false => self.apply_slice_fwd(vec),
true => self.apply_slice_bkwd(vec),
}
}
pub fn apply_vec<T>(&self, vec: &mut Vec<T>) {
assert!(vec.len() == self.len());
let mut v = vec![];
v.resize_with(vec.len(), Option::<T>::default);
for (i, el) in vec.drain(..).enumerate() {
if self.inv {
v[self.indices[i]] = Some(el);
} else {
v[i] = Some(el);
}
}
for (i, p) in self.indices.iter().cloned().enumerate() {
if self.inv {
vec.push(v[i].take().unwrap());
} else {
vec.push(v[p].take().unwrap());
}
}
}
/// Apply the inverse of a permutation to a slice of elements
///
/// Given a slice of elements, this will permute the elements in place according
/// to the inverse of this permutation. This is equivalent to "undoing" the permutation.
///
/// # Examples
///
/// ```
/// # use permutation::Permutation;
/// let permutation = Permutation::from_vec(vec![0,3,1,2]);
/// let vec = vec!['a','b', 'c', 'd'];
/// assert!(permutation.apply_inv_slice(vec) == vec!['a', 'c', 'd', 'b']);
/// ```
pub fn apply_inv_slice<T: Clone, D>(&self, vec: D) -> Vec<T>
where D: Deref<Target = [T]>
{
assert!(vec.len() == self.len());
match self.inv {
false => self.apply_slice_bkwd(vec),
true => self.apply_slice_fwd(vec),
}
}
}
/// Return the permutation that would sort a given slice.
///
/// This calculates the permutation that if it were applied to the slice,
/// would put the elements in sorted order.
///
/// # Examples
///
/// ```
/// # use permutation::Permutation;
/// let mut vec = vec!['z','w','h','a','s','j'];
/// let permutation = permutation::sort(&vec[..]);
/// let permuted = permutation.apply_slice(&vec[..]);
/// vec.sort();
/// assert!(vec == permuted);
/// ```
///
/// You can also use it to sort multiple arrays based on the ordering of one.
///
/// ```
/// let names = vec!["Bob", "Steve", "Jane"];
/// let salary = vec![10, 5, 15];
/// let permutation = permutation::sort(&salary[..]);
/// let ordered_names = permutation.apply_slice(&names[..]);
/// let ordered_salaries = permutation.apply_slice(&salary[..]);
/// assert!(ordered_names == vec!["Steve", "Bob", "Jane"]);
/// assert!(ordered_salaries == vec![5, 10, 15]);
/// ```
pub fn sort<T, D>(vec: D) -> Permutation
where T: Ord,
D: Deref<Target = [T]>
{
let mut permutation = Permutation::one(vec.len());
//We use the reverse permutation form, because its more efficient for applying to indices.
permutation.indices.sort_by_key(|&i| &vec[i]);
return permutation;
}
/// Return the permutation that would sort a given slice by a comparator.
///
/// This is the same as `permutation::sort()` except that it allows you to specify
/// the comparator to use when sorting similar to `std::slice.sort_by()`
///
/// # Examples
///
/// ```
/// # use permutation::Permutation;
/// let mut vec = vec!['z','w','h','a','s','j'];
/// let permutation = permutation::sort_by(&vec[..], |a, b| b.cmp(a));
/// let permuted = permutation.apply_slice(&vec[..]);
/// vec.sort_by(|a,b| b.cmp(a));
/// assert!(vec == permuted);
/// ```
pub fn sort_by<T, D, F>(vec: D, mut compare: F) -> Permutation
where T: Ord,
D: Deref<Target = [T]>,
F: FnMut(&T, &T) -> Ordering
{
let mut permutation = Permutation::one(vec.len());
//We use the reverse permutation form, because its more efficient for applying to indices.
permutation.indices.sort_by(|&i, &j| compare(&vec[i], &vec[j]));
return permutation;
}
/// Return the permutation that would sort a given slice by a key function.
///
/// This is the same as `permutation::sort()` except that it allows you to specify
/// the key function simliar to `std::slice.sort_by_key()`
///
/// # Examples
///
/// ```
/// # use permutation::Permutation;
/// let mut vec = vec![2, 4, 6, 8, 10, 11];
/// let permutation = permutation::sort_by_key(&vec[..], |a| a % 3);
/// let permuted = permutation.apply_slice(&vec[..]);
/// vec.sort_by_key(|a| a % 3);
/// assert!(vec == permuted);
/// ```
pub fn sort_by_key<T, D, B, F>(vec: D, mut f: F) -> Permutation
where B: Ord,
D: Deref<Target = [T]>,
F: FnMut(&T) -> B
{
let mut permutation = Permutation::one(vec.len());
//We use the reverse permutation form, because its more efficient for applying to indices.
permutation.indices.sort_by_key(|&i| f(&vec[i]));
return permutation;
}
pub fn by_key<B, F>(len: usize, f: F) -> Permutation
where B: Ord,
F: FnMut(&usize) -> B
{
let mut permutation = Permutation::one(len);
//We use the reverse permutation form, because its more efficient for applying to indices.
permutation.indices.sort_by_key(f);
return permutation;
}
#[cfg(test)]
mod tests {
use permutation;
use permutation::Permutation;
#[test]
fn basics() {
let p1 = Permutation::one(5);
let p2 = Permutation::one(5);
assert!(p1.valid());
assert!(p1 == p2);
let p3 = Permutation::one(6);
assert!(p1 != p3);
assert!(&p1 * &p2 == p1);
assert!(p1.clone().inverse() == p1);
}
#[test]
fn powers() {
let id = Permutation::one(3);
let p1 = Permutation::from_vec(vec![1, 0, 2]);
let square = &p1 * &p1;
assert!(square == id);
let cube = &p1 * □
assert!(cube == p1);
}
#[test]
fn apply_vec() {
use super::sort;
let v = vec![1, 0, 2];
let p = sort(v.as_slice());
let cloned = p.apply_slice(v.as_slice());
let mut v = v;
p.apply_vec(&mut v);
assert!(v == cloned);
}
#[test]
fn prod() {
let p1 = Permutation::from_vec(vec![1, 0, 2]);
let p2 = Permutation::from_vec(vec![0, 2, 1]);
let prod = &p1 * &p2;
assert!(prod == Permutation::from_vec(vec![2, 0, 1]));
}
#[test]
fn len() {
let p1 = Permutation::from_vec(vec![1, 0, 2]);
assert!(p1.len() == 3)
}
fn check_not_equal_inverses(p2: &Permutation, p3: &Permutation) {
assert!(*p2 != *p3);
assert!(p2 * p3 == Permutation::one(p2.len()));
assert!(p3 * p2 == Permutation::one(p2.len()));
assert!(*p2 == p3.clone().inverse());
assert!(p2.clone().inverse() == *p3);
assert!(p2.clone().inverse() != p3.clone().inverse());
assert!(p2 * &p3.clone().inverse() != Permutation::one(p2.len()));
assert!(&p2.clone().inverse() * p3 != Permutation::one(p2.len()));
}
#[test]
fn inverse() {
let p1 = Permutation::from_vec(vec![1, 0, 2]);
let rev = p1.clone().inverse();
assert!(p1 == rev);
//An element and its inverse
let p2 = Permutation::from_vec(vec![1, 2, 0, 4, 3]);
let p3 = Permutation::from_vec(vec![2, 0, 1, 4, 3]);
check_not_equal_inverses(&p2, &p3);
println!("{:?}, {:?}, {:?}",
p2.clone().inverse(),
p3.clone().inverse(),
&p2.clone().inverse() * &p3.clone().inverse());
assert!(&p2.clone().inverse() * &p3.clone().inverse() == Permutation::one(p2.len()));
//An element, and a distinct element which is not its inverse.
let p4 = Permutation::from_vec(vec![1, 2, 0, 3, 4]);
let p5 = Permutation::from_vec(vec![2, 0, 1, 4, 3]);
assert!(p4 != p5);
assert!(p4 != p5.clone().inverse());
assert!(p4.clone().inverse() != p5);
assert!(p4.clone().inverse() != p5.clone().inverse());
assert!(&p4 * &p5 != Permutation::one(p4.len()));
assert!(&p5 * &p4 != Permutation::one(p4.len()));
assert!(&p4.clone().inverse() * &p5 != Permutation::one(p4.len()));
assert!(&p4 * &p5.clone().inverse() != Permutation::one(p4.len()));
}
#[test]
fn sorting() {
let elems = vec!['a', 'b', 'e', 'g', 'f'];
let perm = permutation::sort(&elems[..]);
println!("{:?}", perm);
assert!(perm == Permutation::from_vec(vec![0, 1, 2, 4, 3]));
}
#[test]
fn strings() {
let elems = vec!["doggie", "cat", "doggo", "dog", "doggies", "god"];
let perm = permutation::sort(&elems[..]);
assert!(perm == Permutation::from_vec(vec![1, 3, 0, 4, 2, 5]));
assert!(perm.apply_slice(&elems[..]) ==
vec!["cat", "dog", "doggie", "doggies", "doggo", "god"]);
let parallel = vec!["doggie1", "cat1", "doggo1", "dog1", "doggies1", "god1"];
let par_permuted = perm.apply_slice(¶llel[..]);
println!("{:?}", par_permuted);
assert!(par_permuted == vec!["cat1", "dog1", "doggie1", "doggies1", "doggo1", "god1"]);
assert!(perm.apply_inv_slice(par_permuted) == parallel);
}
#[test]
fn by_key() {
let vec = vec![1, 10, 9, 8];
let perm = permutation::sort_by_key(vec, |i| -i);
assert!(perm == Permutation::from_vec(vec![1, 2, 3, 0]));
}
#[test]
fn by_cmp() {
let vec = vec!["aaabaab", "aba", "cas", "aaab"];
let perm = permutation::sort_by(vec, |a, b| a.cmp(b));
assert!(perm == Permutation::from_vec(vec![3, 0, 1, 2]));
}
#[test]
fn indices() {
let vec = vec![100, 10, 1, 1000];
let perm = permutation::sort_by_key(vec, |x| -x);
println!("{:?}", perm.apply_inv_idx(0));
assert!(perm.apply_inv_idx(0) == 3);
assert!(perm.apply_idx(3) == 0);
assert!(perm.apply_inv_idx(1) == 0);
assert!(perm.apply_idx(0) == 1);
assert!(perm.apply_inv_idx(2) == 1);
assert!(perm.apply_idx(1) == 2);
assert!(perm.apply_inv_idx(3) == 2);
assert!(perm.apply_idx(2) == 3);
}
#[test]
fn normalize() {
let vec = vec![100, 10, 1, 1000];
let perm = permutation::sort_by_key(vec, |x| -x);
let f = perm.clone().normalize(false);
let b = perm.clone().normalize(true);
assert!(perm == f);
assert!(f == b);
for idx in 0..perm.len() {
assert!(perm.apply_idx(idx) == f.apply_idx(idx));
assert!(f.apply_idx(idx) == b.apply_idx(idx));
assert!(perm.apply_inv_idx(idx) == f.apply_inv_idx(idx));
assert!(f.apply_inv_idx(idx) == b.apply_inv_idx(idx));
}
let inv = perm.clone().inverse();
let fi = inv.clone().normalize(false);
let bi = inv.clone().normalize(true);
assert!(inv == fi);
assert!(fi == bi);
for idx in 0..perm.len() {
assert!(inv.apply_idx(idx) == fi.apply_idx(idx));
assert!(fi.apply_idx(idx) == bi.apply_idx(idx));
assert!(inv.apply_inv_idx(idx) == fi.apply_inv_idx(idx));
assert!(fi.apply_inv_idx(idx) == bi.apply_inv_idx(idx));
}
}
#[test]
fn normalize_inv() {
let p1 = Permutation::from_vec(vec![1, 0, 2]);
let rev = p1.clone().inverse();
assert!(p1 == rev);
//An element and its inverse
let mut p2 = Permutation::from_vec(vec![1, 2, 0, 4, 3]);
let mut p3 = Permutation::from_vec(vec![2, 0, 1, 4, 3]);
p2 = p2.normalize(false);
p3 = p3.normalize(false);
check_not_equal_inverses(&p2, &p3);
p2 = p2.normalize(true);
p3 = p3.normalize(true);
check_not_equal_inverses(&p2, &p3);
p2 = p2.normalize(true);
p3 = p3.normalize(false);
check_not_equal_inverses(&p2, &p3);
p2 = p2.normalize(false);
p3 = p3.normalize(true);
check_not_equal_inverses(&p2, &p3);
}
}
|
/// Keys and buttons
///
/// Most of the keys/buttons are modeled after USB HUT 1.12
/// (see http://www.usb.org/developers/hidpage).
/// Also see linux/include/uapi/linux/input-event-codes.h
///
/// Abbreviations in the comments:
/// AC - Application Control
/// AL - Application Launch Button
/// SC - System Contro
///
#[repr(u8)]
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum Key {
Reserved,
Esc,
One,
Two,
Three,
Four,
Five,
Six,
Seven,
Eight,
Nine,
Zero,
Minus,
Equal,
Backspace,
Tab,
Q,
W,
E,
R,
T,
Y,
U,
I,
O,
P,
LeftBrace,
RightBrace,
Enter,
LeftCtrl,
A,
S,
D,
F,
G,
H,
J,
K,
L,
Semicolon,
Apostrophe,
Grave,
LeftShift,
BackSlash,
Z,
X,
C,
V,
B,
N,
M,
Comma,
Dot,
Slash,
RightShift,
Kpasterisk,
LeftAlt,
Space,
CapsLock,
F1,
F2,
F3,
F4,
F5,
F6,
F7,
F8,
F9,
F10,
NumLock,
ScrollLock,
Kp7,
Kp8,
Kp9,
Kpminus,
Kp4,
Kp5,
Kp6,
Kpplus,
Kp1,
Kp2,
Kp3,
Kp0,
Kpdot,
Zenkakuhankaku,
PoundDisplaced, // 102nd key
F11,
F12,
Ro,
Katakana,
Hiragana,
Henkan,
Katakanahiragana,
Muhenkan,
Kpjpcomma,
Kpenter,
RightCtrl,
Kpslash,
Sysrq,
RightAlt,
LineFeed,
Home,
Up,
PageUp,
Left,
Right,
End,
Down,
PageDown,
Insert,
Delete,
Macro,
Mute,
VolumeDown,
VolumeUp,
Power, /* sc system power down */
Kpequal,
Kpplusminus,
Pause,
Scale, /* al compiz scale (expose) */
Kpcomma,
Hangeul,
Hanguel,
Hanja,
Yen,
LeftMeta,
RightMeta,
Compose,
Stop, /* ac stop */
Again,
Props, /* ac properties */
Undo, /* ac undo */
Front,
Copy, /* ac copy */
Open, /* ac open */
Paste, /* ac paste */
Find, /* ac search */
Cut, /* ac cut */
Help, /* al integrated help center */
Menu, /* menu (show menu) */
Calc, /* al calculator */
Setup,
Sleep, /* sc system sleep */
Wakeup, /* system wake up */
File, /* al local machine browser */
SendFile,
DeleteFile,
Xfer,
Prog1,
Prog2,
Www, /* al internet browser */
Msdos,
Coffee, /* al terminal lock/screensaver */
//screenlock, coffee
RotateDisplay, /* display orientation for e.g. tablets */
//direction, rotate_display
CycleWindows,
Mail,
Bookmarks, /* ac bookmarks */
Computer,
Back, /* ac back */
Forward, /* ac forward */
CloseCD,
EjectCD,
EjectCloseCD,
NextSong,
PlayPause,
PreviousSong,
StopCD,
Record,
Rewind,
Phone, /* media select telephone */
Iso,
Config, /* al consumer control configuration */
Homepage, /* ac home */
Refresh, /* ac refresh */
Exit, /* ac exit */
Move,
Edit,
ScrollUp,
ScrollDown,
Kpleftparen,
Kprightparen,
New, /* ac new */
Redo, /* ac redo/repeat */
F13,
F14,
F15,
F16,
F17,
F18,
F19,
F20,
F21,
F22,
F23,
F24,
PlayCD,
PauseCD,
Prog3,
Prog4,
Dashboard, /* al dashboard */
Suspend,
Close, /* ac close */
Play,
FastForward,
BassBoost,
Print, /* ac print */
Hp,
Camera,
Sound,
Question,
Email,
Chat,
Search,
Connect,
Finance, /* al checkbook/finance */
Sport,
Shop,
Alterase,
Cancel, /* ac cancel */
BrightnessDown,
BrightnessUp,
Media,
SwitchVideoMode, /* cycle between available video
outputs (Monitor/LCD/TV-out/etc) */
Kbdillumtoggle,
Kbdillumdown,
Kbdillumup,
Send, /* ac send */
Reply, /* ac reply */
ForwardMail, /* ac forward msg */
Save, /* ac save */
Documents,
Battery,
BlueTooth,
Wlan,
Uwb,
Unknown,
VideoNext, /* drive next video source */
VideoPrev, /* drive previous video source */
BrightnessCycle, /* brightness up, after max is min */
BrightnessAuto, /* set auto brightness: manual brightness control is off, rely on ambient */
DisplayOff, /* display device to off state */
Wwan, /* wireless wan (lte, umts, gsm, etc.) */
//#define WIMAX KEY_WWAN
RFkill, /* key that controls all radios */
MicMute, /* mute / unmute the microphone */
}
impl From<Key> for u8 {
fn from(val: Key) -> u8 {
match val {
Key::Reserved => 0,
Key::Esc => 1,
Key::One => 2,
Key::Two => 3,
Key::Three => 4,
Key::Four => 5,
Key::Five => 6,
Key::Six => 7,
Key::Seven => 8,
Key::Eight => 9,
Key::Nine => 10,
Key::Zero => 11,
Key::Minus => 12,
Key::Equal => 13,
Key::Backspace => 14,
Key::Tab => 15,
Key::Q => 16,
Key::W => 17,
Key::E => 18,
Key::R => 19,
Key::T => 20,
Key::Y => 21,
Key::U => 22,
Key::I => 23,
Key::O => 24,
Key::P => 25,
Key::LeftBrace => 26,
Key::RightBrace => 27,
Key::Enter => 28,
Key::LeftCtrl => 29,
Key::A => 30,
Key::S => 31,
Key::D => 32,
Key::F => 33,
Key::G => 34,
Key::H => 35,
Key::J => 36,
Key::K => 37,
Key::L => 38,
Key::Semicolon => 39,
Key::Apostrophe => 40,
Key::Grave => 41,
Key::LeftShift => 42,
Key::BackSlash => 43,
Key::Z => 44,
Key::X => 45,
Key::C => 46,
Key::V => 47,
Key::B => 48,
Key::N => 49,
Key::M => 50,
Key::Comma => 51,
Key::Dot => 52,
Key::Slash => 53,
Key::RightShift => 54,
Key::Kpasterisk => 55,
Key::LeftAlt => 56,
Key::Space => 57,
Key::CapsLock => 58,
Key::F1 => 59,
Key::F2 => 60,
Key::F3 => 61,
Key::F4 => 62,
Key::F5 => 63,
Key::F6 => 64,
Key::F7 => 65,
Key::F8 => 66,
Key::F9 => 67,
Key::F10 => 68,
Key::NumLock => 69,
Key::ScrollLock => 70,
Key::Kp7 => 71,
Key::Kp8 => 72,
Key::Kp9 => 73,
Key::Kpminus => 74,
Key::Kp4 => 75,
Key::Kp5 => 76,
Key::Kp6 => 77,
Key::Kpplus => 78,
Key::Kp1 => 79,
Key::Kp2 => 80,
Key::Kp3 => 81,
Key::Kp0 => 82,
Key::Kpdot => 83,
Key::Zenkakuhankaku => 84,
Key::PoundDisplaced => 85,
Key::F11 => 86,
Key::F12 => 87,
Key::Ro => 88,
Key::Katakana => 89,
Key::Hiragana => 90,
Key::Henkan => 91,
Key::Katakanahiragana => 92,
Key::Muhenkan => 93,
Key::Kpjpcomma => 94,
Key::Kpenter => 95,
Key::RightCtrl => 96,
Key::Kpslash => 97,
Key::Sysrq => 98,
Key::RightAlt => 99,
Key::LineFeed => 100,
Key::Home => 101,
Key::Up => 102,
Key::PageUp => 103,
Key::Left => 104,
Key::Right => 105,
Key::End => 106,
Key::Down => 107,
Key::PageDown => 108,
Key::Insert => 109,
Key::Delete => 110,
Key::Macro => 111,
Key::Mute => 112,
Key::VolumeDown => 113,
Key::VolumeUp => 114,
Key::Power => 115,
Key::Kpequal => 116,
Key::Kpplusminus => 117,
Key::Pause => 118,
Key::Scale => 119,
Key::Kpcomma => 120,
Key::Hangeul => 121,
Key::Hanguel => 122,
Key::Hanja => 123,
Key::Yen => 124,
Key::LeftMeta => 125,
Key::RightMeta => 126,
Key::Compose => 127,
Key::Stop => 128,
Key::Again => 129,
Key::Props => 130,
Key::Undo => 131,
Key::Front => 132,
Key::Copy => 133,
Key::Open => 134,
Key::Paste => 135,
Key::Find => 136,
Key::Cut => 137,
Key::Help => 138,
Key::Menu => 139,
Key::Calc => 140,
Key::Setup => 141,
Key::Sleep => 142,
Key::Wakeup => 143,
Key::File => 144,
Key::SendFile => 145,
Key::DeleteFile => 146,
Key::Xfer => 147,
Key::Prog1 => 148,
Key::Prog2 => 149,
Key::Www => 150,
Key::Msdos => 151,
Key::Coffee => 152,
Key::RotateDisplay => 153,
Key::CycleWindows => 154,
Key::Mail => 155,
Key::Bookmarks => 156,
Key::Computer => 157,
Key::Back => 158,
Key::Forward => 159,
Key::CloseCD => 160,
Key::EjectCD => 161,
Key::EjectCloseCD => 162,
Key::NextSong => 163,
Key::PlayPause => 164,
Key::PreviousSong => 165,
Key::StopCD => 166,
Key::Record => 167,
Key::Rewind => 168,
Key::Phone => 169,
Key::Iso => 170,
Key::Config => 171,
Key::Homepage => 172,
Key::Refresh => 173,
Key::Exit => 174,
Key::Move => 175,
Key::Edit => 176,
Key::ScrollUp => 177,
Key::ScrollDown => 178,
Key::Kpleftparen => 179,
Key::Kprightparen => 180,
Key::New => 181,
Key::Redo => 182,
Key::F13 => 183,
Key::F14 => 184,
Key::F15 => 185,
Key::F16 => 186,
Key::F17 => 187,
Key::F18 => 188,
Key::F19 => 189,
Key::F20 => 190,
Key::F21 => 191,
Key::F22 => 192,
Key::F23 => 193,
Key::F24 => 194,
Key::PlayCD => 200,
Key::PauseCD => 201,
Key::Prog3 => 202,
Key::Prog4 => 203,
Key::Dashboard => 204,
Key::Suspend => 205,
Key::Close => 206,
Key::Play => 207,
Key::FastForward => 208,
Key::BassBoost => 209,
Key::Print => 210,
Key::Hp => 211,
Key::Camera => 212,
Key::Sound => 213,
Key::Question => 214,
Key::Email => 215,
Key::Chat => 216,
Key::Search => 217,
Key::Connect => 218,
Key::Finance => 219,
Key::Sport => 220,
Key::Shop => 221,
Key::Alterase => 222,
Key::Cancel => 223,
Key::BrightnessDown => 224,
Key::BrightnessUp => 225,
Key::Media => 226,
Key::SwitchVideoMode => 227,
Key::Kbdillumtoggle => 228,
Key::Kbdillumdown => 229,
Key::Kbdillumup => 230,
Key::Send => 231,
Key::Reply => 232,
Key::ForwardMail => 233,
Key::Save => 234,
Key::Documents => 235,
Key::Battery => 236,
Key::BlueTooth => 237,
Key::Wlan => 238,
Key::Uwb => 239,
Key::Unknown => 240,
Key::VideoNext => 241,
Key::VideoPrev => 242,
Key::BrightnessCycle => 243,
Key::BrightnessAuto => 244,
Key::DisplayOff => 245,
Key::Wwan => 246,
Key::RFkill => 247,
Key::MicMute => 248,
}
}
}
impl From<u8> for Key {
fn from(val: u8) -> Key {
match val {
0 => Key::Reserved,
1 => Key::Esc,
2 => Key::One,
3 => Key::Two,
4 => Key::Three,
5 => Key::Four,
6 => Key::Five,
7 => Key::Six,
8 => Key::Seven,
9 => Key::Eight,
10 => Key::Nine,
11 => Key::Zero,
12 => Key::Minus,
13 => Key::Equal,
14 => Key::Backspace,
15 => Key::Tab,
16 => Key::Q,
17 => Key::W,
18 => Key::E,
19 => Key::R,
20 => Key::T,
21 => Key::Y,
22 => Key::U,
23 => Key::I,
24 => Key::O,
25 => Key::P,
26 => Key::LeftBrace,
27 => Key::RightBrace,
28 => Key::Enter,
29 => Key::LeftCtrl,
30 => Key::A,
31 => Key::S,
32 => Key::D,
33 => Key::F,
34 => Key::G,
35 => Key::H,
36 => Key::J,
37 => Key::K,
38 => Key::L,
39 => Key::Semicolon,
40 => Key::Apostrophe,
41 => Key::Grave,
42 => Key::LeftShift,
43 => Key::BackSlash,
44 => Key::Z,
45 => Key::X,
46 => Key::C,
47 => Key::V,
48 => Key::B,
49 => Key::N,
50 => Key::M,
51 => Key::Comma,
52 => Key::Dot,
53 => Key::Slash,
54 => Key::RightShift,
55 => Key::Kpasterisk,
56 => Key::LeftAlt,
57 => Key::Space,
58 => Key::CapsLock,
59 => Key::F1,
60 => Key::F2,
61 => Key::F3,
62 => Key::F4,
63 => Key::F5,
64 => Key::F6,
65 => Key::F7,
66 => Key::F8,
67 => Key::F9,
68 => Key::F10,
69 => Key::NumLock,
70 => Key::ScrollLock,
71 => Key::Kp7,
72 => Key::Kp8,
73 => Key::Kp9,
74 => Key::Kpminus,
75 => Key::Kp4,
76 => Key::Kp5,
77 => Key::Kp6,
78 => Key::Kpplus,
79 => Key::Kp1,
80 => Key::Kp2,
81 => Key::Kp3,
82 => Key::Kp0,
83 => Key::Kpdot,
84 => Key::Zenkakuhankaku,
85 => Key::PoundDisplaced,
86 => Key::F11,
87 => Key::F12,
88 => Key::Ro,
89 => Key::Katakana,
90 => Key::Hiragana,
91 => Key::Henkan,
92 => Key::Katakanahiragana,
93 => Key::Muhenkan,
94 => Key::Kpjpcomma,
95 => Key::Kpenter,
96 => Key::RightCtrl,
97 => Key::Kpslash,
98 => Key::Sysrq,
99 => Key::RightAlt,
100 => Key::LineFeed,
101 => Key::Home,
102 => Key::Up,
103 => Key::PageUp,
104 => Key::Left,
105 => Key::Right,
106 => Key::End,
107 => Key::Down,
108 => Key::PageDown,
109 => Key::Insert,
110 => Key::Delete,
111 => Key::Macro,
112 => Key::Mute,
113 => Key::VolumeDown,
114 => Key::VolumeUp,
115 => Key::Power,
116 => Key::Kpequal,
117 => Key::Kpplusminus,
118 => Key::Pause,
119 => Key::Scale,
120 => Key::Kpcomma,
121 => Key::Hangeul,
122 => Key::Hanguel,
123 => Key::Hanja,
124 => Key::Yen,
125 => Key::LeftMeta,
126 => Key::RightMeta,
127 => Key::Compose,
128 => Key::Stop,
129 => Key::Again,
130 => Key::Props,
131 => Key::Undo,
132 => Key::Front,
133 => Key::Copy,
134 => Key::Open,
135 => Key::Paste,
136 => Key::Find,
137 => Key::Cut,
138 => Key::Help,
139 => Key::Menu,
140 => Key::Calc,
141 => Key::Setup,
142 => Key::Sleep,
143 => Key::Wakeup,
144 => Key::File,
145 => Key::SendFile,
146 => Key::DeleteFile,
147 => Key::Xfer,
148 => Key::Prog1,
149 => Key::Prog2,
150 => Key::Www,
151 => Key::Msdos,
152 => Key::Coffee,
153 => Key::RotateDisplay,
154 => Key::CycleWindows,
155 => Key::Mail,
156 => Key::Bookmarks,
157 => Key::Computer,
158 => Key::Back,
159 => Key::Forward,
160 => Key::CloseCD,
161 => Key::EjectCD,
162 => Key::EjectCloseCD,
163 => Key::NextSong,
164 => Key::PlayPause,
165 => Key::PreviousSong,
166 => Key::StopCD,
167 => Key::Record,
168 => Key::Rewind,
169 => Key::Phone,
170 => Key::Iso,
171 => Key::Config,
172 => Key::Homepage,
173 => Key::Refresh,
174 => Key::Exit,
175 => Key::Move,
176 => Key::Edit,
177 => Key::ScrollUp,
178 => Key::ScrollDown,
179 => Key::Kpleftparen,
180 => Key::Kprightparen,
181 => Key::New,
182 => Key::Redo,
183 => Key::F13,
184 => Key::F14,
185 => Key::F15,
186 => Key::F16,
187 => Key::F17,
188 => Key::F18,
189 => Key::F19,
190 => Key::F20,
191 => Key::F21,
192 => Key::F22,
193 => Key::F23,
194 => Key::F24,
200 => Key::PlayCD,
201 => Key::PauseCD,
202 => Key::Prog3,
203 => Key::Prog4,
204 => Key::Dashboard,
205 => Key::Suspend,
206 => Key::Close,
207 => Key::Play,
208 => Key::FastForward,
209 => Key::BassBoost,
210 => Key::Print,
211 => Key::Hp,
212 => Key::Camera,
213 => Key::Sound,
214 => Key::Question,
215 => Key::Email,
216 => Key::Chat,
217 => Key::Search,
218 => Key::Connect,
219 => Key::Finance,
220 => Key::Sport,
221 => Key::Shop,
222 => Key::Alterase,
223 => Key::Cancel,
224 => Key::BrightnessDown,
225 => Key::BrightnessUp,
226 => Key::Media,
227 => Key::SwitchVideoMode,
228 => Key::Kbdillumtoggle,
229 => Key::Kbdillumdown,
230 => Key::Kbdillumup,
231 => Key::Send,
232 => Key::Reply,
233 => Key::ForwardMail,
234 => Key::Save,
235 => Key::Documents,
236 => Key::Battery,
237 => Key::BlueTooth,
238 => Key::Wlan,
239 => Key::Uwb,
240 => Key::Unknown,
241 => Key::VideoNext,
242 => Key::VideoPrev,
243 => Key::BrightnessCycle,
244 => Key::BrightnessAuto,
245 => Key::DisplayOff,
246 => Key::Wwan,
247 => Key::RFkill,
248 => Key::MicMute,
_ => panic!("Key from u8 failed."),
}
}
}
|
mod common;
#[test]
#[cfg(feature = "devkit-arm-tests")]
pub fn test_branch() {
let (cpu, _mem) = common::execute_arm(
"b",
"
mov r0, #5
b _exit
mov r0, #8 @ should not be executed
",
);
assert_eq!(cpu.registers.read(0), 5);
}
#[test]
#[cfg(feature = "devkit-arm-tests")]
pub fn test_branch_and_link() {
let (cpu, _mem) = common::execute_arm(
"bl",
"
ldr r1, =skipped
mov r0, #5
bl _exit
skipped:
mov r0, #8 @ should not be executed
",
);
assert_eq!(cpu.registers.read(0), 5);
assert_eq!(cpu.registers.read(14), cpu.registers.read(1));
}
#[test]
#[cfg(feature = "devkit-arm-tests")]
pub fn test_branch_and_exchange() {
let (cpu, _mem) = common::execute_arm(
"bx-to-arm",
"
ldr r1, =location
mov r0, #5
bx r1
mov r0, #3
location:
nop
",
);
assert_eq!(cpu.registers.read(0), 5);
let (cpu, _mem) = common::execute_arm(
"bx-to-thumb",
"
ldr r1, =location
orr r1, #1
mov r0, #5
bx r1
mov r0, #3
.thumb
location:
nop
",
);
assert_eq!(cpu.registers.read(0), 5);
}
|
use anyhow::Error;
use env_logger::Env;
use log::{error, info};
use structopt::StructOpt;
use rodio::Sink;
use std::path::PathBuf;
fn main() {
env_logger::from_env(Env::default().default_filter_or("info")).init();
let opts = Opts::from_args();
let status = match opts.command {
Command::Convert { input } => decode_to_file(input),
Command::Play { input } => play_file(input),
};
if let Err(e) = status {
log_error(e);
std::process::exit(1);
}
}
fn decode_to_file(input: PathBuf) -> Result<(), Error> {
let decoder = ffmpeg_decoder::Decoder::open(&input)?;
let samples = decoder.collect::<Vec<i16>>();
let samples_u8 =
unsafe { std::slice::from_raw_parts(samples.as_ptr() as *const u8, samples.len() * 2) };
let mut out_path: PathBuf = input;
out_path.set_extension("raw");
std::fs::write(&out_path, samples_u8)?;
info!(
"File successfully decoded, converted and saved to: {:?}",
out_path
);
Ok(())
}
fn play_file(input: PathBuf) -> Result<(), Error> {
let decoder = ffmpeg_decoder::Decoder::open(&input)?;
let device = rodio::default_output_device().unwrap();
let sink = Sink::new(&device);
sink.append(decoder);
sink.play();
sink.sleep_until_end();
Ok(())
}
fn log_error(e: Error) {
error!("{}", e);
}
#[derive(StructOpt)]
#[structopt(
name = "libav-decoder-cli",
about = "Convert input audio file sample format to signed 16bit"
)]
struct Opts {
#[structopt(subcommand)]
command: Command,
}
#[derive(StructOpt)]
enum Command {
/// Convert file and save as `.raw` alongside input file
Convert {
/// Input audio file
#[structopt(parse(from_os_str))]
input: PathBuf,
},
/// Play input file
Play {
/// Input audio file
#[structopt(parse(from_os_str))]
input: PathBuf,
},
}
|
use rocksdb::{ColumnFamilyOptions, DBOptions, Writable, DB};
use super::tempdir_with_prefix;
#[test]
pub fn test_ttl() {
let path = tempdir_with_prefix("_rust_rocksdb_ttl_test");
let path_str = path.path().to_str().unwrap();
// should be able to open db with ttl
{
let mut opts = DBOptions::new();
let cf_opts = ColumnFamilyOptions::new();
let ttl = 10;
opts.create_if_missing(true);
let mut db = match DB::open_cf_with_ttl(
opts,
path.path().to_str().unwrap(),
vec![("default", cf_opts)],
&[ttl],
) {
Ok(db) => {
println!("successfully opened db with ttl");
db
}
Err(e) => panic!("failed to open db with ttl: {}", e),
};
match db.create_cf("cf1") {
Ok(_) => println!("cf1 created successfully"),
Err(e) => {
panic!("could not create column family: {}", e);
}
}
assert_eq!(db.cf_names(), vec!["default", "cf1"]);
match db.create_cf("cf2") {
Ok(_) => println!("cf2 created successfully"),
Err(e) => {
panic!("could not create column family: {}", e);
}
}
assert_eq!(db.cf_names(), vec!["default", "cf1", "cf2"]);
drop(db);
}
// should be able to write, read over a cf with the length of ttls equals to that of cfs
{
let db = match DB::open_cf_with_ttl(
DBOptions::new(),
path_str,
vec![
("cf1", ColumnFamilyOptions::new()),
("cf2", ColumnFamilyOptions::new()),
("default", ColumnFamilyOptions::new()),
],
&[10, 10, 10],
) {
Ok(db) => {
println!("successfully opened cf with ttl");
db
}
Err(e) => panic!("failed to open cf with ttl: {}", e),
};
let cf1 = db.cf_handle("cf1").unwrap();
assert!(db.put_cf(cf1, b"k1", b"v1").is_ok());
assert!(db.get_cf(cf1, b"k1").unwrap().unwrap().to_utf8().unwrap() == "v1");
let p = db.put_cf(cf1, b"k1", b"a");
assert!(p.is_ok());
}
// should be able to write, read over a cf with the length of ttls equals to that of cfs.
// default cf could be with ttl 0 if it is not in cfds
{
let db = match DB::open_cf_with_ttl(
DBOptions::new(),
path_str,
vec![
("cf1", ColumnFamilyOptions::new()),
("cf2", ColumnFamilyOptions::new()),
],
&[10, 10],
) {
Ok(db) => {
println!("successfully opened cf with ttl");
db
}
Err(e) => panic!("failed to open cf with ttl: {}", e),
};
let cf1 = db.cf_handle("cf1").unwrap();
assert!(db.put_cf(cf1, b"k1", b"v1").is_ok());
assert!(db.get_cf(cf1, b"k1").unwrap().unwrap().to_utf8().unwrap() == "v1");
let p = db.put_cf(cf1, b"k1", b"a");
assert!(p.is_ok());
}
// should fail to open cf with ttl when the length of ttls not equal to that of cfs
{
let _db = match DB::open_cf_with_ttl(
DBOptions::new(),
path_str,
vec![
("cf1", ColumnFamilyOptions::new()),
("cf2", ColumnFamilyOptions::new()),
],
&[10],
) {
Ok(_) => panic!(
"should not have opened DB successfully with ttl \
when the length of ttl not equal to that of cfs"
),
Err(e) => assert!(e.starts_with("the length of ttls not equal to length of cfs")),
};
}
// should fail to open cf with ttl when the length of ttls not equal to that of cfs
// when default is in cfds, it's ttl must be supplied
{
let _db = match DB::open_cf_with_ttl(
DBOptions::new(),
path_str,
vec![
("cf1", ColumnFamilyOptions::new()),
("cf2", ColumnFamilyOptions::new()),
("default", ColumnFamilyOptions::new()),
],
&[10, 10],
) {
Ok(_) => panic!(
"should not have opened DB successfully with ttl \
when the length of ttl not equal to that of cfs"
),
Err(e) => assert!(e.starts_with("the length of ttls not equal to length of cfs")),
};
}
}
|
use std::io::Write;
mod life {
extern crate std;
extern crate rand;
use self::rand::Rng; // ???
use std::io::{Write,Read};
use std::error::Error;
pub struct Board {
// row-major, idx = y_i * COL + x_i
data: Vec<bool>,
x: usize,
y: usize,
}
impl Board {
pub fn generate(x: usize, y: usize) -> Board {
if x == 0 || y == 0 {
panic!("Generator dim is zero!");
}
// That sure is a command
// Also I can't figure out how to get rid of the rand:Rng use statement
// I'd really rather learn full names.
Board{x: x, y: y, data:
rand::thread_rng().gen_iter::<bool>().take(x * y).collect::<Vec<bool>>()
}
}
// This should really return a result thing. But then again, so should load
pub fn save(&self, fname: &std::path::Path) {
let mut file = match std::fs::File::create(&fname) {
Ok(file) => file,
Err(why) => panic!("Couldn't create file \"{}\" because {}", fname.display(), why.description()),
};
// fmt::Display != .display it seems
// but this works, I guess.
match file.write_all(format!("{}",self).as_bytes()) {
Err(why) => panic!("Writing to \"{}\" ate it because {}", fname.display(), why.description()),
Ok(_) => println!("Saved to \"{}\"", fname.display()),
};
}
// THIS IS A HOUSE OF CARDS DOOMED TO FAIL DO NOT LOOK DIRECTLY AT IT
pub fn load(fname: &std::path::Path) -> Board {
let mut data = String::new();
{
let mut file = std::fs::File::open(fname)
.expect("FILE OPEN FAILED >:C");
file.read_to_string(&mut data)
.expect("FILE LOAD DIED >:C");
}
let mut data_lines = data.split('\n');
// it's gross, but it works to get the x and y values.
// It'll explode in new and terrifying ways if it doesn't parse right.
let header_values = data_lines.next()
.unwrap()
.split(',')
.map(|val_str| val_str.parse::<usize>().unwrap())
.collect::<Vec<usize>>();
let tot = header_values[0] * header_values[1];
if tot == 0 {
panic!("Bad dimensions!");
}
let mut file_data: Vec<bool> = Vec::with_capacity(tot);
for line in data_lines {
file_data.extend(line.chars().map(|ch| match ch {
'#' => true,
'-' => false,
_ => panic!("Unrecognized symbol \"{}\" in file!", ch),
}));
}
if file_data.len() != tot {
panic!("Expected {} but got {} from file", tot, file_data.len());
}
Board{x: header_values[0], y: header_values[1], data:file_data}
}
fn coord_map(&self, x_i: usize, y_i: usize) -> Result<usize,&'static str> {
// we never rollover/under by more than one
// expect weirdness if the x or y dim is usize's max
// Also that means you're using like all you memory and then some
// So this is your fault, really, not mine.
if x_i < self.x && y_i < self.y {
Ok((y_i * self.y) + x_i)
} else {
Err("No")
}
}
pub fn iterate(&mut self) {
let window_offsets: Vec<(isize,isize)> = vec!(
(-1,-1), ( 0,-1), ( 1,-1),
(-1, 0), ( 1, 0),
(-1, 1), ( 0, 1), ( 1, 1));
let mut next = self.data.clone();
// WHY IS THIS SO DIFFUCULT.
// you can't add negative one to an unsigned integer
// You have to subtract one
// How the hell do you use that with offsets like this
// Rust is the worst.
macro_rules! bs_math {
($a:expr, $b:expr) => {(
if $b < 0 {
$a.wrapping_sub((-$b) as usize)
} else {
$a.wrapping_add($b as usize)
}
)};
}
// could enumerate and map, but then we'd have to convert 1d => 2d
// and that involves modular arithmatic, which is gross
let mut current_pos = 0; // save a little time calculating this over and over
for yi in 0..self.y {
for xi in 0..self.x {
next[current_pos] = match window_offsets.iter().map(
|&(dx, dy)| match self.coord_map(bs_math!(xi, dx), bs_math!(yi, dy)) {
Ok(coord) => match self.data[coord] {
true => 1,
false => 0,
},
Err(_) => 0,
}
)
.sum::<usize>() { // 2 = maintain, 3 = alive, else dead
2 => self.data[current_pos],
3 => true,
_ => false,
};
//println!("{},{} => {}", xi, yi, next[current_pos]);
current_pos += 1;
}
}
self.data = next;
}
}
// allows easy printing of struct without just relying on debug stuff
impl std::fmt::Display for Board {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
let mut board_view: String = self.data.chunks(self.x)
.map(|row_data| row_data.iter()
.map(|&value| match value {
true => "#",
false => "-",
}))
.fold(String::with_capacity((self.x + 1) * self.y), |mut acc, cur| {
acc.extend(cur);
acc.push('\n');
acc
});
// THE SHAME
board_view.pop();
// consider removing x,y since it's data duplication
// But it makes parsling slightly easier
write!(f, "{},{}\n{}", self.x, self.y, board_view)
}
}
}
fn main_menu() {
'main_menu: loop {
print!("(G)enerate, (L)oad, (E)xit: ");
std::io::stdout().flush()
.expect("FLUSH ATE IT >:C");
let mut sel = String::new();
std::io::stdin().read_line(&mut sel)
.expect("READLINE ATE IT >:C");
//sel.pop(); // remove newline, etc
let mut board: life::Board;
match sel.trim() {
"g" | "G" => {
'gen: loop {
let mut x_str = String::new();
print!("X dim: ");
std::io::stdout().flush()
.expect("FLUSH ATE IT >:C");
std::io::stdin().read_line(&mut x_str)
.expect("READLINE ATE IT >:C");
let x_trim = x_str.trim();
let x_val = match x_trim.parse::<usize>() {
Ok(x_val) => x_val,
Err(_) => {
println!("Could not parse \"{}\"", x_trim);
continue;
},
};
let mut y_str = String::new();
print!("Y dim: ");
std::io::stdout().flush()
.expect("FLUSH ATE IT >:C");
std::io::stdin().read_line(&mut y_str)
.expect("READLINE ATE IT >:C");
let y_trim = y_str.trim();
let y_val = match y_trim.parse::<usize>() {
Ok(y_val) => y_val,
Err(_) => {
println!("Could not parse \"{}\"", y_trim);
continue;
},
};
board = life::Board::generate(x_val, y_val);
break;
}
},
"l" | "L" => {
let mut fname_str = String::new();
print!("File: ");
std::io::stdout().flush()
.expect("FLUSH ATE IT >:C");
std::io::stdin().read_line(&mut fname_str)
.expect("READLINE FUKKIN ATE IT >:C");
board = life::Board::load(std::path::Path::new(fname_str.trim()));
},
"e" | "E" => {
return;
},
val @ _ => {
println!("\"{}\" unrecognized.", val);
continue;
}
};
'op_menu: loop {
println!("{}",board);
print!("(I)terate, (S)ave, (B)ack: ");
std::io::stdout().flush()
.expect("FLUSH ATE IT >:C");
// UGH SHADOWING I KNOW
let mut sel = String::new();
std::io::stdin().read_line(&mut sel)
.expect("READLINE FUKKIN ATE IT >:C");
match sel.trim() {
"i" | "I" => {
board.iterate();
},
"s" | "S" => {
let mut fname_str = String::new();
print!("File: ");
std::io::stdout().flush()
.expect("FLUSH ATE IT >:C");
std::io::stdin().read_line(&mut fname_str)
.expect("READLINE FUKKIN ATE IT >:C");
board.save(std::path::Path::new(fname_str.trim()));
},
"b" | "B" => {
break;
},
val @ _ => {
println!("\"{}\" unrecognized.", val);
continue;
}
};
}
// back to main menu!
}
}
fn main() {
main_menu()
}
|
pub trait TryRef<T> {
fn try_ref(&self) -> Option<&T>;
}
pub trait TryMut<T> {
fn try_mut(&mut self) -> Option<&mut T>;
}
|
/*
Copyright (c) 2023 Uber Technologies, Inc.
<p>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
<p>http://www.apache.org/licenses/LICENSE-2.0
<p>Unless required by applicable law or agreed to in writing, software distributed under the
License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
express or implied. See the License for the specific language governing permissions and
limitations under the License.
*/
use std::{
collections::{HashMap, VecDeque},
path::{Path, PathBuf},
};
use colored::Colorize;
use itertools::Itertools;
use log::{debug, error};
use tree_sitter::{InputEdit, Node, Parser, Tree};
use crate::{
models::capture_group_patterns::CGPattern,
models::rule_graph::{GLOBAL, PARENT},
utilities::tree_sitter_utilities::{
get_node_for_range, get_replace_range, get_tree_sitter_edit, number_of_errors,
},
};
use super::{
edit::Edit,
matches::{Match, Range},
piranha_arguments::PiranhaArguments,
rule::InstantiatedRule,
rule_store::RuleStore,
};
use getset::{CopyGetters, Getters, MutGetters, Setters};
// Maintains the updated source code content and AST of the file
#[derive(Clone, Getters, CopyGetters, MutGetters, Setters)]
pub(crate) struct SourceCodeUnit {
// The tree representing the file
ast: Tree,
// The original content of a file
#[get = "pub"]
#[set = "pub(crate)"]
original_content: String,
// The content of a file
#[get = "pub"]
#[set = "pub(crate)"]
code: String,
// The tag substitution cache.
// This map is looked up to instantiate new rules.
#[get = "pub"]
substitutions: HashMap<String, String>,
// The path to the source code.
#[get = "pub"]
path: PathBuf,
// Rewrites applied to this source code unit
#[get = "pub"]
#[get_mut = "pub"]
rewrites: Vec<Edit>,
// Matches for the read_only rules in this source code unit
#[get = "pub"]
#[get_mut = "pub"]
matches: Vec<(String, Match)>,
// Piranha Arguments passed by the user
#[get = "pub"]
piranha_arguments: PiranhaArguments,
}
impl SourceCodeUnit {
pub(crate) fn new(
parser: &mut Parser, code: String, substitutions: &HashMap<String, String>, path: &Path,
piranha_arguments: &PiranhaArguments,
) -> Self {
let ast = parser.parse(&code, None).expect("Could not parse code");
let source_code_unit = Self {
ast,
original_content: code.to_string(),
code,
substitutions: substitutions.clone(),
path: path.to_path_buf(),
rewrites: Vec::new(),
matches: Vec::new(),
piranha_arguments: piranha_arguments.clone(),
};
// Panic if allow dirty ast is false and the tree is syntactically incorrect
if !piranha_arguments.allow_dirty_ast() && source_code_unit._number_of_errors() > 0 {
error!("{}: {}", "Syntax Error".red(), path.to_str().unwrap().red());
_ = &source_code_unit._panic_for_syntax_error();
}
source_code_unit
}
pub(crate) fn root_node(&self) -> Node<'_> {
self.ast.root_node()
}
/// Will apply the `rule` to all of its occurrences in the source code unit.
fn apply_rule(
&mut self, rule: InstantiatedRule, rules_store: &mut RuleStore, parser: &mut Parser,
scope_query: &Option<CGPattern>,
) {
loop {
if !self._apply_rule(rule.clone(), rules_store, parser, scope_query) {
break;
}
}
}
/// Applies the rule to the first match in the source code
/// This is implements the main algorithm of piranha.
/// Parameters:
/// * `rule` : the rule to be applied
/// * `rule_store`: contains the input rule graph.
///
/// Algorithm:
/// * check if the rule is match only
/// ** IF not (i.e. it is a rewrite):
/// *** Get the first match of the rule for the file
/// (We only get the first match because the idea is that we will apply this change, and keep calling this method `_apply_rule` until all
/// matches have been exhaustively updated.
/// *** Apply the rewrite
/// *** Update the substitution table
/// *** Propagate the change
/// ** Else (i.e. it is a match only rule):
/// *** Get all the matches, and for each match
/// *** Update the substitution table
/// *** Propagate the change
fn _apply_rule(
&mut self, rule: InstantiatedRule, rule_store: &mut RuleStore, parser: &mut Parser,
scope_query: &Option<CGPattern>,
) -> bool {
let scope_node = self.get_scope_node(scope_query, rule_store);
let mut query_again = false;
// When rule is a "rewrite" rule :
// Update the first match of the rewrite rule
// Add mappings to the substitution
// Propagate each applied edit. The next rule will be applied relative to the application of this edit.
if !rule.rule().is_match_only_rule() {
if let Some(edit) = self.get_edit(&rule, rule_store, scope_node, true) {
self.rewrites_mut().push(edit.clone());
query_again = true;
// Add all the (code_snippet, tag) mapping to the substitution table.
self.substitutions.extend(edit.p_match().matches().clone());
// Apply edit_1
let applied_ts_edit = self.apply_edit(&edit, parser);
self.propagate(get_replace_range(applied_ts_edit), rule, rule_store, parser);
}
}
// When rule is a "match-only" rule :
// Get all the matches
// Add mappings to the substitution
// Propagate each match. Note that, we pass a identity edit (where old range == new range) in to the propagate logic.
// The next edit will be applied relative to the identity edit.
else {
for m in self.get_matches(&rule, rule_store, scope_node, true) {
self.matches_mut().push((rule.name(), m.clone()));
// In this scenario we pass the match and replace range as the range of the match `m`
// This is equivalent to propagating an identity rule
// i.e. a rule that replaces the matched code with itself
// Note that, here we DO NOT invoke the `_apply_edit` method and only update the `substitutions`
// By NOT invoking this we simulate the application of an identity rule
//
self.substitutions.extend(m.matches().clone());
self.propagate(*m.range(), rule.clone(), rule_store, parser);
}
}
query_again
}
/// This is the propagation logic of the Piranha's main algorithm.
/// Parameters:
/// * `applied_ts_edit` - it's(`rule`'s) application site (in terms of replacement range)
/// * `rule` - The `rule` that was just applied
/// * `rule_store` - contains the input "rule graph"
/// * `parser` - parser for the language
/// Algorithm:
///
/// (i) Lookup the `rule_store` and get all the (next) rules that could be after applying the current rule (`rule`).
/// * We will receive the rules grouped by scope: `GLOBAL` and `PARENT` are applicable to each language. However, other scopes are determined
/// based on the `<language>/scope_config.toml`.
/// (ii) Add the `GLOBAL` rule to the global rule list in the `rule_store` (This will be performed in the next iteration)
/// (iii) Apply the local cleanup i.e. `PARENT` scoped rules
/// (iv) Go to step 1 (and repeat this for the applicable parent scoped rule. Do this until, no parent scoped rule is applicable.) (recursive)
/// (iv) Apply the rules based on custom language specific scopes (as defined in `<language>/scope_config.toml`) (recursive)
///
fn propagate(
&mut self, replace_range: Range, rule: InstantiatedRule, rules_store: &mut RuleStore,
parser: &mut Parser,
) {
let mut current_replace_range = replace_range;
let mut current_rule = rule.name();
let mut next_rules_stack: VecDeque<(CGPattern, InstantiatedRule)> = VecDeque::new();
// Perform the parent edits, while queueing the Method and Class level edits.
// let file_level_scope_names = [METHOD, CLASS];
loop {
debug!("Current Rule: {current_rule}");
// Get all the (next) rules that could be after applying the current rule (`rule`).
let next_rules_by_scope = self
.piranha_arguments
.rule_graph()
.get_next(¤t_rule, self.substitutions());
debug!(
"\n{}",
&next_rules_by_scope
.iter()
.map(|(k, v)| {
let rules = v.iter().map(|f| f.name()).join(", ");
format!("Next Rules:\nScope {k} \nRules {rules}").blue()
})
.join("\n")
);
// Adds rules of scope != ["Parent", "Global"] to the stack
self.add_rules_to_stack(
&next_rules_by_scope,
current_replace_range,
rules_store,
&mut next_rules_stack,
);
// Add Global rules as seed rules
for r in &next_rules_by_scope[GLOBAL] {
rules_store.add_to_global_rules(r);
}
// Process the parent
// Find the rules to be applied in the "Parent" scope that match any parent (context) of the changed node in the previous edit
if let Some(edit) = self.get_edit_for_context(
*current_replace_range.start_byte(),
*current_replace_range.end_byte(),
rules_store,
&next_rules_by_scope[PARENT],
) {
self.rewrites_mut().push(edit.clone());
debug!(
"\n{}",
format!(
"Cleaning up the context, by applying the rule - {}",
edit.matched_rule()
)
.green()
);
// Apply the matched rule to the parent
let applied_edit = self.apply_edit(&edit, parser);
current_replace_range = get_replace_range(applied_edit);
current_rule = edit.matched_rule().to_string();
// Add the (tag, code_snippet) mapping to substitution table.
self.substitutions.extend(edit.p_match().matches().clone());
} else {
// No more parents found for cleanup
break;
}
}
// Apply the next rules from the stack
for (sq, rle) in &next_rules_stack {
self.apply_rule(rle.clone(), rules_store, parser, &Some(sq.clone()));
}
}
/// Adds the "Method" and "Class" scoped next rules to the queue.
fn add_rules_to_stack(
&mut self, next_rules_by_scope: &HashMap<String, Vec<InstantiatedRule>>,
current_match_range: Range, rules_store: &mut RuleStore,
stack: &mut VecDeque<(CGPattern, InstantiatedRule)>,
) {
for (scope_level, rules) in next_rules_by_scope {
// Scope level is not "PArent" or "Global"
if ![PARENT, GLOBAL].contains(&scope_level.as_str()) {
for rule in rules {
let scope_query = self.get_scope_query(
scope_level,
*current_match_range.start_byte(),
*current_match_range.end_byte(),
rules_store,
);
// Add Method and Class scoped rules to the queue
stack.push_front((scope_query, rule.clone()));
}
}
}
}
fn get_scope_node(&self, scope_query: &Option<CGPattern>, rules_store: &mut RuleStore) -> Node {
// Get scope node
// let mut scope_node = self.root_node();
if let Some(query_str) = scope_query {
// Apply the scope query in the source code and get the appropriate node
let scope_pattern = rules_store.query(query_str);
if let Some(p_match) = scope_pattern.get_match(&self.root_node(), self.code(), true) {
return get_node_for_range(
self.root_node(),
*p_match.range().start_byte(),
*p_match.range().end_byte(),
);
}
}
self.root_node()
}
/// Apply all `rules` sequentially.
pub(crate) fn apply_rules(
&mut self, rules_store: &mut RuleStore, rules: &[InstantiatedRule], parser: &mut Parser,
scope_query: Option<CGPattern>,
) {
for rule in rules {
self.apply_rule(rule.to_owned(), rules_store, parser, &scope_query)
}
self.perform_delete_consecutive_new_lines();
}
/// Applies an edit to the source code unit
/// # Arguments
/// * `replace_range` - the range of code to be replaced
/// * `replacement_str` - the replacement string
/// * `parser`
///
/// # Returns
/// The `edit:InputEdit` performed.
///
/// Note - Causes side effect. - Updates `self.ast` and `self.code`
pub(crate) fn apply_edit(&mut self, edit: &Edit, parser: &mut Parser) -> InputEdit {
// Get the tree_sitter's input edit representation
let (new_source_code, ts_edit) = get_tree_sitter_edit(self.code.clone(), edit);
// Apply edit to the tree
let number_of_errors = self._number_of_errors();
self.ast.edit(&ts_edit);
self._replace_file_contents_and_re_parse(&new_source_code, parser, true);
// Panic if the number of errors increased after the edit
if self._number_of_errors() > number_of_errors {
self._panic_for_syntax_error();
}
ts_edit
}
fn _panic_for_syntax_error(&self) {
let msg = format!(
"Produced syntactically incorrect source code {}",
self.code()
);
panic!("{}", msg);
}
/// Returns the number of errors in this source code unit
fn _number_of_errors(&self) -> usize {
number_of_errors(&self.root_node())
}
// Replaces the content of the current file with the new content and re-parses the AST
/// # Arguments
/// * `replacement_content` - new content of file
/// * `parser`
/// * `is_current_ast_edited` : have you invoked `edit` on the current AST ?
/// Note - Causes side effect. - Updates `self.ast` and `self.code`
pub(crate) fn _replace_file_contents_and_re_parse(
&mut self, replacement_content: &str, parser: &mut Parser, is_current_ast_edited: bool,
) {
let prev_tree = if is_current_ast_edited {
Some(&self.ast)
} else {
None
};
// Create a new updated tree from the previous tree
let new_tree = parser
.parse(replacement_content, prev_tree)
.expect("Could not generate new tree!");
self.ast = new_tree;
self.code = replacement_content.to_string();
}
pub(crate) fn global_substitutions(&self) -> HashMap<String, String> {
self
.substitutions()
.iter()
.filter(|e| e.0.starts_with(self.piranha_arguments.global_tag_prefix()))
.map(|(a, b)| (a.to_string(), b.to_string()))
.collect()
}
}
#[cfg(test)]
#[path = "unit_tests/source_code_unit_test.rs"]
mod source_code_unit_test;
|
use std::cmp::min;
use rand::Rng;
use rand::distributions::{ Distribution, Uniform };
use crate::prelude::*;
use super::*;
pub struct StratifiedSampler {
pixel: PixelSamplerData,
x_samples: u32,
y_samples: u32,
jitter: bool,
dimensions: u32,
}
impl StratifiedSampler {
pub fn new(x_samples: u32, y_samples: u32, jitter: bool, dimensions: u32, seed: i32) -> Self {
let samples = u64::from(x_samples) * u64::from(y_samples);
let pixel = PixelSamplerData::new(samples, dimensions, seed);
Self {
pixel,
x_samples,
y_samples,
jitter,
dimensions,
}
}
}
impl Sampler for StratifiedSampler {
fn create_new(&self, seed: i32) -> Box<dyn Sampler + Send + 'static> {
let sampler = Self::new(
self.x_samples,
self.y_samples,
self.jitter,
self.dimensions,
seed,
);
Box::new(sampler)
}
fn samples_per_pixel(&self) -> u64 {
self.pixel.samples_per_pixel()
}
fn start_pixel(&mut self, pixel: Point2i) {
let samples_per_pixel = self.pixel.samples_per_pixel();
// generate single stratified samples for pixel
let samples_1d = self.pixel.samples_1d();
for i in 0..samples_1d.len() {
let mut sample = stratified_sample_1d(self.x_samples * self.y_samples, self.jitter, self.pixel.get_rng());
shuffle(&mut sample, 1, self.pixel.get_rng());
let pixel = self.pixel.samples_1d_mut();
pixel[i] = sample;
}
let samples_2d = self.pixel.samples_2d();
for i in 0..samples_2d.len() {
let mut sample = stratified_sample_2d(self.x_samples, self.y_samples, self.jitter, self.pixel.get_rng());
shuffle(&mut sample, 1, self.pixel.get_rng());
let pixel = self.pixel.samples_2d_mut();
pixel[i] = sample;
}
// generate arrays of stratified samples for pixel
let samples_1d_sizes = self.pixel.samples_array_1d_sizes();
for i in 0..samples_1d_sizes.len() {
for _ in 0..samples_per_pixel {
let count = self.pixel.samples_array_1d_sizes()[i];
let mut sample = stratified_sample_1d(count, self.jitter, self.pixel.get_rng());
shuffle(&mut sample, 1, self.pixel.get_rng());
let pixel = self.pixel.samples_array_1d_mut();
pixel[i] = sample;
}
}
let samples_2d_sizes = self.pixel.samples_array_2d_sizes();
for i in 0..samples_2d_sizes.len() {
for _ in 0..samples_per_pixel {
let count = self.pixel.samples_array_2d_sizes()[i];
let sample = latin_hypercube(count as usize, 2, self.pixel.get_rng());
let pixel = self.pixel.samples_array_2d_mut();
pixel[i] = sample
.chunks(2)
.map(|c| Point2f::new(c[0], c[1]))
.collect();
}
}
self.pixel.start_pixel(pixel)
}
fn set_sample_number(&mut self, n: u64) -> bool {
self.pixel.set_sample_number(n)
}
fn start_next_sample(&mut self) -> bool {
self.pixel.start_next_sample()
}
fn get_1d(&mut self) -> Float {
self.pixel.get_1d()
}
fn get_2d(&mut self) -> Point2f {
self.pixel.get_2d()
}
fn request_1d_vec(&mut self, n: u32) {
self.pixel.request_1d_vec(n)
}
fn request_2d_vec(&mut self, n: u32) {
self.pixel.request_2d_vec(n)
}
fn get_1d_vec(&mut self, n: u32) -> Option<Vec<Float>> {
self.pixel.get_1d_vec(n)
}
fn get_2d_vec(&mut self, n: u32) -> Option<Vec<Point2f>> {
self.pixel.get_2d_vec(n)
}
}
fn jitter_value(jitter: bool, rng: &mut impl Rng) -> Float {
if jitter { rng.gen() } else { float(0.5) }
}
fn stratified_sample_1d(samples: u32, jitter: bool, rng: &mut impl Rng) -> Vec<Float> {
let inv_n = float(1.0) / float(samples);
let mut vec = Vec::with_capacity(samples as usize);
for i in 0..samples {
let i = float(i);
let delta = jitter_value(jitter, rng);
vec.push(min((i + delta) * inv_n, float(ONE_MINUS_EPSILON)));
}
vec
}
fn stratified_sample_2d(x_samples: u32, y_samples: u32, jitter: bool, rng: &mut impl Rng) -> Vec<Point2f> {
let inv_x = float(1.0) / float(x_samples);
let inv_y = float(1.0) / float(y_samples);
let mut vec = Vec::with_capacity(x_samples as usize * y_samples as usize);
for y in 0..y_samples {
for x in 0..x_samples {
let x = float(x);
let y = float(y);
let jx = jitter_value(jitter, rng);
let jy = jitter_value(jitter, rng);
let x = min((x + jx) * inv_x, float(ONE_MINUS_EPSILON));
let y = min((y + jy) * inv_y, float(ONE_MINUS_EPSILON));
vec.push(Point2f::new(x, y));
}
}
vec
}
fn shuffle<T>(vec: &mut Vec<T>, dimensions: usize, rng: &mut impl Rng) {
for i in 0..vec.len() {
let bounds = Uniform::from(0..vec.len() - i);
let other = i + bounds.sample(rng);
for j in 0..dimensions {
vec.swap(dimensions * i + j, dimensions * other + j);
}
}
}
fn latin_hypercube(n: usize, dimensions: usize, rng: &mut impl Rng) -> Vec<Float> {
let inv_n = float(1.0) / float(n);
let mut vec = Vec::with_capacity(n * dimensions);
for i in 0..n {
for j in 0..dimensions {
let sj = (float(i) + rng.gen()) * inv_n;
vec[dimensions * i + j] = min(sj, float(ONE_MINUS_EPSILON));
}
}
for i in 0..dimensions {
for j in 0..n {
let bounds = Uniform::from(0..(n - j));
let other = j + bounds.sample(rng);
vec.swap(n * j + i, n * other + i);
}
}
vec
}
|
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - GICV virtual machine control register"]
pub gicv_ctlr: GICV_CTLR,
#[doc = "0x04 - GICV VM priority mask register"]
pub gicv_pmr: GICV_PMR,
#[doc = "0x08 - GICV VM binary point register"]
pub gicv_bpr: GICV_BPR,
#[doc = "0x0c - GICV VM interrupt acknowledge register"]
pub gicv_iar: GICV_IAR,
#[doc = "0x10 - GICV VM end of interrupt register"]
pub gicv_eoir: GICV_EOIR,
#[doc = "0x14 - GICV VM running priority register"]
pub gicv_rpr: GICV_RPR,
#[doc = "0x18 - GICV VM highest priority pending interrupt register"]
pub gicv_hppir: GICV_HPPIR,
#[doc = "0x1c - GICV VM aliased binary point register"]
pub gicv_abpr: GICV_ABPR,
#[doc = "0x20 - GICV VM aliased interrupt register"]
pub gicv_aiar: GICV_AIAR,
#[doc = "0x24 - GICV VM aliased end of interrupt register"]
pub gicv_aeoir: GICV_AEOIR,
#[doc = "0x28 - GICV VM aliased highest priority pending interrupt register"]
pub gicv_ahppir: GICV_AHPPIR,
_reserved11: [u8; 0xa4],
#[doc = "0xd0 - The GICV_APR0 is an alias of GICH_APR."]
pub gicv_apr0: GICV_APR0,
_reserved12: [u8; 0x28],
#[doc = "0xfc - The GICV_IIDR is an alias of GICC_IIDR."]
pub gicv_iidr: GICV_IIDR,
_reserved13: [u8; 0x0f00],
#[doc = "0x1000 - GICV VM deactivate interrupt register"]
pub gicv_dir: GICV_DIR,
}
#[doc = "GICV_CTLR (rw) register accessor: GICV virtual machine control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`gicv_ctlr::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 [`gicv_ctlr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`gicv_ctlr`]
module"]
pub type GICV_CTLR = crate::Reg<gicv_ctlr::GICV_CTLR_SPEC>;
#[doc = "GICV virtual machine control register"]
pub mod gicv_ctlr;
#[doc = "GICV_PMR (rw) register accessor: GICV VM priority mask register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`gicv_pmr::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 [`gicv_pmr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`gicv_pmr`]
module"]
pub type GICV_PMR = crate::Reg<gicv_pmr::GICV_PMR_SPEC>;
#[doc = "GICV VM priority mask register"]
pub mod gicv_pmr;
#[doc = "GICV_BPR (rw) register accessor: GICV VM binary point register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`gicv_bpr::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 [`gicv_bpr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`gicv_bpr`]
module"]
pub type GICV_BPR = crate::Reg<gicv_bpr::GICV_BPR_SPEC>;
#[doc = "GICV VM binary point register"]
pub mod gicv_bpr;
#[doc = "GICV_IAR (r) register accessor: GICV VM interrupt acknowledge register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`gicv_iar::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`gicv_iar`]
module"]
pub type GICV_IAR = crate::Reg<gicv_iar::GICV_IAR_SPEC>;
#[doc = "GICV VM interrupt acknowledge register"]
pub mod gicv_iar;
#[doc = "GICV_EOIR (w) register accessor: GICV VM end of interrupt register\n\nYou can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`gicv_eoir::W`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`gicv_eoir`]
module"]
pub type GICV_EOIR = crate::Reg<gicv_eoir::GICV_EOIR_SPEC>;
#[doc = "GICV VM end of interrupt register"]
pub mod gicv_eoir;
#[doc = "GICV_RPR (r) register accessor: GICV VM running priority register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`gicv_rpr::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`gicv_rpr`]
module"]
pub type GICV_RPR = crate::Reg<gicv_rpr::GICV_RPR_SPEC>;
#[doc = "GICV VM running priority register"]
pub mod gicv_rpr;
#[doc = "GICV_HPPIR (r) register accessor: GICV VM highest priority pending interrupt register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`gicv_hppir::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`gicv_hppir`]
module"]
pub type GICV_HPPIR = crate::Reg<gicv_hppir::GICV_HPPIR_SPEC>;
#[doc = "GICV VM highest priority pending interrupt register"]
pub mod gicv_hppir;
#[doc = "GICV_ABPR (rw) register accessor: GICV VM aliased binary point register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`gicv_abpr::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 [`gicv_abpr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`gicv_abpr`]
module"]
pub type GICV_ABPR = crate::Reg<gicv_abpr::GICV_ABPR_SPEC>;
#[doc = "GICV VM aliased binary point register"]
pub mod gicv_abpr;
#[doc = "GICV_AIAR (r) register accessor: GICV VM aliased interrupt register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`gicv_aiar::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`gicv_aiar`]
module"]
pub type GICV_AIAR = crate::Reg<gicv_aiar::GICV_AIAR_SPEC>;
#[doc = "GICV VM aliased interrupt register"]
pub mod gicv_aiar;
#[doc = "GICV_AEOIR (w) register accessor: GICV VM aliased end of interrupt register\n\nYou can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`gicv_aeoir::W`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`gicv_aeoir`]
module"]
pub type GICV_AEOIR = crate::Reg<gicv_aeoir::GICV_AEOIR_SPEC>;
#[doc = "GICV VM aliased end of interrupt register"]
pub mod gicv_aeoir;
#[doc = "GICV_AHPPIR (r) register accessor: GICV VM aliased highest priority pending interrupt register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`gicv_ahppir::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`gicv_ahppir`]
module"]
pub type GICV_AHPPIR = crate::Reg<gicv_ahppir::GICV_AHPPIR_SPEC>;
#[doc = "GICV VM aliased highest priority pending interrupt register"]
pub mod gicv_ahppir;
#[doc = "GICV_APR0 (rw) register accessor: The GICV_APR0 is an alias of GICH_APR.\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`gicv_apr0::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 [`gicv_apr0::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`gicv_apr0`]
module"]
pub type GICV_APR0 = crate::Reg<gicv_apr0::GICV_APR0_SPEC>;
#[doc = "The GICV_APR0 is an alias of GICH_APR."]
pub mod gicv_apr0;
#[doc = "GICV_IIDR (r) register accessor: The GICV_IIDR is an alias of GICC_IIDR.\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`gicv_iidr::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`gicv_iidr`]
module"]
pub type GICV_IIDR = crate::Reg<gicv_iidr::GICV_IIDR_SPEC>;
#[doc = "The GICV_IIDR is an alias of GICC_IIDR."]
pub mod gicv_iidr;
#[doc = "GICV_DIR (w) register accessor: GICV VM deactivate interrupt register\n\nYou can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`gicv_dir::W`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`gicv_dir`]
module"]
pub type GICV_DIR = crate::Reg<gicv_dir::GICV_DIR_SPEC>;
#[doc = "GICV VM deactivate interrupt register"]
pub mod gicv_dir;
|
use std::io::prelude::*;
use std::net::TcpStream;
use std::sync::MutexGuard;
use regex::Regex;
use database::Db;
use response::serve_error_page;
use response::serve_guest_json;
use response::serve_guests_json;
use response::serve_index_page;
use response::serve_method_not_allowed;
#[derive(Debug)]
struct Request {
method: String,
path: String,
host: String,
user_agent: String,
headers: Vec<String>,
body: String,
}
// Special enum for wrapping a could-be-string-could-be-json response
#[derive(Debug)]
pub enum Response {
S(String),
J(Vec<String>),
}
fn parse_request(buf: &[u8]) -> Request {
let stream_string = String::from_utf8_lossy(&buf[..]);
let mut splitted = stream_string.split(" ");
let mut split_vec = splitted.collect::<Vec<&str>>();
let method = String::from(split_vec[0]);
let path = String::from(split_vec[1]);
splitted = stream_string.split("\r\n");
split_vec = splitted.collect::<Vec<&str>>();
let host = String::from(split_vec[1]).replace("Host: ", "");
let user_agent = String::from(split_vec[2]).replace("User-Agent: ", "");
let headers = parse_headers(&split_vec);
let body = parse_body(&split_vec);
let parsed_request = Request {
method,
path,
host,
user_agent,
headers,
body,
};
parsed_request
}
fn parse_headers(rvec: &Vec<&str>) -> Vec<String> {
// Copy vector so you can mutate it safely
let mut new_vec = rvec.clone();
new_vec.remove(0);
new_vec.remove(1);
// Find empty vec entry, indicates the start of the body
let header_end_index = new_vec.iter().position(|x| *x == "").unwrap();
// Remove empty string indicating end of headers
new_vec.remove(header_end_index);
// Now header_end_index is the start of the body
new_vec.remove(header_end_index);
// Cannot have a Vec<&str> in a struct because &str size cannot be known
// at compile time, so we have to convert it into a Vec<String> here to
// be passed back into the struct
let returned_vec: Vec<String> = new_vec.iter().map(|s| String::from(&**s)).collect();
returned_vec
}
fn parse_body(rvec: &Vec<&str>) -> String {
// Copy vector so you can mutate it safely
let mut new_vec = rvec.clone();
// Find empty vec entry, indicates the start of the body
let body_start_index = new_vec.iter().position(|x| *x == "").unwrap();
// Remove empty string indicating end of headers
new_vec.remove(body_start_index);
// .replace is used to remove empty data left over from
// buffer initialisation
String::from(new_vec[body_start_index]).replace("\u{0}", "")
}
fn handle_routing(method: &str, path: &str, conn: MutexGuard<Db>) -> (String, Response) {
let re_g = Regex::new(r"^/guests$").unwrap();
let re_g_id = Regex::new(r"^/guests/.*$").unwrap();
if path == "/" {
if method == "GET" {
return serve_index_page();
} else {
return serve_method_not_allowed();
}
} else if re_g.is_match(path) {
if method == "GET" {
return serve_guests_json(conn);
} else {
return serve_method_not_allowed();
}
} else if re_g_id.is_match(path) {
if method == "GET" {
return serve_guest_json(conn, path);
} else {
return serve_method_not_allowed();
}
} else {
return serve_error_page();
}
}
pub fn handle_connection(mut stream: TcpStream, conn: MutexGuard<Db>) {
// Arbitrary buffer length - hopefully long enough to capture all
// headers, even if there's shit-loads of them
let mut buffer = [0; 512];
stream.read(&mut buffer).unwrap();
let request_obj = parse_request(&buffer);
println!("{:?}", request_obj);
let (status_line, contents) = handle_routing(&request_obj.method, &request_obj.path, conn);
match contents {
Response::S(string) => {
let response = format!("{}{}", status_line, string);
stream.write(response.as_bytes()).unwrap();
}
Response::J(json) => {
let status = format!("{}", status_line);
let mut mapped_json = json.join(",");
stream.write(status.as_bytes()).unwrap();
stream.write(mapped_json.as_bytes()).unwrap();
}
};
stream.flush().unwrap();
}
|
use ::stark_hash::{stark_hash, StarkHash};
use criterion::{black_box, criterion_group, criterion_main, Criterion};
pub fn criterion_benchmark(c: &mut Criterion) {
// These are the test vectors also used in tests, taken from
// https://github.com/starkware-libs/crypto-cpp/blob/master/src/starkware/crypto/pedersen_hash_test.cc
let e0 = "03d937c035c878245caf64531a5756109c53068da139362728feb561405371cb";
let e1 = "0208a0a10250e382e1e4bbe2880906c2791bf6275695e02fbbc6aeff9cd8b31a";
let e0 = StarkHash::from_hex_str(e0).unwrap();
let e1 = StarkHash::from_hex_str(e1).unwrap();
c.bench_function("pedersen_hash", |b| {
b.iter(|| {
black_box(stark_hash(e0, e1));
});
});
}
criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);
|
fn main() {
let f1 = 3 + 2;
// let f2 = 3 + 2.0; // error no implementation for `{integer} + {float}`
let f3 = 3.0 + 2.0;
println!("{:?}", f1);
// println!("{:?}", f2);
println!("{:?}", f3);
}
|
#[doc = "Reader of register SNIFF_CTRL"]
pub type R = crate::R<u32, super::SNIFF_CTRL>;
#[doc = "Writer for register SNIFF_CTRL"]
pub type W = crate::W<u32, super::SNIFF_CTRL>;
#[doc = "Register SNIFF_CTRL `reset()`'s with value 0"]
impl crate::ResetValue for super::SNIFF_CTRL {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `OUT_INV`"]
pub type OUT_INV_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `OUT_INV`"]
pub struct OUT_INV_W<'a> {
w: &'a mut W,
}
impl<'a> OUT_INV_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 << 11)) | (((value as u32) & 0x01) << 11);
self.w
}
}
#[doc = "Reader of field `OUT_REV`"]
pub type OUT_REV_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `OUT_REV`"]
pub struct OUT_REV_W<'a> {
w: &'a mut W,
}
impl<'a> OUT_REV_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 << 10)) | (((value as u32) & 0x01) << 10);
self.w
}
}
#[doc = "Reader of field `BSWAP`"]
pub type BSWAP_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `BSWAP`"]
pub struct BSWAP_W<'a> {
w: &'a mut W,
}
impl<'a> BSWAP_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 << 9)) | (((value as u32) & 0x01) << 9);
self.w
}
}
#[doc = "\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum CALC_A {
#[doc = "0: Calculate a CRC-32 (IEEE802.3 polynomial)"]
CRC32 = 0,
#[doc = "1: Calculate a CRC-32 (IEEE802.3 polynomial) with bit reversed data"]
CRC32R = 1,
#[doc = "2: Calculate a CRC-16-CCITT"]
CRC16 = 2,
#[doc = "3: Calculate a CRC-16-CCITT with bit reversed data"]
CRC16R = 3,
#[doc = "14: XOR reduction over all data. == 1 if the total 1 population count is odd."]
EVEN = 14,
#[doc = "15: Calculate a simple 32-bit checksum (addition with a 32 bit accumulator)"]
SUM = 15,
}
impl From<CALC_A> for u8 {
#[inline(always)]
fn from(variant: CALC_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `CALC`"]
pub type CALC_R = crate::R<u8, CALC_A>;
impl CALC_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<u8, CALC_A> {
use crate::Variant::*;
match self.bits {
0 => Val(CALC_A::CRC32),
1 => Val(CALC_A::CRC32R),
2 => Val(CALC_A::CRC16),
3 => Val(CALC_A::CRC16R),
14 => Val(CALC_A::EVEN),
15 => Val(CALC_A::SUM),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `CRC32`"]
#[inline(always)]
pub fn is_crc32(&self) -> bool {
*self == CALC_A::CRC32
}
#[doc = "Checks if the value of the field is `CRC32R`"]
#[inline(always)]
pub fn is_crc32r(&self) -> bool {
*self == CALC_A::CRC32R
}
#[doc = "Checks if the value of the field is `CRC16`"]
#[inline(always)]
pub fn is_crc16(&self) -> bool {
*self == CALC_A::CRC16
}
#[doc = "Checks if the value of the field is `CRC16R`"]
#[inline(always)]
pub fn is_crc16r(&self) -> bool {
*self == CALC_A::CRC16R
}
#[doc = "Checks if the value of the field is `EVEN`"]
#[inline(always)]
pub fn is_even(&self) -> bool {
*self == CALC_A::EVEN
}
#[doc = "Checks if the value of the field is `SUM`"]
#[inline(always)]
pub fn is_sum(&self) -> bool {
*self == CALC_A::SUM
}
}
#[doc = "Write proxy for field `CALC`"]
pub struct CALC_W<'a> {
w: &'a mut W,
}
impl<'a> CALC_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: CALC_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "Calculate a CRC-32 (IEEE802.3 polynomial)"]
#[inline(always)]
pub fn crc32(self) -> &'a mut W {
self.variant(CALC_A::CRC32)
}
#[doc = "Calculate a CRC-32 (IEEE802.3 polynomial) with bit reversed data"]
#[inline(always)]
pub fn crc32r(self) -> &'a mut W {
self.variant(CALC_A::CRC32R)
}
#[doc = "Calculate a CRC-16-CCITT"]
#[inline(always)]
pub fn crc16(self) -> &'a mut W {
self.variant(CALC_A::CRC16)
}
#[doc = "Calculate a CRC-16-CCITT with bit reversed data"]
#[inline(always)]
pub fn crc16r(self) -> &'a mut W {
self.variant(CALC_A::CRC16R)
}
#[doc = "XOR reduction over all data. == 1 if the total 1 population count is odd."]
#[inline(always)]
pub fn even(self) -> &'a mut W {
self.variant(CALC_A::EVEN)
}
#[doc = "Calculate a simple 32-bit checksum (addition with a 32 bit accumulator)"]
#[inline(always)]
pub fn sum(self) -> &'a mut W {
self.variant(CALC_A::SUM)
}
#[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 << 5)) | (((value as u32) & 0x0f) << 5);
self.w
}
}
#[doc = "Reader of field `DMACH`"]
pub type DMACH_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `DMACH`"]
pub struct DMACH_W<'a> {
w: &'a mut W,
}
impl<'a> DMACH_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 << 1)) | (((value as u32) & 0x0f) << 1);
self.w
}
}
#[doc = "Reader of field `EN`"]
pub type EN_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `EN`"]
pub struct EN_W<'a> {
w: &'a mut W,
}
impl<'a> EN_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
}
}
impl R {
#[doc = "Bit 11 - If set, the result appears inverted (bitwise complement) when read. This does not affect the way the checksum is calculated; the result is transformed on-the-fly between the result register and the bus."]
#[inline(always)]
pub fn out_inv(&self) -> OUT_INV_R {
OUT_INV_R::new(((self.bits >> 11) & 0x01) != 0)
}
#[doc = "Bit 10 - If set, the result appears bit-reversed when read. This does not affect the way the checksum is calculated; the result is transformed on-the-fly between the result register and the bus."]
#[inline(always)]
pub fn out_rev(&self) -> OUT_REV_R {
OUT_REV_R::new(((self.bits >> 10) & 0x01) != 0)
}
#[doc = "Bit 9 - Locally perform a byte reverse on the sniffed data, before feeding into checksum.\\n\\n Note that the sniff hardware is downstream of the DMA channel byteswap performed in the read master: if channel CTRL_BSWAP and SNIFF_CTRL_BSWAP are both enabled, their effects cancel from the sniffer's point of view."]
#[inline(always)]
pub fn bswap(&self) -> BSWAP_R {
BSWAP_R::new(((self.bits >> 9) & 0x01) != 0)
}
#[doc = "Bits 5:8"]
#[inline(always)]
pub fn calc(&self) -> CALC_R {
CALC_R::new(((self.bits >> 5) & 0x0f) as u8)
}
#[doc = "Bits 1:4 - DMA channel for Sniffer to observe"]
#[inline(always)]
pub fn dmach(&self) -> DMACH_R {
DMACH_R::new(((self.bits >> 1) & 0x0f) as u8)
}
#[doc = "Bit 0 - Enable sniffer"]
#[inline(always)]
pub fn en(&self) -> EN_R {
EN_R::new((self.bits & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 11 - If set, the result appears inverted (bitwise complement) when read. This does not affect the way the checksum is calculated; the result is transformed on-the-fly between the result register and the bus."]
#[inline(always)]
pub fn out_inv(&mut self) -> OUT_INV_W {
OUT_INV_W { w: self }
}
#[doc = "Bit 10 - If set, the result appears bit-reversed when read. This does not affect the way the checksum is calculated; the result is transformed on-the-fly between the result register and the bus."]
#[inline(always)]
pub fn out_rev(&mut self) -> OUT_REV_W {
OUT_REV_W { w: self }
}
#[doc = "Bit 9 - Locally perform a byte reverse on the sniffed data, before feeding into checksum.\\n\\n Note that the sniff hardware is downstream of the DMA channel byteswap performed in the read master: if channel CTRL_BSWAP and SNIFF_CTRL_BSWAP are both enabled, their effects cancel from the sniffer's point of view."]
#[inline(always)]
pub fn bswap(&mut self) -> BSWAP_W {
BSWAP_W { w: self }
}
#[doc = "Bits 5:8"]
#[inline(always)]
pub fn calc(&mut self) -> CALC_W {
CALC_W { w: self }
}
#[doc = "Bits 1:4 - DMA channel for Sniffer to observe"]
#[inline(always)]
pub fn dmach(&mut self) -> DMACH_W {
DMACH_W { w: self }
}
#[doc = "Bit 0 - Enable sniffer"]
#[inline(always)]
pub fn en(&mut self) -> EN_W {
EN_W { w: self }
}
}
|
#[doc = "Reader of register INIT_SCN_ADV_RX_FIFO"]
pub type R = crate::R<u32, super::INIT_SCN_ADV_RX_FIFO>;
#[doc = "Reader of field `ADV_SCAN_RSP_RX_DATA`"]
pub type ADV_SCAN_RSP_RX_DATA_R = crate::R<u16, u16>;
impl R {
#[doc = "Bits 0:15 - IO mapped FIFO of depth 64, to store ADV and SCAN_RSP header and payload received by the scanner. The RSSI value at the time of reception of this packet is also stored. Firmware reads from the same address to read out consecutive words of data. Note: The 16 bit header is first loaded to the advertise channel data receive FIFO followed by the payload data and then 16 bit RSSI."]
#[inline(always)]
pub fn adv_scan_rsp_rx_data(&self) -> ADV_SCAN_RSP_RX_DATA_R {
ADV_SCAN_RSP_RX_DATA_R::new((self.bits & 0xffff) as u16)
}
}
|
use std::collections::HashMap;
/*
The key observation, for efficiently solving the second part of the puzzle (part 1 is
easily done with any sensible algorithm), is that a vector/array of all numbers - which
is the most obvious data structure to use - is unnecessary to keep. All we ever need to know
is the most recent index of each number (if any). This suggests using a hashmap, whose keys
are the numbers, and values are the most recent index. Actually, the easiest way is for the
value to be *pairs* of the *two* most recent indices. The algorithm then becomes very
easy (provided one remembers to not update the hashmap until after the difference has been
calculated!), as well as efficient even up to 30 million iterations (and beyond)!
(Actually this solution still ran for a few minutes (although down to just 15-20 seconds when compiled
in release mode) - must have some inefficiencies that can be
improved. But still reasonable, and vastly better than using vectors!)
*/
#[derive(Debug)]
struct IndexPair(Option<usize>, Option<usize>);
impl IndexPair {
fn new() -> IndexPair {
IndexPair(None, None)
}
fn has_both(&self) -> bool {
if let IndexPair(Some(_), Some(_)) = self {
true
} else {
false
}
}
fn new_index(&self, index: usize) -> IndexPair {
let IndexPair(_, new) = self;
IndexPair(*new, Some(index))
}
fn index_difference(&self) -> usize {
let IndexPair(old, new) = self;
new.unwrap() - old.unwrap()
}
}
#[derive(Debug)]
struct Numbers {
used: HashMap<usize, IndexPair>,
index: usize,
last: usize,
}
impl Numbers {
fn new() -> Numbers {
Numbers {
used: HashMap::new(),
index: 0,
last: 0,
}
}
fn insert(&mut self, num: usize) -> () {
self.last = num;
let old_pair = self.used.get(&num);
let new = &IndexPair::new();
let old_pair = match old_pair {
None => new,
Some(p) => p,
};
let new_pair = old_pair.new_index(self.index);
self.used.insert(num, new_pair);
self.index += 1;
}
fn from_vec(nums: Vec<usize>) -> Numbers {
let mut new = Numbers::new();
for num in nums {
new.insert(num);
}
new
}
fn next(&mut self) -> () {
let new = &IndexPair::new();
let last_index_pair = self.used.get(&self.last).unwrap_or(new);
let new_val = if last_index_pair.has_both() {
last_index_pair.index_difference()
} else {
0
};
let new_index_pair = self.used.get(&new_val).unwrap_or(new).new_index(self.index);
self.used.insert(new_val, new_index_pair);
self.last = new_val;
self.index += 1;
}
fn get_nth(&mut self, n: usize) -> usize {
for _ in (self.index + 1)..(n + 1) {
self.next();
}
self.last
}
}
fn solve_part_1(nums: &mut Numbers) -> usize {
nums.get_nth(2020)
}
pub fn part_1() -> usize {
let mut nums = Numbers::from_vec(vec![12, 1, 16, 3, 11, 0]);
solve_part_1(&mut nums)
}
fn solve_part_2(nums: &mut Numbers) -> usize {
nums.get_nth(30000000)
}
pub fn part_2() -> usize {
let mut nums = Numbers::from_vec(vec![12, 1, 16, 3, 11, 0]);
solve_part_2(&mut nums)
}
|
mod character_program;
mod cube_program;
mod mask_check_program;
mod mask_program;
mod table_grid_program;
mod table_texture_program;
mod tablemask_program;
use super::webgl;
pub use character_program::CharacterProgram;
pub use cube_program::CubeProgram;
pub use mask_check_program::MaskCheckProgram;
pub use mask_program::MaskProgram;
pub use table_grid_program::TableGridProgram;
pub use table_texture_program::TableTextureProgram;
pub use tablemask_program::TablemaskProgram;
fn compile_shader(
context: &web_sys::WebGlRenderingContext,
shader_source: &str,
shader_type: u32,
) -> Result<web_sys::WebGlShader, String> {
let shader = context
.create_shader(shader_type)
.ok_or_else(|| String::from("Unable to create shader object"))?;
context.shader_source(&shader, shader_source);
context.compile_shader(&shader);
if context
.get_shader_parameter(&shader, web_sys::WebGlRenderingContext::COMPILE_STATUS)
.as_bool()
.unwrap_or(false)
{
Ok(shader)
} else {
Err(context
.get_shader_info_log(&shader)
.unwrap_or_else(|| String::from("Unknown error creating shader")))
}
}
fn link_program(
context: &web_sys::WebGlRenderingContext,
vertex_shader: &web_sys::WebGlShader,
fragment_shader: &web_sys::WebGlShader,
) -> Result<web_sys::WebGlProgram, String> {
let program = context
.create_program()
.ok_or_else(|| String::from("Unable to create shader object"))?;
context.attach_shader(&program, vertex_shader);
context.attach_shader(&program, fragment_shader);
context.link_program(&program);
if context
.get_program_parameter(&program, web_sys::WebGlRenderingContext::LINK_STATUS)
.as_bool()
.unwrap_or(false)
{
Ok(program)
} else {
Err(context
.get_program_info_log(&program)
.unwrap_or_else(|| String::from("Unknown error creating program object")))
}
}
|
fn main() {
let mut a : [i32; 3]= [1, 2, 3];
a[2] = 100;
println!("{:?}", a);
} |
pub fn run() {
// Print to console
println!("Hello from print.rs file");
// Basic formatting
println!("{} is from {}", "Vaibhav", "Shimla");
// Positional Arguments
println!("{0} is from {1} and {0} like to {2}", "Vaibhav", "Shimla", "Code");
// Named Arguments
println!("{name} like to play {activity}", name = "Vaibhav", activity = "Hocus Pocus");
// Placeholder traits
println!("Bin: {:b}, Hex: {:x}, Octal: {:o}", 10, 10, 10);
// Placeholder for debug trait
println!("{:?}", (12, true, "hello"));
// Basic math
println!("10 + 10 = {}", 10 + 10);
}
|
#[doc = "Register `VCTR40` reader"]
pub type R = crate::R<VCTR40_SPEC>;
#[doc = "Register `VCTR40` writer"]
pub type W = crate::W<VCTR40_SPEC>;
#[doc = "Field `B1280` reader - B1280"]
pub type B1280_R = crate::BitReader;
#[doc = "Field `B1280` writer - B1280"]
pub type B1280_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1281` reader - B1281"]
pub type B1281_R = crate::BitReader;
#[doc = "Field `B1281` writer - B1281"]
pub type B1281_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1282` reader - B1282"]
pub type B1282_R = crate::BitReader;
#[doc = "Field `B1282` writer - B1282"]
pub type B1282_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1283` reader - B1283"]
pub type B1283_R = crate::BitReader;
#[doc = "Field `B1283` writer - B1283"]
pub type B1283_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1284` reader - B1284"]
pub type B1284_R = crate::BitReader;
#[doc = "Field `B1284` writer - B1284"]
pub type B1284_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1285` reader - B1285"]
pub type B1285_R = crate::BitReader;
#[doc = "Field `B1285` writer - B1285"]
pub type B1285_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1286` reader - B1286"]
pub type B1286_R = crate::BitReader;
#[doc = "Field `B1286` writer - B1286"]
pub type B1286_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1287` reader - B1287"]
pub type B1287_R = crate::BitReader;
#[doc = "Field `B1287` writer - B1287"]
pub type B1287_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1288` reader - B1288"]
pub type B1288_R = crate::BitReader;
#[doc = "Field `B1288` writer - B1288"]
pub type B1288_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1289` reader - B1289"]
pub type B1289_R = crate::BitReader;
#[doc = "Field `B1289` writer - B1289"]
pub type B1289_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1290` reader - B1290"]
pub type B1290_R = crate::BitReader;
#[doc = "Field `B1290` writer - B1290"]
pub type B1290_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1291` reader - B1291"]
pub type B1291_R = crate::BitReader;
#[doc = "Field `B1291` writer - B1291"]
pub type B1291_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1292` reader - B1292"]
pub type B1292_R = crate::BitReader;
#[doc = "Field `B1292` writer - B1292"]
pub type B1292_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1293` reader - B1293"]
pub type B1293_R = crate::BitReader;
#[doc = "Field `B1293` writer - B1293"]
pub type B1293_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1294` reader - B1294"]
pub type B1294_R = crate::BitReader;
#[doc = "Field `B1294` writer - B1294"]
pub type B1294_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1295` reader - B1295"]
pub type B1295_R = crate::BitReader;
#[doc = "Field `B1295` writer - B1295"]
pub type B1295_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1296` reader - B1296"]
pub type B1296_R = crate::BitReader;
#[doc = "Field `B1296` writer - B1296"]
pub type B1296_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1297` reader - B1297"]
pub type B1297_R = crate::BitReader;
#[doc = "Field `B1297` writer - B1297"]
pub type B1297_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1298` reader - B1298"]
pub type B1298_R = crate::BitReader;
#[doc = "Field `B1298` writer - B1298"]
pub type B1298_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1299` reader - B1299"]
pub type B1299_R = crate::BitReader;
#[doc = "Field `B1299` writer - B1299"]
pub type B1299_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1300` reader - B1300"]
pub type B1300_R = crate::BitReader;
#[doc = "Field `B1300` writer - B1300"]
pub type B1300_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1301` reader - B1301"]
pub type B1301_R = crate::BitReader;
#[doc = "Field `B1301` writer - B1301"]
pub type B1301_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1302` reader - B1302"]
pub type B1302_R = crate::BitReader;
#[doc = "Field `B1302` writer - B1302"]
pub type B1302_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1303` reader - B1303"]
pub type B1303_R = crate::BitReader;
#[doc = "Field `B1303` writer - B1303"]
pub type B1303_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1304` reader - B1304"]
pub type B1304_R = crate::BitReader;
#[doc = "Field `B1304` writer - B1304"]
pub type B1304_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1305` reader - B1305"]
pub type B1305_R = crate::BitReader;
#[doc = "Field `B1305` writer - B1305"]
pub type B1305_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1306` reader - B1306"]
pub type B1306_R = crate::BitReader;
#[doc = "Field `B1306` writer - B1306"]
pub type B1306_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1307` reader - B1307"]
pub type B1307_R = crate::BitReader;
#[doc = "Field `B1307` writer - B1307"]
pub type B1307_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1308` reader - B1308"]
pub type B1308_R = crate::BitReader;
#[doc = "Field `B1308` writer - B1308"]
pub type B1308_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1309` reader - B1309"]
pub type B1309_R = crate::BitReader;
#[doc = "Field `B1309` writer - B1309"]
pub type B1309_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1310` reader - B1310"]
pub type B1310_R = crate::BitReader;
#[doc = "Field `B1310` writer - B1310"]
pub type B1310_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1311` reader - B1311"]
pub type B1311_R = crate::BitReader;
#[doc = "Field `B1311` writer - B1311"]
pub type B1311_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bit 0 - B1280"]
#[inline(always)]
pub fn b1280(&self) -> B1280_R {
B1280_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - B1281"]
#[inline(always)]
pub fn b1281(&self) -> B1281_R {
B1281_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 2 - B1282"]
#[inline(always)]
pub fn b1282(&self) -> B1282_R {
B1282_R::new(((self.bits >> 2) & 1) != 0)
}
#[doc = "Bit 3 - B1283"]
#[inline(always)]
pub fn b1283(&self) -> B1283_R {
B1283_R::new(((self.bits >> 3) & 1) != 0)
}
#[doc = "Bit 4 - B1284"]
#[inline(always)]
pub fn b1284(&self) -> B1284_R {
B1284_R::new(((self.bits >> 4) & 1) != 0)
}
#[doc = "Bit 5 - B1285"]
#[inline(always)]
pub fn b1285(&self) -> B1285_R {
B1285_R::new(((self.bits >> 5) & 1) != 0)
}
#[doc = "Bit 6 - B1286"]
#[inline(always)]
pub fn b1286(&self) -> B1286_R {
B1286_R::new(((self.bits >> 6) & 1) != 0)
}
#[doc = "Bit 7 - B1287"]
#[inline(always)]
pub fn b1287(&self) -> B1287_R {
B1287_R::new(((self.bits >> 7) & 1) != 0)
}
#[doc = "Bit 8 - B1288"]
#[inline(always)]
pub fn b1288(&self) -> B1288_R {
B1288_R::new(((self.bits >> 8) & 1) != 0)
}
#[doc = "Bit 9 - B1289"]
#[inline(always)]
pub fn b1289(&self) -> B1289_R {
B1289_R::new(((self.bits >> 9) & 1) != 0)
}
#[doc = "Bit 10 - B1290"]
#[inline(always)]
pub fn b1290(&self) -> B1290_R {
B1290_R::new(((self.bits >> 10) & 1) != 0)
}
#[doc = "Bit 11 - B1291"]
#[inline(always)]
pub fn b1291(&self) -> B1291_R {
B1291_R::new(((self.bits >> 11) & 1) != 0)
}
#[doc = "Bit 12 - B1292"]
#[inline(always)]
pub fn b1292(&self) -> B1292_R {
B1292_R::new(((self.bits >> 12) & 1) != 0)
}
#[doc = "Bit 13 - B1293"]
#[inline(always)]
pub fn b1293(&self) -> B1293_R {
B1293_R::new(((self.bits >> 13) & 1) != 0)
}
#[doc = "Bit 14 - B1294"]
#[inline(always)]
pub fn b1294(&self) -> B1294_R {
B1294_R::new(((self.bits >> 14) & 1) != 0)
}
#[doc = "Bit 15 - B1295"]
#[inline(always)]
pub fn b1295(&self) -> B1295_R {
B1295_R::new(((self.bits >> 15) & 1) != 0)
}
#[doc = "Bit 16 - B1296"]
#[inline(always)]
pub fn b1296(&self) -> B1296_R {
B1296_R::new(((self.bits >> 16) & 1) != 0)
}
#[doc = "Bit 17 - B1297"]
#[inline(always)]
pub fn b1297(&self) -> B1297_R {
B1297_R::new(((self.bits >> 17) & 1) != 0)
}
#[doc = "Bit 18 - B1298"]
#[inline(always)]
pub fn b1298(&self) -> B1298_R {
B1298_R::new(((self.bits >> 18) & 1) != 0)
}
#[doc = "Bit 19 - B1299"]
#[inline(always)]
pub fn b1299(&self) -> B1299_R {
B1299_R::new(((self.bits >> 19) & 1) != 0)
}
#[doc = "Bit 20 - B1300"]
#[inline(always)]
pub fn b1300(&self) -> B1300_R {
B1300_R::new(((self.bits >> 20) & 1) != 0)
}
#[doc = "Bit 21 - B1301"]
#[inline(always)]
pub fn b1301(&self) -> B1301_R {
B1301_R::new(((self.bits >> 21) & 1) != 0)
}
#[doc = "Bit 22 - B1302"]
#[inline(always)]
pub fn b1302(&self) -> B1302_R {
B1302_R::new(((self.bits >> 22) & 1) != 0)
}
#[doc = "Bit 23 - B1303"]
#[inline(always)]
pub fn b1303(&self) -> B1303_R {
B1303_R::new(((self.bits >> 23) & 1) != 0)
}
#[doc = "Bit 24 - B1304"]
#[inline(always)]
pub fn b1304(&self) -> B1304_R {
B1304_R::new(((self.bits >> 24) & 1) != 0)
}
#[doc = "Bit 25 - B1305"]
#[inline(always)]
pub fn b1305(&self) -> B1305_R {
B1305_R::new(((self.bits >> 25) & 1) != 0)
}
#[doc = "Bit 26 - B1306"]
#[inline(always)]
pub fn b1306(&self) -> B1306_R {
B1306_R::new(((self.bits >> 26) & 1) != 0)
}
#[doc = "Bit 27 - B1307"]
#[inline(always)]
pub fn b1307(&self) -> B1307_R {
B1307_R::new(((self.bits >> 27) & 1) != 0)
}
#[doc = "Bit 28 - B1308"]
#[inline(always)]
pub fn b1308(&self) -> B1308_R {
B1308_R::new(((self.bits >> 28) & 1) != 0)
}
#[doc = "Bit 29 - B1309"]
#[inline(always)]
pub fn b1309(&self) -> B1309_R {
B1309_R::new(((self.bits >> 29) & 1) != 0)
}
#[doc = "Bit 30 - B1310"]
#[inline(always)]
pub fn b1310(&self) -> B1310_R {
B1310_R::new(((self.bits >> 30) & 1) != 0)
}
#[doc = "Bit 31 - B1311"]
#[inline(always)]
pub fn b1311(&self) -> B1311_R {
B1311_R::new(((self.bits >> 31) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - B1280"]
#[inline(always)]
#[must_use]
pub fn b1280(&mut self) -> B1280_W<VCTR40_SPEC, 0> {
B1280_W::new(self)
}
#[doc = "Bit 1 - B1281"]
#[inline(always)]
#[must_use]
pub fn b1281(&mut self) -> B1281_W<VCTR40_SPEC, 1> {
B1281_W::new(self)
}
#[doc = "Bit 2 - B1282"]
#[inline(always)]
#[must_use]
pub fn b1282(&mut self) -> B1282_W<VCTR40_SPEC, 2> {
B1282_W::new(self)
}
#[doc = "Bit 3 - B1283"]
#[inline(always)]
#[must_use]
pub fn b1283(&mut self) -> B1283_W<VCTR40_SPEC, 3> {
B1283_W::new(self)
}
#[doc = "Bit 4 - B1284"]
#[inline(always)]
#[must_use]
pub fn b1284(&mut self) -> B1284_W<VCTR40_SPEC, 4> {
B1284_W::new(self)
}
#[doc = "Bit 5 - B1285"]
#[inline(always)]
#[must_use]
pub fn b1285(&mut self) -> B1285_W<VCTR40_SPEC, 5> {
B1285_W::new(self)
}
#[doc = "Bit 6 - B1286"]
#[inline(always)]
#[must_use]
pub fn b1286(&mut self) -> B1286_W<VCTR40_SPEC, 6> {
B1286_W::new(self)
}
#[doc = "Bit 7 - B1287"]
#[inline(always)]
#[must_use]
pub fn b1287(&mut self) -> B1287_W<VCTR40_SPEC, 7> {
B1287_W::new(self)
}
#[doc = "Bit 8 - B1288"]
#[inline(always)]
#[must_use]
pub fn b1288(&mut self) -> B1288_W<VCTR40_SPEC, 8> {
B1288_W::new(self)
}
#[doc = "Bit 9 - B1289"]
#[inline(always)]
#[must_use]
pub fn b1289(&mut self) -> B1289_W<VCTR40_SPEC, 9> {
B1289_W::new(self)
}
#[doc = "Bit 10 - B1290"]
#[inline(always)]
#[must_use]
pub fn b1290(&mut self) -> B1290_W<VCTR40_SPEC, 10> {
B1290_W::new(self)
}
#[doc = "Bit 11 - B1291"]
#[inline(always)]
#[must_use]
pub fn b1291(&mut self) -> B1291_W<VCTR40_SPEC, 11> {
B1291_W::new(self)
}
#[doc = "Bit 12 - B1292"]
#[inline(always)]
#[must_use]
pub fn b1292(&mut self) -> B1292_W<VCTR40_SPEC, 12> {
B1292_W::new(self)
}
#[doc = "Bit 13 - B1293"]
#[inline(always)]
#[must_use]
pub fn b1293(&mut self) -> B1293_W<VCTR40_SPEC, 13> {
B1293_W::new(self)
}
#[doc = "Bit 14 - B1294"]
#[inline(always)]
#[must_use]
pub fn b1294(&mut self) -> B1294_W<VCTR40_SPEC, 14> {
B1294_W::new(self)
}
#[doc = "Bit 15 - B1295"]
#[inline(always)]
#[must_use]
pub fn b1295(&mut self) -> B1295_W<VCTR40_SPEC, 15> {
B1295_W::new(self)
}
#[doc = "Bit 16 - B1296"]
#[inline(always)]
#[must_use]
pub fn b1296(&mut self) -> B1296_W<VCTR40_SPEC, 16> {
B1296_W::new(self)
}
#[doc = "Bit 17 - B1297"]
#[inline(always)]
#[must_use]
pub fn b1297(&mut self) -> B1297_W<VCTR40_SPEC, 17> {
B1297_W::new(self)
}
#[doc = "Bit 18 - B1298"]
#[inline(always)]
#[must_use]
pub fn b1298(&mut self) -> B1298_W<VCTR40_SPEC, 18> {
B1298_W::new(self)
}
#[doc = "Bit 19 - B1299"]
#[inline(always)]
#[must_use]
pub fn b1299(&mut self) -> B1299_W<VCTR40_SPEC, 19> {
B1299_W::new(self)
}
#[doc = "Bit 20 - B1300"]
#[inline(always)]
#[must_use]
pub fn b1300(&mut self) -> B1300_W<VCTR40_SPEC, 20> {
B1300_W::new(self)
}
#[doc = "Bit 21 - B1301"]
#[inline(always)]
#[must_use]
pub fn b1301(&mut self) -> B1301_W<VCTR40_SPEC, 21> {
B1301_W::new(self)
}
#[doc = "Bit 22 - B1302"]
#[inline(always)]
#[must_use]
pub fn b1302(&mut self) -> B1302_W<VCTR40_SPEC, 22> {
B1302_W::new(self)
}
#[doc = "Bit 23 - B1303"]
#[inline(always)]
#[must_use]
pub fn b1303(&mut self) -> B1303_W<VCTR40_SPEC, 23> {
B1303_W::new(self)
}
#[doc = "Bit 24 - B1304"]
#[inline(always)]
#[must_use]
pub fn b1304(&mut self) -> B1304_W<VCTR40_SPEC, 24> {
B1304_W::new(self)
}
#[doc = "Bit 25 - B1305"]
#[inline(always)]
#[must_use]
pub fn b1305(&mut self) -> B1305_W<VCTR40_SPEC, 25> {
B1305_W::new(self)
}
#[doc = "Bit 26 - B1306"]
#[inline(always)]
#[must_use]
pub fn b1306(&mut self) -> B1306_W<VCTR40_SPEC, 26> {
B1306_W::new(self)
}
#[doc = "Bit 27 - B1307"]
#[inline(always)]
#[must_use]
pub fn b1307(&mut self) -> B1307_W<VCTR40_SPEC, 27> {
B1307_W::new(self)
}
#[doc = "Bit 28 - B1308"]
#[inline(always)]
#[must_use]
pub fn b1308(&mut self) -> B1308_W<VCTR40_SPEC, 28> {
B1308_W::new(self)
}
#[doc = "Bit 29 - B1309"]
#[inline(always)]
#[must_use]
pub fn b1309(&mut self) -> B1309_W<VCTR40_SPEC, 29> {
B1309_W::new(self)
}
#[doc = "Bit 30 - B1310"]
#[inline(always)]
#[must_use]
pub fn b1310(&mut self) -> B1310_W<VCTR40_SPEC, 30> {
B1310_W::new(self)
}
#[doc = "Bit 31 - B1311"]
#[inline(always)]
#[must_use]
pub fn b1311(&mut self) -> B1311_W<VCTR40_SPEC, 31> {
B1311_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 = "MPCBBx vector register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`vctr40::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 [`vctr40::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct VCTR40_SPEC;
impl crate::RegisterSpec for VCTR40_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`vctr40::R`](R) reader structure"]
impl crate::Readable for VCTR40_SPEC {}
#[doc = "`write(|w| ..)` method takes [`vctr40::W`](W) writer structure"]
impl crate::Writable for VCTR40_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets VCTR40 to value 0xffff_ffff"]
impl crate::Resettable for VCTR40_SPEC {
const RESET_VALUE: Self::Ux = 0xffff_ffff;
}
|
use std::collections::HashMap;
fn main() {
proconio::input! {
s: String,
}
const RADIX: u32 = 10;
let cs: Vec<u32> = s.chars().map(|x| x.to_digit(RADIX).unwrap()).collect();
let n = cs.len();
if n == 1 {
if cs[0] % 8 == 0 {
println!("Yes");
return;
}
println!("No");
return;
}
if n == 2{
if (cs[0] + cs[1]*10) % 8 == 0 {
println!("Yes");
return;
}
if (cs[1] + cs[0]*10) % 8 == 0 {
println!("Yes");
return;
}
println!("No");
return;
}
if is_all_odd(cs.clone()) {
// 全て奇数の場合は8の倍数になりえない
println!("No");
return;
}
// 要素ごとのカウント
let mut map = HashMap::new();
for i in 0..n {
let counter = map.entry(cs[i]).or_insert(0);
if *counter < 3 {
// 3桁しか確認しないため
*counter += 1;
}
}
let mut cs: Vec<u32> = vec![];
for (k, v) in &map {
for _ in 0..(*v as usize){
cs.push(*k);
}
}
let n = cs.len();
// println!("{:?}", cs);
// 8の倍数は下三桁のみの確認で良い 1000 / 25 = 8
for i in 0..n {
if cs[i] % 2 == 1 {
continue;
}
for j in 0..n {
if i == j {
continue;
}
for k in 0..n {
if i == k || j == k{
continue;
}
// println!("{} {}", cs[i] + cs[j]*10 + cs[k]*100, (cs[i] + cs[j]*10 + cs[k]*100) % 8);
if (cs[i] + cs[j]*10 + cs[k]*100) % 8 == 0 {
println!("Yes");
return;
}
}
}
}
println!("No");
}
fn is_all_odd(cs: Vec<u32>) -> bool {
for c in cs{
if c % 2 == 0 {
return false;
}
}
return true;
} |
pub mod client;
pub mod rpc_mock;
pub mod rpc_request;
pub mod thin_client;
|
//! This project is used for explaining the STFT operation on real-world
//! signals. Here we first sample the acceleromater data. Sampling period is set
//! as 10 milliseconds. We also generate a Hamming window. These signals are
//! represented with x and v arrays in main.c file respectively. The input
//! signal is divided into subwindows and FFT of each subwindow is calculated by
//! the STFT function. The result is stored in the XST array.
//!
//! Requires `cargo install probe-run`
//! `cargo run --release --example 4_11_stft_accelerometer`
//!
//! Note: This is currently stack overflowing with Window larger than 16
#![no_std]
#![no_main]
use panic_break as _;
use stm32f4xx_hal as hal;
use cmsis_dsp_sys::{arm_cfft_f32, arm_cfft_sR_f32_len16, arm_cmplx_mag_f32};
use core::f32::consts::PI;
use cty::uint32_t;
use hal::{prelude::*, spi, stm32};
use itertools::Itertools;
use lis3dsh::{accelerometer::RawAccelerometer, Lis3dsh};
use micromath::F32Ext;
use rtt_target::{rprintln, rtt_init_print};
use typenum::{Sum, Unsigned};
type N = heapless::consts::U1024;
type WINDOW = heapless::consts::U16;
type WINDOWCOMPLEX = Sum<WINDOW, WINDOW>;
//todo derive this from WINDOW
const WINDOW_CONST: usize = 16;
#[cortex_m_rt::entry]
fn main() -> ! {
rtt_init_print!(BlockIfFull, 128);
let dp = stm32::Peripherals::take().unwrap();
let cp = cortex_m::peripheral::Peripherals::take().unwrap();
// Set up the system clock.
let rcc = dp.RCC.constrain();
let clocks = rcc
.cfgr
.use_hse(8.mhz()) //discovery board has 8 MHz crystal for HSE
.sysclk(168.mhz())
.freeze();
let mut delay = hal::delay::Delay::new(cp.SYST, clocks);
let gpioa = dp.GPIOA.split();
let gpioe = dp.GPIOE.split();
let sck = gpioa.pa5.into_alternate_af5().internal_pull_up(false);
let miso = gpioa.pa6.into_alternate_af5().internal_pull_up(false);
let mosi = gpioa.pa7.into_alternate_af5().internal_pull_up(false);
let spi_mode = spi::Mode {
polarity: spi::Polarity::IdleLow,
phase: spi::Phase::CaptureOnFirstTransition,
};
let spi = spi::Spi::spi1(
dp.SPI1,
(sck, miso, mosi),
spi_mode,
10.mhz().into(),
clocks,
);
let chip_select = gpioe.pe3.into_push_pull_output();
let mut lis3dsh = Lis3dsh::new_spi(spi, chip_select);
lis3dsh.init(&mut delay).unwrap();
rprintln!("reading accel");
// dont love the idea of delaying in an iterator ...
let accel = (0..N::to_usize())
.map(|_| {
while !lis3dsh.is_data_ready().unwrap() {}
let dat = lis3dsh.accel_raw().unwrap();
dat[0] as f32
})
.collect::<heapless::Vec<f32, N>>();
rprintln!("computing");
let hamming = (0..WINDOW::to_usize())
.map(|m| 0.54 - 0.46 * (2.0 * PI * m as f32 / WINDOW::to_usize() as f32).cos());
// get 64 input at a time, overlapping 32
// windowing is easier to do on slices
let overlapping_chirp_windows = Windows {
v: &accel[..],
size: WINDOW::to_usize(),
inc: WINDOW::to_usize() / 2,
};
let mut xst: heapless::Vec<[f32; WINDOW_CONST], N> = heapless::Vec::new();
let mut mag = [0f32; WINDOW_CONST];
for chirp_win in overlapping_chirp_windows {
// 64-0=64 of input to 64-64=0, so input * chirp.rev
let mut dtfsecoef = hamming
.clone()
.zip(chirp_win.iter().rev())
.map(|(v, x)| v * x)
.interleave_shortest(core::iter::repeat(0.0))
.collect::<heapless::Vec<f32, WINDOWCOMPLEX>>();
unsafe {
//Finding the FFT of window
arm_cfft_f32(&arm_cfft_sR_f32_len16, dtfsecoef.as_mut_ptr(), 0, 1);
arm_cmplx_mag_f32(
dtfsecoef.as_ptr(),
mag.as_mut_ptr(),
WINDOW_CONST as uint32_t,
);
}
xst.push(mag).ok();
}
rprintln!("xst: {:?}", xst);
// signal to probe-run to exit
loop {
cortex_m::asm::bkpt()
}
}
pub struct Windows<'a, T: 'a> {
v: &'a [T],
size: usize,
inc: usize,
}
impl<'a, T> Iterator for Windows<'a, T> {
type Item = &'a [T];
#[inline]
fn next(&mut self) -> Option<&'a [T]> {
if self.size > self.v.len() {
None
} else {
let ret = Some(&self.v[..self.size]);
self.v = &self.v[self.inc..];
ret
}
}
}
//C needs access to a sqrt fn, lets use micromath
#[no_mangle]
pub extern "C" fn sqrtf(x: f32) -> f32 {
x.sqrt()
}
|
mod msg;
mod querier;
mod query;
pub use msg::{create_swap_msg, create_swap_send_msg, TerraMsg, TerraMsgWrapper};
pub use querier::TerraQuerier;
pub use query::{SwapResponse, TaxCapResponse, TaxRateResponse, TerraQuery, TerraQueryWrapper};
// This export is added to all contracts that import this package, signifying that they require
// "terra" support on the chain they run on.
#[no_mangle]
extern "C" fn requires_terra() {}
|
use wasm_bindgen::{JsCast, JsValue};
use js_sys::{Object, Float32Array, WebAssembly};
use web_sys::console::log_1;
use super::constants::{HasBufferKind, ViewPrecision, HasViewPrecision};
#[derive(Clone, Copy, Debug)]
pub struct Data<V: View, B: HasBufferKind> {
pub buffer: B,
pub view: V,
}
#[derive(Clone, Debug)]
pub struct Float32View {
size: usize,
data: Float32Array,
}
pub trait View: HasViewPrecision {
fn length(&self) -> usize;
fn object(&self) -> &Object;
fn get_precision(&self) -> ViewPrecision;
}
impl Float32View {
pub fn create(data_raw: &[f32]) -> Result<Self, DataViewError> {
let data = Float32View::build_data(data_raw)?;
Ok(Float32View { data, size: data_raw.len() })
}
pub fn update_data(&mut self, data_raw: &[f32]) -> Result<(), DataViewError> {
self.data = Float32View::build_data(data_raw)?;
self.size = data_raw.len();
return Ok(())
}
pub fn log(&self) {
let value = JsValue::from(&self.data);
log_1(&value);
}
fn build_data(data_raw: &[f32]) -> Result<js_sys::Float32Array, DataViewError> {
let memory_buffer = wasm_bindgen::memory()
.dyn_into::<WebAssembly::Memory>()
.map_err(|_| DataViewError::FailedToCreateMemory)?
.buffer();
let data_location = data_raw.as_ptr() as u32 / 4;
let data = js_sys::Float32Array::new(&memory_buffer)
.subarray(data_location, data_location + data_raw.len() as u32);
Ok(data)
}
}
impl HasViewPrecision for Float32View {
fn view_precision_constant(&self) -> u32 {
self.get_precision().view_precision_constant()
}
}
impl View for Float32View {
fn length(&self) -> usize { self.size }
fn object(&self) -> &Object { self.data.as_ref() }
fn get_precision(&self) -> ViewPrecision {
ViewPrecision::Float
}
}
#[derive(Clone, Copy)]
pub enum DataViewError {
FailedToCreateMemory,
}
impl DataViewError {
pub fn to_string(&self) -> String {
match self {
DataViewError::FailedToCreateMemory => "Failed to create memory".to_string(),
}
}
}
|
/*
smart pointers
originate in C++
- have unique metadata
- one we will explore is the reference counting smart pointer type
- Rc<T> enables multiple owners of the same data; Box<T> and RefCell<T> have single owners
- Box<T> allows immutable or mutable borrows checked at compile time
- Rc<T> allows only immutable borrows checked at compile time
- RefCell<T> allows immutable or mutable borrows checked at runtime
- Because RefCell<T> allows mutable borrows checked at runtime, you can mutate hte value inside the RefCell<T> even when the RefCell<T> is immutable
- this is known as the _interior mutability_ pattern
*/
use::std::ops::Deref;
#[derive(Debug)]
struct MyBox<T>(T);
impl <T> Deref for MyBox<T> {
type Target = T;
fn deref(&self) -> &T {
&self.0
}
}
impl <T> MyBox<T> {
fn new(x: T) -> MyBox<T> {
MyBox(x)
}
}
fn hello(name: &str) {
println!("Hello, {}!", name);
}
struct CustomSmartPointer {
data: String,
}
impl Drop for CustomSmartPointer {
fn drop(&mut self) {
println!("Dropping CustomSmartPointer with data `{}`!", self.data)
}
}
enum List {
Cons(i32, Rc<List>),
Nil,
}
use List::{Cons, Nil};
use std::rc::Rc;
fn main() {
let mut x = 5;
let y = &mut x;
let a = Rc::new(Cons(5, Rc::new(Cons(10, Rc::new(Nil)))));
println!("count after creating a = {}", Rc::strong_count(&a));
let b = Cons(3, Rc::clone(&a));
println!("count after creating b = {}", Rc::strong_count(&a));
{
let c = Cons(4, Rc::clone(&a));
println!("count after creating c = {}", Rc::strong_count(&a));
}
println!("count after c goes out of scope = {}", Rc::strong_count(&a));
let c = CustomSmartPointer {data: String::from("my stuff") };
let d = CustomSmartPointer {data: String::from("other stuff") };
println!("CustomSmartPointers created.");
let m = MyBox::new(String::from("Rust"));
println!("{:?}", hello(&m));
let x = 5;
let y = MyBox(x);
assert_eq!(5, *y);
}
|
use crate::parser::ast::Ast;
use crate::parser::ast::AstKind;
use error::InterpreterError;
use std::io;
mod error;
pub struct Interpreter {
position: usize,
tape: Vec<u32>,
size: usize,
}
impl Interpreter {
pub fn new(tape_size: usize) -> Self {
Interpreter {
position: 0,
size: tape_size,
tape: vec![0; tape_size],
}
}
pub fn eval(&mut self, expr: Vec<Ast>) -> Result<(), InterpreterError> {
fn _eval(
_position: &mut usize,
_tape: &mut Vec<u32>,
_size: usize,
_expr: &Vec<Ast>,
) -> Result<(), InterpreterError> {
for ast in _expr.into_iter() {
match &ast.value {
AstKind::Incr => _tape[*_position] += 1,
AstKind::Decr => _tape[*_position] -= 1,
AstKind::Next => {
if *_position + 1 >= _size - 1 {
return Err(InterpreterError::buffer_overflow(ast.loc));
} else {
*_position += 1
}
}
AstKind::Prev => {
if *_position == 0 {
return Err(InterpreterError::negative_postion(ast.loc));
} else {
*_position -= 1
}
}
AstKind::Write => {
let decoded_char = std::char::from_u32(_tape[*_position]);
match decoded_char {
Some(c) => print!("{}", c),
_ => return Err(InterpreterError::cannot_decode_character(ast.loc)),
}
}
AstKind::Read => {
let mut buf_in = String::new();
match io::stdin().read_line(&mut buf_in) {
Ok(_) => (),
Err(_) => return Err(InterpreterError::cannot_read_character(ast.loc)),
};
_tape[*_position] = match buf_in.trim().parse::<u32>() {
Ok(num) => num,
Err(_) => buf_in.chars().collect::<Vec<char>>()[0] as u32,
};
}
AstKind::Loop(inner_ast) => {
while _tape[*_position] != 0 {
_eval(_position, _tape, _size, &inner_ast)?
}
}
}
}
Ok(())
}
_eval(&mut self.position, &mut self.tape, self.size, &expr)
}
}
|
use core::fmt::{self, Debug};
use crate::{
map::{Key, MaybeMap},
Bound::{self, *},
RangeBounds, Segment, SegmentMap,
};
pub mod iterators;
pub mod ops;
#[cfg(test)]
mod tests;
/// # SegmentSet
///
/// A set based on a [`SegmentMap`]. Like [`SegmentMap`], adjacent ranges will be
/// merged into a single range.
///
/// See [`SegmentMap`]'s documentation for more details on implementation. The
/// internal representation of this `struct` is is a `SegmentMap<T, ()>`
///
/// # Examples
///
/// ```
/// # use segmap::*;
/// let mut set = SegmentSet::new();
///
/// // Add some ranges
/// set.insert(0..5);
/// set.insert(5..10); // Note, this will be merged with 0..5!
/// set.insert(20..25);
///
/// // Check if a point is covered
/// assert!(set.contains(&7));
/// assert!(!set.contains(&12));
///
/// // Remove a range (or parts of some ranges)
/// assert!(set.contains(&5));
/// assert!(set.contains(&24));
/// set.remove(3..6);
/// set.remove(22..);
/// assert!(!set.contains(&5));
/// assert!(!set.contains(&24));
///
/// // Check which ranges are covered
/// assert!(set.into_iter().eq(vec![
/// Segment::from(0..3),
/// Segment::from(6..10),
/// Segment::from(20..22),
/// ]));
/// ```
///
#[derive(Clone)]
pub struct SegmentSet<T> {
pub(crate) map: SegmentMap<T, ()>,
}
impl<T> SegmentSet<T> {
/// Makes a new empty `SegmentSet`.
pub fn new() -> Self
where
T: Ord,
{
SegmentSet {
map: SegmentMap::new(),
}
}
/// Make a new `SegmentSet` with a single range present, representing all
/// possible values.
///
/// ```
/// # use segmap::*;
///
/// // Thus, this
/// let full = SegmentSet::<u32>::full();
///
/// // Is equivalent to
/// let mut manual = SegmentSet::new();
/// manual.insert(..);
///
/// assert_eq!(full, manual);
/// ```
pub fn full() -> Self
where
T: Ord,
{
let mut set = Self::new();
set.map
.map
.insert(Key(Segment::new(Unbounded, Unbounded)), ());
set
}
/// Clears the set, removing all elements.
///
/// # Examples
///
/// ```
/// # use segmap::*;
/// let mut set = SegmentSet::new();
/// set.insert(0..1);
/// set.clear();
/// assert!(set.is_empty());
/// ```
pub fn clear(&mut self) {
self.map.clear()
}
/// Returns `true` if any range in the set covers the specified value.
///
/// # Examples
///
/// ```
/// # use segmap::*;
/// let mut set = SegmentSet::new();
/// set.insert(0..5);
/// assert!(set.contains(&3));
/// ```
pub fn contains(&self, value: &T) -> bool
where
T: Clone + Ord,
{
self.map.contains(value)
}
/// Returns a reference to the range covering the given value, if any.
///
/// # Examples
///
/// ```
/// # use segmap::*;
/// let mut set = SegmentSet::new();
/// set.insert(0..5);
///
/// assert_eq!(set.get_range_for(&3), Some(&Segment::from(0..5)));
/// assert!(set.get_range_for(&6).is_none());
/// ```
pub fn get_range_for(&self, value: &T) -> Option<&Segment<T>>
where
T: Clone + Ord,
{
self.map.get_range_value(value).map(|(range, _)| range)
}
/// Insert a range into the set.
///
/// If the inserted range either overlaps or is immediately adjacent
/// any existing range, then the ranges will be coalesced into
/// a single contiguous range.
///
/// # Examples
///
/// ```
/// # use segmap::*;
/// let mut set = SegmentSet::new();
/// set.insert(0..5);
/// assert!(!set.is_empty())
/// ```
///
/// # See Also
///
/// - [`SegmentMap::insert`] and [`SegmentMap::set`] for the internal map's
/// insertion semantics. Because values are always `()` and returning
/// overwritten values is not necessary, this method uses `set`.
///
pub fn insert<R>(&mut self, range: R)
where
R: RangeBounds<T>,
T: Clone + Ord,
{
self.map.set(range, ())
}
/// Removes a range from the set returning if all or any of it was present.
///
/// # Examples
///
/// ```
/// # use segmap::*;
/// let mut set = SegmentSet::new();
/// set.insert(0..5);
/// assert!(set.remove(0..2));
/// ```
///
/// # See Also
///
/// - [`SegmentMap::remove`] and [`SegmentMap::clear_range`] for the internal map's
/// removal semantics. However, this method will not allocate anything to
/// return.
/// - [`SegmentSet::take`] if you want the removed elements
///
pub fn remove<R>(&mut self, range: R) -> bool
where
R: RangeBounds<T>,
T: Clone + Ord,
{
let mut removed_ranges = MaybeMap::None;
self.map
.remove_internal(Segment::from(&range), &mut removed_ranges);
removed_ranges.into()
}
/// Removes a range from the set, returning a set containing the removed
/// elements
///
/// # Examples
///
/// ```
/// # use segmap::*;
/// let mut set = SegmentSet::new();
/// set.insert(0..5);
/// let removed = set.take(0..2);
///
///
/// ```
///
/// # See Also
///
/// - [`SegmentMap::remove`] and [`SegmentMap::clear_range`] for the internal map's
/// removal semantics. However, this method will not allocate anything to
/// return.
/// - [`SegmentSet::remove`] if you don't want the removed elements
///
pub fn take<R>(&mut self, range: R) -> Self
where
R: RangeBounds<T>,
T: Clone + Ord,
{
Self {
map: self.map.remove(range).unwrap_or_default(),
}
}
/// Retains only the elements specified by the predicate.
///
/// In other words, remove all ranges `f(v)` returns `false`.
///
/// # Examples
///
/// ```
/// # use segmap::*;
/// let mut set = SegmentSet::new();
/// set.insert(0..4);
/// set.insert(5..9);
/// set.insert(10..14);
/// set.insert(15..19);
/// set.insert(20..24);
///
/// // Keep only the ranges with even numbered starts
/// set.retain(|r| r.start_value().unwrap() % 2 == 0);
///
/// assert!(set.contains(&0));
/// assert!(set.contains(&10));
/// assert!(set.contains(&12));
/// assert!(set.contains(&20));
/// assert!(set.contains(&23));
///
/// assert!(!set.contains(&15));
/// ```
///
/// # See Also
///
/// - [`SegmentMap::retain`], which is called internally
///
pub fn retain<F>(&mut self, mut f: F)
where
T: Ord,
F: FnMut(&Segment<T>) -> bool,
{
self.map.retain(|r, _| f(r))
}
/// Moves all elements from `other` into `Self`, leaving `other` empty.
///
/// # Examples
///
/// ```
/// # use segmap::*;
/// let mut a = SegmentSet::new();
/// a.insert(0..1);
/// a.insert(1..2);
/// a.insert(2..3);
///
/// let mut b = SegmentSet::new();
/// b.insert(2..3);
/// b.insert(3..4);
/// b.insert(4..5);
///
/// a.append(&mut b);
///
/// // Ranges in a should all be coalesced to 0..5
/// assert!(a.into_iter().eq(vec![
/// Segment::from(0..5)
/// ]));
/// assert!(b.is_empty());
/// ```
pub fn append(&mut self, other: &mut Self)
where
T: Clone + Ord,
{
self.map.append(&mut other.map)
}
/// Split the set into two at the given bound. Returns everything including
/// and after that bound.
///
/// # Examples
///
/// # Basic Usage
///
/// ```
/// # use segmap::*;
/// let mut a = SegmentSet::new();
/// a.insert(0..1);
/// a.insert(2..3);
/// a.insert(4..5);
/// a.insert(6..7);
///
/// let b = a.split_off(Bound::Included(4));
///
/// assert!(a.into_iter().eq(vec![
/// Segment::from(0..1),
/// Segment::from(2..3),
/// ]));
/// assert!(b.into_iter().eq(vec![
/// Segment::from(4..5),
/// Segment::from(6..7),
/// ]));
/// ```
///
/// ## Mixed Bounds
///
/// ```
/// # use segmap::*;
/// let mut a = SegmentSet::new();
/// a.insert(0..7);
///
/// let c = a.split_off(Bound::Excluded(4));
/// let b = a.split_off(Bound::Included(2));
///
/// assert!(a.into_iter().eq(vec![
/// Segment::from(0..2)
/// ]));
/// assert!(b.into_iter().eq(vec![
/// Segment::from(2..=4)
/// ]));
/// assert!(c.into_iter().eq(vec![
/// Segment::new(Bound::Excluded(4), Bound::Excluded(7))
/// ]));
/// ```
///
pub fn split_off(&mut self, at: Bound<T>) -> Self
where
T: Clone + Ord,
{
Self {
map: self.map.split_off(at),
}
}
// TODO: split_off_range
}
impl<T: Clone + Ord> SegmentSet<&T> {
pub fn cloned(&self) -> SegmentSet<T> {
SegmentSet {
map: SegmentMap {
map: self.map.map.iter().map(|(k, _)| (k.cloned(), ())).collect(),
store: alloc::vec::Vec::with_capacity(self.map.store.len()),
},
}
}
}
impl<T> Default for SegmentSet<T>
where
T: Clone + Ord,
{
fn default() -> Self {
SegmentSet::new()
}
}
impl<K, V> From<SegmentMap<K, V>> for SegmentSet<K>
where
K: Ord,
{
fn from(map: SegmentMap<K, V>) -> Self {
let SegmentMap { map, store } = map;
SegmentSet {
map: SegmentMap {
map: map.into_iter().map(|(k, _)| (k, ())).collect(),
store,
},
}
}
}
// We can't just derive this automatically, because that would
// expose irrelevant (and private) implementation details.
// Instead implement it in the same way that the underlying BTreeSet does.
impl<T: Debug> Debug for SegmentSet<T>
where
T: Ord + Clone,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_set().entries(self.iter()).finish()
}
}
impl<T: PartialEq> PartialEq for SegmentSet<T> {
fn eq(&self, other: &Self) -> bool {
self.map == other.map
}
}
|
#[doc = r" Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r" Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::CTRL0 {
#[doc = r" Modifies the contents of the register"]
#[inline]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,
{
let bits = self.register.get();
let r = R { bits: bits };
let mut w = W { bits: bits };
f(&r, &mut w);
self.register.set(w.bits);
}
#[doc = r" Reads the contents of the register"]
#[inline]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
#[doc = r" Writes to the register"]
#[inline]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
let mut w = W::reset_value();
f(&mut w);
self.register.set(w.bits);
}
#[doc = r" Writes the reset value to the register"]
#[inline]
pub fn reset(&self) {
self.write(|w| w)
}
}
#[doc = "Possible values of the field `CTLINK0`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum CTLINK0R {
#[doc = "Use A0/B0 timers as two independent 16-bit timers (default). value."]
TWO_16BIT_TIMERS,
#[doc = "Link A0/B0 timers into a single 32-bit timer. value."]
_32BIT_TIMER,
}
impl CTLINK0R {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
CTLINK0R::TWO_16BIT_TIMERS => false,
CTLINK0R::_32BIT_TIMER => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> CTLINK0R {
match value {
false => CTLINK0R::TWO_16BIT_TIMERS,
true => CTLINK0R::_32BIT_TIMER,
}
}
#[doc = "Checks if the value of the field is `TWO_16BIT_TIMERS`"]
#[inline]
pub fn is_two_16bit_timers(&self) -> bool {
*self == CTLINK0R::TWO_16BIT_TIMERS
}
#[doc = "Checks if the value of the field is `_32BIT_TIMER`"]
#[inline]
pub fn is_32bit_timer(&self) -> bool {
*self == CTLINK0R::_32BIT_TIMER
}
}
#[doc = "Possible values of the field `TMRB0POL`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TMRB0POLR {
#[doc = "The polarity of the TMRPINB0 pin is the same as the timer output. value."]
NORMAL,
#[doc = "The polarity of the TMRPINB0 pin is the inverse of the timer output. value."]
INVERTED,
}
impl TMRB0POLR {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
TMRB0POLR::NORMAL => false,
TMRB0POLR::INVERTED => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> TMRB0POLR {
match value {
false => TMRB0POLR::NORMAL,
true => TMRB0POLR::INVERTED,
}
}
#[doc = "Checks if the value of the field is `NORMAL`"]
#[inline]
pub fn is_normal(&self) -> bool {
*self == TMRB0POLR::NORMAL
}
#[doc = "Checks if the value of the field is `INVERTED`"]
#[inline]
pub fn is_inverted(&self) -> bool {
*self == TMRB0POLR::INVERTED
}
}
#[doc = "Possible values of the field `TMRB0CLR`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TMRB0CLRR {
#[doc = "Allow counter/timer B0 to run value."]
RUN,
#[doc = "Holds counter/timer B0 at 0x0000. value."]
CLEAR,
}
impl TMRB0CLRR {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
TMRB0CLRR::RUN => false,
TMRB0CLRR::CLEAR => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> TMRB0CLRR {
match value {
false => TMRB0CLRR::RUN,
true => TMRB0CLRR::CLEAR,
}
}
#[doc = "Checks if the value of the field is `RUN`"]
#[inline]
pub fn is_run(&self) -> bool {
*self == TMRB0CLRR::RUN
}
#[doc = "Checks if the value of the field is `CLEAR`"]
#[inline]
pub fn is_clear(&self) -> bool {
*self == TMRB0CLRR::CLEAR
}
}
#[doc = "Possible values of the field `TMRB0IE1`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TMRB0IE1R {
#[doc = "Disable counter/timer B0 from generating an interrupt based on COMPR1. value."]
DIS,
#[doc = "Enable counter/timer B0 to generate an interrupt based on COMPR1. value."]
EN,
}
impl TMRB0IE1R {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
TMRB0IE1R::DIS => false,
TMRB0IE1R::EN => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> TMRB0IE1R {
match value {
false => TMRB0IE1R::DIS,
true => TMRB0IE1R::EN,
}
}
#[doc = "Checks if the value of the field is `DIS`"]
#[inline]
pub fn is_dis(&self) -> bool {
*self == TMRB0IE1R::DIS
}
#[doc = "Checks if the value of the field is `EN`"]
#[inline]
pub fn is_en(&self) -> bool {
*self == TMRB0IE1R::EN
}
}
#[doc = "Possible values of the field `TMRB0IE0`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TMRB0IE0R {
#[doc = "Disable counter/timer B0 from generating an interrupt based on COMPR0. value."]
DIS,
#[doc = "Enable counter/timer B0 to generate an interrupt based on COMPR0 value."]
EN,
}
impl TMRB0IE0R {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
TMRB0IE0R::DIS => false,
TMRB0IE0R::EN => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> TMRB0IE0R {
match value {
false => TMRB0IE0R::DIS,
true => TMRB0IE0R::EN,
}
}
#[doc = "Checks if the value of the field is `DIS`"]
#[inline]
pub fn is_dis(&self) -> bool {
*self == TMRB0IE0R::DIS
}
#[doc = "Checks if the value of the field is `EN`"]
#[inline]
pub fn is_en(&self) -> bool {
*self == TMRB0IE0R::EN
}
}
#[doc = "Possible values of the field `TMRB0FN`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TMRB0FNR {
#[doc = "Single count (output toggles and sticks). Count to CMPR0B0, stop. value."]
SINGLECOUNT,
#[doc = "Repeated count (periodic 1-clock-cycle-wide pulses). Count to CMPR0B0, restart. value."]
REPEATEDCOUNT,
#[doc = "Pulse once (aka one-shot). Count to CMPR0B0, assert, count to CMPR1B0, deassert, stop. value."]
PULSE_ONCE,
#[doc = "Pulse continously. Count to CMPR0B0, assert, count to CMPR1B0, deassert, restart. value."]
PULSE_CONT,
#[doc = "Single pattern. value."]
SINGLEPATTERN,
#[doc = "Repeated pattern. value."]
REPEATPATTERN,
#[doc = "Continuous run (aka Free Run). Count continuously. value."]
CONTINUOUS,
#[doc = "Alternate PWM value."]
ALTPWN,
}
impl TMRB0FNR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
match *self {
TMRB0FNR::SINGLECOUNT => 0,
TMRB0FNR::REPEATEDCOUNT => 1,
TMRB0FNR::PULSE_ONCE => 2,
TMRB0FNR::PULSE_CONT => 3,
TMRB0FNR::SINGLEPATTERN => 4,
TMRB0FNR::REPEATPATTERN => 5,
TMRB0FNR::CONTINUOUS => 6,
TMRB0FNR::ALTPWN => 7,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: u8) -> TMRB0FNR {
match value {
0 => TMRB0FNR::SINGLECOUNT,
1 => TMRB0FNR::REPEATEDCOUNT,
2 => TMRB0FNR::PULSE_ONCE,
3 => TMRB0FNR::PULSE_CONT,
4 => TMRB0FNR::SINGLEPATTERN,
5 => TMRB0FNR::REPEATPATTERN,
6 => TMRB0FNR::CONTINUOUS,
7 => TMRB0FNR::ALTPWN,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `SINGLECOUNT`"]
#[inline]
pub fn is_singlecount(&self) -> bool {
*self == TMRB0FNR::SINGLECOUNT
}
#[doc = "Checks if the value of the field is `REPEATEDCOUNT`"]
#[inline]
pub fn is_repeatedcount(&self) -> bool {
*self == TMRB0FNR::REPEATEDCOUNT
}
#[doc = "Checks if the value of the field is `PULSE_ONCE`"]
#[inline]
pub fn is_pulse_once(&self) -> bool {
*self == TMRB0FNR::PULSE_ONCE
}
#[doc = "Checks if the value of the field is `PULSE_CONT`"]
#[inline]
pub fn is_pulse_cont(&self) -> bool {
*self == TMRB0FNR::PULSE_CONT
}
#[doc = "Checks if the value of the field is `SINGLEPATTERN`"]
#[inline]
pub fn is_singlepattern(&self) -> bool {
*self == TMRB0FNR::SINGLEPATTERN
}
#[doc = "Checks if the value of the field is `REPEATPATTERN`"]
#[inline]
pub fn is_repeatpattern(&self) -> bool {
*self == TMRB0FNR::REPEATPATTERN
}
#[doc = "Checks if the value of the field is `CONTINUOUS`"]
#[inline]
pub fn is_continuous(&self) -> bool {
*self == TMRB0FNR::CONTINUOUS
}
#[doc = "Checks if the value of the field is `ALTPWN`"]
#[inline]
pub fn is_altpwn(&self) -> bool {
*self == TMRB0FNR::ALTPWN
}
}
#[doc = "Possible values of the field `TMRB0CLK`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TMRB0CLKR {
#[doc = "Clock source is TMRPINB. value."]
TMRPIN,
#[doc = "Clock source is the HFRC / 4 value."]
HFRC_DIV4,
#[doc = "Clock source is HFRC / 16 value."]
HFRC_DIV16,
#[doc = "Clock source is HFRC / 256 value."]
HFRC_DIV256,
#[doc = "Clock source is HFRC / 1024 value."]
HFRC_DIV1024,
#[doc = "Clock source is HFRC / 4096 value."]
HFRC_DIV4K,
#[doc = "Clock source is the XT (uncalibrated). value."]
XT,
#[doc = "Clock source is XT / 2 value."]
XT_DIV2,
#[doc = "Clock source is XT / 16 value."]
XT_DIV16,
#[doc = "Clock source is XT / 128 value."]
XT_DIV128,
#[doc = "Clock source is LFRC / 2 value."]
LFRC_DIV2,
#[doc = "Clock source is LFRC / 32 value."]
LFRC_DIV32,
#[doc = "Clock source is LFRC / 1024 value."]
LFRC_DIV1K,
#[doc = "Clock source is LFRC value."]
LFRC,
#[doc = "Clock source is 100 Hz from the current RTC oscillator. value."]
RTC_100HZ,
#[doc = "Clock source is HCLK / 4 (note: this clock is only available when MCU is in active mode) value."]
HCLK_DIV4,
#[doc = "Clock source is XT / 4 value."]
XT_DIV4,
#[doc = "Clock source is XT / 8 value."]
XT_DIV8,
#[doc = "Clock source is XT / 32 value."]
XT_DIV32,
#[doc = "Clock source is CTIMERA0 OUT. value."]
CTMRA0,
#[doc = "Clock source is CTIMERB1 OUT. value."]
CTMRB1,
#[doc = "Clock source is CTIMERA1 OUT. value."]
CTMRA1,
#[doc = "Clock source is CTIMERA2 OUT. value."]
CTMRA2,
#[doc = "Clock source is CTIMERB2 OUT. value."]
CTMRB2,
#[doc = "Clock source is CTIMERB3 OUT. value."]
CTMRB3,
#[doc = "Clock source is CTIMERB4 OUT. value."]
CTMRB4,
#[doc = "Clock source is CTIMERB5 OUT. value."]
CTMRB5,
#[doc = "Clock source is CTIMERB6 OUT. value."]
CTMRB6,
#[doc = "Clock source is BLE buck converter TON pulses. value."]
BUCKBLE,
#[doc = "Clock source is Memory buck converter TON pulses. value."]
BUCKB,
#[doc = "Clock source is CPU buck converter TON pulses. value."]
BUCKA,
#[doc = r" Reserved"]
_Reserved(u8),
}
impl TMRB0CLKR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
match *self {
TMRB0CLKR::TMRPIN => 0,
TMRB0CLKR::HFRC_DIV4 => 1,
TMRB0CLKR::HFRC_DIV16 => 2,
TMRB0CLKR::HFRC_DIV256 => 3,
TMRB0CLKR::HFRC_DIV1024 => 4,
TMRB0CLKR::HFRC_DIV4K => 5,
TMRB0CLKR::XT => 6,
TMRB0CLKR::XT_DIV2 => 7,
TMRB0CLKR::XT_DIV16 => 8,
TMRB0CLKR::XT_DIV128 => 9,
TMRB0CLKR::LFRC_DIV2 => 10,
TMRB0CLKR::LFRC_DIV32 => 11,
TMRB0CLKR::LFRC_DIV1K => 12,
TMRB0CLKR::LFRC => 13,
TMRB0CLKR::RTC_100HZ => 14,
TMRB0CLKR::HCLK_DIV4 => 15,
TMRB0CLKR::XT_DIV4 => 16,
TMRB0CLKR::XT_DIV8 => 17,
TMRB0CLKR::XT_DIV32 => 18,
TMRB0CLKR::CTMRA0 => 20,
TMRB0CLKR::CTMRB1 => 21,
TMRB0CLKR::CTMRA1 => 22,
TMRB0CLKR::CTMRA2 => 23,
TMRB0CLKR::CTMRB2 => 24,
TMRB0CLKR::CTMRB3 => 25,
TMRB0CLKR::CTMRB4 => 26,
TMRB0CLKR::CTMRB5 => 27,
TMRB0CLKR::CTMRB6 => 28,
TMRB0CLKR::BUCKBLE => 29,
TMRB0CLKR::BUCKB => 30,
TMRB0CLKR::BUCKA => 31,
TMRB0CLKR::_Reserved(bits) => bits,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: u8) -> TMRB0CLKR {
match value {
0 => TMRB0CLKR::TMRPIN,
1 => TMRB0CLKR::HFRC_DIV4,
2 => TMRB0CLKR::HFRC_DIV16,
3 => TMRB0CLKR::HFRC_DIV256,
4 => TMRB0CLKR::HFRC_DIV1024,
5 => TMRB0CLKR::HFRC_DIV4K,
6 => TMRB0CLKR::XT,
7 => TMRB0CLKR::XT_DIV2,
8 => TMRB0CLKR::XT_DIV16,
9 => TMRB0CLKR::XT_DIV128,
10 => TMRB0CLKR::LFRC_DIV2,
11 => TMRB0CLKR::LFRC_DIV32,
12 => TMRB0CLKR::LFRC_DIV1K,
13 => TMRB0CLKR::LFRC,
14 => TMRB0CLKR::RTC_100HZ,
15 => TMRB0CLKR::HCLK_DIV4,
16 => TMRB0CLKR::XT_DIV4,
17 => TMRB0CLKR::XT_DIV8,
18 => TMRB0CLKR::XT_DIV32,
20 => TMRB0CLKR::CTMRA0,
21 => TMRB0CLKR::CTMRB1,
22 => TMRB0CLKR::CTMRA1,
23 => TMRB0CLKR::CTMRA2,
24 => TMRB0CLKR::CTMRB2,
25 => TMRB0CLKR::CTMRB3,
26 => TMRB0CLKR::CTMRB4,
27 => TMRB0CLKR::CTMRB5,
28 => TMRB0CLKR::CTMRB6,
29 => TMRB0CLKR::BUCKBLE,
30 => TMRB0CLKR::BUCKB,
31 => TMRB0CLKR::BUCKA,
i => TMRB0CLKR::_Reserved(i),
}
}
#[doc = "Checks if the value of the field is `TMRPIN`"]
#[inline]
pub fn is_tmrpin(&self) -> bool {
*self == TMRB0CLKR::TMRPIN
}
#[doc = "Checks if the value of the field is `HFRC_DIV4`"]
#[inline]
pub fn is_hfrc_div4(&self) -> bool {
*self == TMRB0CLKR::HFRC_DIV4
}
#[doc = "Checks if the value of the field is `HFRC_DIV16`"]
#[inline]
pub fn is_hfrc_div16(&self) -> bool {
*self == TMRB0CLKR::HFRC_DIV16
}
#[doc = "Checks if the value of the field is `HFRC_DIV256`"]
#[inline]
pub fn is_hfrc_div256(&self) -> bool {
*self == TMRB0CLKR::HFRC_DIV256
}
#[doc = "Checks if the value of the field is `HFRC_DIV1024`"]
#[inline]
pub fn is_hfrc_div1024(&self) -> bool {
*self == TMRB0CLKR::HFRC_DIV1024
}
#[doc = "Checks if the value of the field is `HFRC_DIV4K`"]
#[inline]
pub fn is_hfrc_div4k(&self) -> bool {
*self == TMRB0CLKR::HFRC_DIV4K
}
#[doc = "Checks if the value of the field is `XT`"]
#[inline]
pub fn is_xt(&self) -> bool {
*self == TMRB0CLKR::XT
}
#[doc = "Checks if the value of the field is `XT_DIV2`"]
#[inline]
pub fn is_xt_div2(&self) -> bool {
*self == TMRB0CLKR::XT_DIV2
}
#[doc = "Checks if the value of the field is `XT_DIV16`"]
#[inline]
pub fn is_xt_div16(&self) -> bool {
*self == TMRB0CLKR::XT_DIV16
}
#[doc = "Checks if the value of the field is `XT_DIV128`"]
#[inline]
pub fn is_xt_div128(&self) -> bool {
*self == TMRB0CLKR::XT_DIV128
}
#[doc = "Checks if the value of the field is `LFRC_DIV2`"]
#[inline]
pub fn is_lfrc_div2(&self) -> bool {
*self == TMRB0CLKR::LFRC_DIV2
}
#[doc = "Checks if the value of the field is `LFRC_DIV32`"]
#[inline]
pub fn is_lfrc_div32(&self) -> bool {
*self == TMRB0CLKR::LFRC_DIV32
}
#[doc = "Checks if the value of the field is `LFRC_DIV1K`"]
#[inline]
pub fn is_lfrc_div1k(&self) -> bool {
*self == TMRB0CLKR::LFRC_DIV1K
}
#[doc = "Checks if the value of the field is `LFRC`"]
#[inline]
pub fn is_lfrc(&self) -> bool {
*self == TMRB0CLKR::LFRC
}
#[doc = "Checks if the value of the field is `RTC_100HZ`"]
#[inline]
pub fn is_rtc_100hz(&self) -> bool {
*self == TMRB0CLKR::RTC_100HZ
}
#[doc = "Checks if the value of the field is `HCLK_DIV4`"]
#[inline]
pub fn is_hclk_div4(&self) -> bool {
*self == TMRB0CLKR::HCLK_DIV4
}
#[doc = "Checks if the value of the field is `XT_DIV4`"]
#[inline]
pub fn is_xt_div4(&self) -> bool {
*self == TMRB0CLKR::XT_DIV4
}
#[doc = "Checks if the value of the field is `XT_DIV8`"]
#[inline]
pub fn is_xt_div8(&self) -> bool {
*self == TMRB0CLKR::XT_DIV8
}
#[doc = "Checks if the value of the field is `XT_DIV32`"]
#[inline]
pub fn is_xt_div32(&self) -> bool {
*self == TMRB0CLKR::XT_DIV32
}
#[doc = "Checks if the value of the field is `CTMRA0`"]
#[inline]
pub fn is_ctmra0(&self) -> bool {
*self == TMRB0CLKR::CTMRA0
}
#[doc = "Checks if the value of the field is `CTMRB1`"]
#[inline]
pub fn is_ctmrb1(&self) -> bool {
*self == TMRB0CLKR::CTMRB1
}
#[doc = "Checks if the value of the field is `CTMRA1`"]
#[inline]
pub fn is_ctmra1(&self) -> bool {
*self == TMRB0CLKR::CTMRA1
}
#[doc = "Checks if the value of the field is `CTMRA2`"]
#[inline]
pub fn is_ctmra2(&self) -> bool {
*self == TMRB0CLKR::CTMRA2
}
#[doc = "Checks if the value of the field is `CTMRB2`"]
#[inline]
pub fn is_ctmrb2(&self) -> bool {
*self == TMRB0CLKR::CTMRB2
}
#[doc = "Checks if the value of the field is `CTMRB3`"]
#[inline]
pub fn is_ctmrb3(&self) -> bool {
*self == TMRB0CLKR::CTMRB3
}
#[doc = "Checks if the value of the field is `CTMRB4`"]
#[inline]
pub fn is_ctmrb4(&self) -> bool {
*self == TMRB0CLKR::CTMRB4
}
#[doc = "Checks if the value of the field is `CTMRB5`"]
#[inline]
pub fn is_ctmrb5(&self) -> bool {
*self == TMRB0CLKR::CTMRB5
}
#[doc = "Checks if the value of the field is `CTMRB6`"]
#[inline]
pub fn is_ctmrb6(&self) -> bool {
*self == TMRB0CLKR::CTMRB6
}
#[doc = "Checks if the value of the field is `BUCKBLE`"]
#[inline]
pub fn is_buckble(&self) -> bool {
*self == TMRB0CLKR::BUCKBLE
}
#[doc = "Checks if the value of the field is `BUCKB`"]
#[inline]
pub fn is_buckb(&self) -> bool {
*self == TMRB0CLKR::BUCKB
}
#[doc = "Checks if the value of the field is `BUCKA`"]
#[inline]
pub fn is_bucka(&self) -> bool {
*self == TMRB0CLKR::BUCKA
}
}
#[doc = "Possible values of the field `TMRB0EN`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TMRB0ENR {
#[doc = "Counter/Timer B0 Disable. value."]
DIS,
#[doc = "Counter/Timer B0 Enable. value."]
EN,
}
impl TMRB0ENR {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
TMRB0ENR::DIS => false,
TMRB0ENR::EN => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> TMRB0ENR {
match value {
false => TMRB0ENR::DIS,
true => TMRB0ENR::EN,
}
}
#[doc = "Checks if the value of the field is `DIS`"]
#[inline]
pub fn is_dis(&self) -> bool {
*self == TMRB0ENR::DIS
}
#[doc = "Checks if the value of the field is `EN`"]
#[inline]
pub fn is_en(&self) -> bool {
*self == TMRB0ENR::EN
}
}
#[doc = "Possible values of the field `TMRA0POL`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TMRA0POLR {
#[doc = "The polarity of the TMRPINA0 pin is the same as the timer output. value."]
NORMAL,
#[doc = "The polarity of the TMRPINA0 pin is the inverse of the timer output. value."]
INVERTED,
}
impl TMRA0POLR {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
TMRA0POLR::NORMAL => false,
TMRA0POLR::INVERTED => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> TMRA0POLR {
match value {
false => TMRA0POLR::NORMAL,
true => TMRA0POLR::INVERTED,
}
}
#[doc = "Checks if the value of the field is `NORMAL`"]
#[inline]
pub fn is_normal(&self) -> bool {
*self == TMRA0POLR::NORMAL
}
#[doc = "Checks if the value of the field is `INVERTED`"]
#[inline]
pub fn is_inverted(&self) -> bool {
*self == TMRA0POLR::INVERTED
}
}
#[doc = "Possible values of the field `TMRA0CLR`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TMRA0CLRR {
#[doc = "Allow counter/timer A0 to run value."]
RUN,
#[doc = "Holds counter/timer A0 at 0x0000. value."]
CLEAR,
}
impl TMRA0CLRR {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
TMRA0CLRR::RUN => false,
TMRA0CLRR::CLEAR => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> TMRA0CLRR {
match value {
false => TMRA0CLRR::RUN,
true => TMRA0CLRR::CLEAR,
}
}
#[doc = "Checks if the value of the field is `RUN`"]
#[inline]
pub fn is_run(&self) -> bool {
*self == TMRA0CLRR::RUN
}
#[doc = "Checks if the value of the field is `CLEAR`"]
#[inline]
pub fn is_clear(&self) -> bool {
*self == TMRA0CLRR::CLEAR
}
}
#[doc = "Possible values of the field `TMRA0IE1`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TMRA0IE1R {
#[doc = "Disable counter/timer A0 from generating an interrupt based on COMPR1. value."]
DIS,
#[doc = "Enable counter/timer A0 to generate an interrupt based on COMPR1. value."]
EN,
}
impl TMRA0IE1R {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
TMRA0IE1R::DIS => false,
TMRA0IE1R::EN => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> TMRA0IE1R {
match value {
false => TMRA0IE1R::DIS,
true => TMRA0IE1R::EN,
}
}
#[doc = "Checks if the value of the field is `DIS`"]
#[inline]
pub fn is_dis(&self) -> bool {
*self == TMRA0IE1R::DIS
}
#[doc = "Checks if the value of the field is `EN`"]
#[inline]
pub fn is_en(&self) -> bool {
*self == TMRA0IE1R::EN
}
}
#[doc = "Possible values of the field `TMRA0IE0`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TMRA0IE0R {
#[doc = "Disable counter/timer A0 from generating an interrupt based on COMPR0. value."]
DIS,
#[doc = "Enable counter/timer A0 to generate an interrupt based on COMPR0. value."]
EN,
}
impl TMRA0IE0R {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
TMRA0IE0R::DIS => false,
TMRA0IE0R::EN => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> TMRA0IE0R {
match value {
false => TMRA0IE0R::DIS,
true => TMRA0IE0R::EN,
}
}
#[doc = "Checks if the value of the field is `DIS`"]
#[inline]
pub fn is_dis(&self) -> bool {
*self == TMRA0IE0R::DIS
}
#[doc = "Checks if the value of the field is `EN`"]
#[inline]
pub fn is_en(&self) -> bool {
*self == TMRA0IE0R::EN
}
}
#[doc = "Possible values of the field `TMRA0FN`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TMRA0FNR {
#[doc = "Single count (output toggles and sticks). Count to CMPR0A0, stop. value."]
SINGLECOUNT,
#[doc = "Repeated count (periodic 1-clock-cycle-wide pulses). Count to CMPR0A0, restart. value."]
REPEATEDCOUNT,
#[doc = "Pulse once (aka one-shot). Count to CMPR0A0, assert, count to CMPR1A0, deassert, stop. value."]
PULSE_ONCE,
#[doc = "Pulse continously. Count to CMPR0A0, assert, count to CMPR1A0, deassert, restart. value."]
PULSE_CONT,
#[doc = "Single pattern. value."]
SINGLEPATTERN,
#[doc = "Repeated pattern. value."]
REPEATPATTERN,
#[doc = "Continuous run (aka Free Run). Count continuously. value."]
CONTINUOUS,
#[doc = "Alternate PWM value."]
ALTPWN,
}
impl TMRA0FNR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
match *self {
TMRA0FNR::SINGLECOUNT => 0,
TMRA0FNR::REPEATEDCOUNT => 1,
TMRA0FNR::PULSE_ONCE => 2,
TMRA0FNR::PULSE_CONT => 3,
TMRA0FNR::SINGLEPATTERN => 4,
TMRA0FNR::REPEATPATTERN => 5,
TMRA0FNR::CONTINUOUS => 6,
TMRA0FNR::ALTPWN => 7,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: u8) -> TMRA0FNR {
match value {
0 => TMRA0FNR::SINGLECOUNT,
1 => TMRA0FNR::REPEATEDCOUNT,
2 => TMRA0FNR::PULSE_ONCE,
3 => TMRA0FNR::PULSE_CONT,
4 => TMRA0FNR::SINGLEPATTERN,
5 => TMRA0FNR::REPEATPATTERN,
6 => TMRA0FNR::CONTINUOUS,
7 => TMRA0FNR::ALTPWN,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `SINGLECOUNT`"]
#[inline]
pub fn is_singlecount(&self) -> bool {
*self == TMRA0FNR::SINGLECOUNT
}
#[doc = "Checks if the value of the field is `REPEATEDCOUNT`"]
#[inline]
pub fn is_repeatedcount(&self) -> bool {
*self == TMRA0FNR::REPEATEDCOUNT
}
#[doc = "Checks if the value of the field is `PULSE_ONCE`"]
#[inline]
pub fn is_pulse_once(&self) -> bool {
*self == TMRA0FNR::PULSE_ONCE
}
#[doc = "Checks if the value of the field is `PULSE_CONT`"]
#[inline]
pub fn is_pulse_cont(&self) -> bool {
*self == TMRA0FNR::PULSE_CONT
}
#[doc = "Checks if the value of the field is `SINGLEPATTERN`"]
#[inline]
pub fn is_singlepattern(&self) -> bool {
*self == TMRA0FNR::SINGLEPATTERN
}
#[doc = "Checks if the value of the field is `REPEATPATTERN`"]
#[inline]
pub fn is_repeatpattern(&self) -> bool {
*self == TMRA0FNR::REPEATPATTERN
}
#[doc = "Checks if the value of the field is `CONTINUOUS`"]
#[inline]
pub fn is_continuous(&self) -> bool {
*self == TMRA0FNR::CONTINUOUS
}
#[doc = "Checks if the value of the field is `ALTPWN`"]
#[inline]
pub fn is_altpwn(&self) -> bool {
*self == TMRA0FNR::ALTPWN
}
}
#[doc = "Possible values of the field `TMRA0CLK`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TMRA0CLKR {
#[doc = "Clock source is TMRPINA. value."]
TMRPIN,
#[doc = "Clock source is the HFRC / 4 value."]
HFRC_DIV4,
#[doc = "Clock source is HFRC / 16 value."]
HFRC_DIV16,
#[doc = "Clock source is HFRC / 256 value."]
HFRC_DIV256,
#[doc = "Clock source is HFRC / 1024 value."]
HFRC_DIV1024,
#[doc = "Clock source is HFRC / 4096 value."]
HFRC_DIV4K,
#[doc = "Clock source is the XT (uncalibrated). value."]
XT,
#[doc = "Clock source is XT / 2 value."]
XT_DIV2,
#[doc = "Clock source is XT / 16 value."]
XT_DIV16,
#[doc = "Clock source is XT / 128 value."]
XT_DIV128,
#[doc = "Clock source is LFRC / 2 value."]
LFRC_DIV2,
#[doc = "Clock source is LFRC / 32 value."]
LFRC_DIV32,
#[doc = "Clock source is LFRC / 1024 value."]
LFRC_DIV1K,
#[doc = "Clock source is LFRC value."]
LFRC,
#[doc = "Clock source is 100 Hz from the current RTC oscillator. value."]
RTC_100HZ,
#[doc = "Clock source is HCLK / 4 (note: this clock is only available when MCU is in active mode) value."]
HCLK_DIV4,
#[doc = "Clock source is XT / 4 value."]
XT_DIV4,
#[doc = "Clock source is XT / 8 value."]
XT_DIV8,
#[doc = "Clock source is XT / 32 value."]
XT_DIV32,
#[doc = "Clock source is CTIMERB0 OUT. value."]
CTMRB0,
#[doc = "Clock source is CTIMERA1 OUT. value."]
CTMRA1,
#[doc = "Clock source is CTIMERB1 OUT. value."]
CTMRB1,
#[doc = "Clock source is CTIMERA2 OUT. value."]
CTMRA2,
#[doc = "Clock source is CTIMERB2 OUT. value."]
CTMRB2,
#[doc = "Clock source is CTIMERB3 OUT. value."]
CTMRB3,
#[doc = "Clock source is CTIMERB4 OUT. value."]
CTMRB4,
#[doc = "Clock source is CTIMERB5 OUT. value."]
CTMRB5,
#[doc = "Clock source is CTIMERB6 OUT. value."]
CTMRB6,
#[doc = "Clock source is BLE buck converter TON pulses. value."]
BUCKBLE,
#[doc = "Clock source is Memory buck converter TON pulses. value."]
BUCKB,
#[doc = "Clock source is CPU buck converter TON pulses. value."]
BUCKA,
#[doc = r" Reserved"]
_Reserved(u8),
}
impl TMRA0CLKR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
match *self {
TMRA0CLKR::TMRPIN => 0,
TMRA0CLKR::HFRC_DIV4 => 1,
TMRA0CLKR::HFRC_DIV16 => 2,
TMRA0CLKR::HFRC_DIV256 => 3,
TMRA0CLKR::HFRC_DIV1024 => 4,
TMRA0CLKR::HFRC_DIV4K => 5,
TMRA0CLKR::XT => 6,
TMRA0CLKR::XT_DIV2 => 7,
TMRA0CLKR::XT_DIV16 => 8,
TMRA0CLKR::XT_DIV128 => 9,
TMRA0CLKR::LFRC_DIV2 => 10,
TMRA0CLKR::LFRC_DIV32 => 11,
TMRA0CLKR::LFRC_DIV1K => 12,
TMRA0CLKR::LFRC => 13,
TMRA0CLKR::RTC_100HZ => 14,
TMRA0CLKR::HCLK_DIV4 => 15,
TMRA0CLKR::XT_DIV4 => 16,
TMRA0CLKR::XT_DIV8 => 17,
TMRA0CLKR::XT_DIV32 => 18,
TMRA0CLKR::CTMRB0 => 20,
TMRA0CLKR::CTMRA1 => 21,
TMRA0CLKR::CTMRB1 => 22,
TMRA0CLKR::CTMRA2 => 23,
TMRA0CLKR::CTMRB2 => 24,
TMRA0CLKR::CTMRB3 => 25,
TMRA0CLKR::CTMRB4 => 26,
TMRA0CLKR::CTMRB5 => 27,
TMRA0CLKR::CTMRB6 => 28,
TMRA0CLKR::BUCKBLE => 29,
TMRA0CLKR::BUCKB => 30,
TMRA0CLKR::BUCKA => 31,
TMRA0CLKR::_Reserved(bits) => bits,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: u8) -> TMRA0CLKR {
match value {
0 => TMRA0CLKR::TMRPIN,
1 => TMRA0CLKR::HFRC_DIV4,
2 => TMRA0CLKR::HFRC_DIV16,
3 => TMRA0CLKR::HFRC_DIV256,
4 => TMRA0CLKR::HFRC_DIV1024,
5 => TMRA0CLKR::HFRC_DIV4K,
6 => TMRA0CLKR::XT,
7 => TMRA0CLKR::XT_DIV2,
8 => TMRA0CLKR::XT_DIV16,
9 => TMRA0CLKR::XT_DIV128,
10 => TMRA0CLKR::LFRC_DIV2,
11 => TMRA0CLKR::LFRC_DIV32,
12 => TMRA0CLKR::LFRC_DIV1K,
13 => TMRA0CLKR::LFRC,
14 => TMRA0CLKR::RTC_100HZ,
15 => TMRA0CLKR::HCLK_DIV4,
16 => TMRA0CLKR::XT_DIV4,
17 => TMRA0CLKR::XT_DIV8,
18 => TMRA0CLKR::XT_DIV32,
20 => TMRA0CLKR::CTMRB0,
21 => TMRA0CLKR::CTMRA1,
22 => TMRA0CLKR::CTMRB1,
23 => TMRA0CLKR::CTMRA2,
24 => TMRA0CLKR::CTMRB2,
25 => TMRA0CLKR::CTMRB3,
26 => TMRA0CLKR::CTMRB4,
27 => TMRA0CLKR::CTMRB5,
28 => TMRA0CLKR::CTMRB6,
29 => TMRA0CLKR::BUCKBLE,
30 => TMRA0CLKR::BUCKB,
31 => TMRA0CLKR::BUCKA,
i => TMRA0CLKR::_Reserved(i),
}
}
#[doc = "Checks if the value of the field is `TMRPIN`"]
#[inline]
pub fn is_tmrpin(&self) -> bool {
*self == TMRA0CLKR::TMRPIN
}
#[doc = "Checks if the value of the field is `HFRC_DIV4`"]
#[inline]
pub fn is_hfrc_div4(&self) -> bool {
*self == TMRA0CLKR::HFRC_DIV4
}
#[doc = "Checks if the value of the field is `HFRC_DIV16`"]
#[inline]
pub fn is_hfrc_div16(&self) -> bool {
*self == TMRA0CLKR::HFRC_DIV16
}
#[doc = "Checks if the value of the field is `HFRC_DIV256`"]
#[inline]
pub fn is_hfrc_div256(&self) -> bool {
*self == TMRA0CLKR::HFRC_DIV256
}
#[doc = "Checks if the value of the field is `HFRC_DIV1024`"]
#[inline]
pub fn is_hfrc_div1024(&self) -> bool {
*self == TMRA0CLKR::HFRC_DIV1024
}
#[doc = "Checks if the value of the field is `HFRC_DIV4K`"]
#[inline]
pub fn is_hfrc_div4k(&self) -> bool {
*self == TMRA0CLKR::HFRC_DIV4K
}
#[doc = "Checks if the value of the field is `XT`"]
#[inline]
pub fn is_xt(&self) -> bool {
*self == TMRA0CLKR::XT
}
#[doc = "Checks if the value of the field is `XT_DIV2`"]
#[inline]
pub fn is_xt_div2(&self) -> bool {
*self == TMRA0CLKR::XT_DIV2
}
#[doc = "Checks if the value of the field is `XT_DIV16`"]
#[inline]
pub fn is_xt_div16(&self) -> bool {
*self == TMRA0CLKR::XT_DIV16
}
#[doc = "Checks if the value of the field is `XT_DIV128`"]
#[inline]
pub fn is_xt_div128(&self) -> bool {
*self == TMRA0CLKR::XT_DIV128
}
#[doc = "Checks if the value of the field is `LFRC_DIV2`"]
#[inline]
pub fn is_lfrc_div2(&self) -> bool {
*self == TMRA0CLKR::LFRC_DIV2
}
#[doc = "Checks if the value of the field is `LFRC_DIV32`"]
#[inline]
pub fn is_lfrc_div32(&self) -> bool {
*self == TMRA0CLKR::LFRC_DIV32
}
#[doc = "Checks if the value of the field is `LFRC_DIV1K`"]
#[inline]
pub fn is_lfrc_div1k(&self) -> bool {
*self == TMRA0CLKR::LFRC_DIV1K
}
#[doc = "Checks if the value of the field is `LFRC`"]
#[inline]
pub fn is_lfrc(&self) -> bool {
*self == TMRA0CLKR::LFRC
}
#[doc = "Checks if the value of the field is `RTC_100HZ`"]
#[inline]
pub fn is_rtc_100hz(&self) -> bool {
*self == TMRA0CLKR::RTC_100HZ
}
#[doc = "Checks if the value of the field is `HCLK_DIV4`"]
#[inline]
pub fn is_hclk_div4(&self) -> bool {
*self == TMRA0CLKR::HCLK_DIV4
}
#[doc = "Checks if the value of the field is `XT_DIV4`"]
#[inline]
pub fn is_xt_div4(&self) -> bool {
*self == TMRA0CLKR::XT_DIV4
}
#[doc = "Checks if the value of the field is `XT_DIV8`"]
#[inline]
pub fn is_xt_div8(&self) -> bool {
*self == TMRA0CLKR::XT_DIV8
}
#[doc = "Checks if the value of the field is `XT_DIV32`"]
#[inline]
pub fn is_xt_div32(&self) -> bool {
*self == TMRA0CLKR::XT_DIV32
}
#[doc = "Checks if the value of the field is `CTMRB0`"]
#[inline]
pub fn is_ctmrb0(&self) -> bool {
*self == TMRA0CLKR::CTMRB0
}
#[doc = "Checks if the value of the field is `CTMRA1`"]
#[inline]
pub fn is_ctmra1(&self) -> bool {
*self == TMRA0CLKR::CTMRA1
}
#[doc = "Checks if the value of the field is `CTMRB1`"]
#[inline]
pub fn is_ctmrb1(&self) -> bool {
*self == TMRA0CLKR::CTMRB1
}
#[doc = "Checks if the value of the field is `CTMRA2`"]
#[inline]
pub fn is_ctmra2(&self) -> bool {
*self == TMRA0CLKR::CTMRA2
}
#[doc = "Checks if the value of the field is `CTMRB2`"]
#[inline]
pub fn is_ctmrb2(&self) -> bool {
*self == TMRA0CLKR::CTMRB2
}
#[doc = "Checks if the value of the field is `CTMRB3`"]
#[inline]
pub fn is_ctmrb3(&self) -> bool {
*self == TMRA0CLKR::CTMRB3
}
#[doc = "Checks if the value of the field is `CTMRB4`"]
#[inline]
pub fn is_ctmrb4(&self) -> bool {
*self == TMRA0CLKR::CTMRB4
}
#[doc = "Checks if the value of the field is `CTMRB5`"]
#[inline]
pub fn is_ctmrb5(&self) -> bool {
*self == TMRA0CLKR::CTMRB5
}
#[doc = "Checks if the value of the field is `CTMRB6`"]
#[inline]
pub fn is_ctmrb6(&self) -> bool {
*self == TMRA0CLKR::CTMRB6
}
#[doc = "Checks if the value of the field is `BUCKBLE`"]
#[inline]
pub fn is_buckble(&self) -> bool {
*self == TMRA0CLKR::BUCKBLE
}
#[doc = "Checks if the value of the field is `BUCKB`"]
#[inline]
pub fn is_buckb(&self) -> bool {
*self == TMRA0CLKR::BUCKB
}
#[doc = "Checks if the value of the field is `BUCKA`"]
#[inline]
pub fn is_bucka(&self) -> bool {
*self == TMRA0CLKR::BUCKA
}
}
#[doc = "Possible values of the field `TMRA0EN`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TMRA0ENR {
#[doc = "Counter/Timer A0 Disable. value."]
DIS,
#[doc = "Counter/Timer A0 Enable. value."]
EN,
}
impl TMRA0ENR {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
TMRA0ENR::DIS => false,
TMRA0ENR::EN => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> TMRA0ENR {
match value {
false => TMRA0ENR::DIS,
true => TMRA0ENR::EN,
}
}
#[doc = "Checks if the value of the field is `DIS`"]
#[inline]
pub fn is_dis(&self) -> bool {
*self == TMRA0ENR::DIS
}
#[doc = "Checks if the value of the field is `EN`"]
#[inline]
pub fn is_en(&self) -> bool {
*self == TMRA0ENR::EN
}
}
#[doc = "Values that can be written to the field `CTLINK0`"]
pub enum CTLINK0W {
#[doc = "Use A0/B0 timers as two independent 16-bit timers (default). value."]
TWO_16BIT_TIMERS,
#[doc = "Link A0/B0 timers into a single 32-bit timer. value."]
_32BIT_TIMER,
}
impl CTLINK0W {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
CTLINK0W::TWO_16BIT_TIMERS => false,
CTLINK0W::_32BIT_TIMER => true,
}
}
}
#[doc = r" Proxy"]
pub struct _CTLINK0W<'a> {
w: &'a mut W,
}
impl<'a> _CTLINK0W<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: CTLINK0W) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Use A0/B0 timers as two independent 16-bit timers (default). value."]
#[inline]
pub fn two_16bit_timers(self) -> &'a mut W {
self.variant(CTLINK0W::TWO_16BIT_TIMERS)
}
#[doc = "Link A0/B0 timers into a single 32-bit timer. value."]
#[inline]
pub fn _32bit_timer(self) -> &'a mut W {
self.variant(CTLINK0W::_32BIT_TIMER)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 31;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `TMRB0POL`"]
pub enum TMRB0POLW {
#[doc = "The polarity of the TMRPINB0 pin is the same as the timer output. value."]
NORMAL,
#[doc = "The polarity of the TMRPINB0 pin is the inverse of the timer output. value."]
INVERTED,
}
impl TMRB0POLW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
TMRB0POLW::NORMAL => false,
TMRB0POLW::INVERTED => true,
}
}
}
#[doc = r" Proxy"]
pub struct _TMRB0POLW<'a> {
w: &'a mut W,
}
impl<'a> _TMRB0POLW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: TMRB0POLW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "The polarity of the TMRPINB0 pin is the same as the timer output. value."]
#[inline]
pub fn normal(self) -> &'a mut W {
self.variant(TMRB0POLW::NORMAL)
}
#[doc = "The polarity of the TMRPINB0 pin is the inverse of the timer output. value."]
#[inline]
pub fn inverted(self) -> &'a mut W {
self.variant(TMRB0POLW::INVERTED)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 28;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `TMRB0CLR`"]
pub enum TMRB0CLRW {
#[doc = "Allow counter/timer B0 to run value."]
RUN,
#[doc = "Holds counter/timer B0 at 0x0000. value."]
CLEAR,
}
impl TMRB0CLRW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
TMRB0CLRW::RUN => false,
TMRB0CLRW::CLEAR => true,
}
}
}
#[doc = r" Proxy"]
pub struct _TMRB0CLRW<'a> {
w: &'a mut W,
}
impl<'a> _TMRB0CLRW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: TMRB0CLRW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Allow counter/timer B0 to run value."]
#[inline]
pub fn run(self) -> &'a mut W {
self.variant(TMRB0CLRW::RUN)
}
#[doc = "Holds counter/timer B0 at 0x0000. value."]
#[inline]
pub fn clear(self) -> &'a mut W {
self.variant(TMRB0CLRW::CLEAR)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 27;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `TMRB0IE1`"]
pub enum TMRB0IE1W {
#[doc = "Disable counter/timer B0 from generating an interrupt based on COMPR1. value."]
DIS,
#[doc = "Enable counter/timer B0 to generate an interrupt based on COMPR1. value."]
EN,
}
impl TMRB0IE1W {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
TMRB0IE1W::DIS => false,
TMRB0IE1W::EN => true,
}
}
}
#[doc = r" Proxy"]
pub struct _TMRB0IE1W<'a> {
w: &'a mut W,
}
impl<'a> _TMRB0IE1W<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: TMRB0IE1W) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Disable counter/timer B0 from generating an interrupt based on COMPR1. value."]
#[inline]
pub fn dis(self) -> &'a mut W {
self.variant(TMRB0IE1W::DIS)
}
#[doc = "Enable counter/timer B0 to generate an interrupt based on COMPR1. value."]
#[inline]
pub fn en(self) -> &'a mut W {
self.variant(TMRB0IE1W::EN)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 26;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `TMRB0IE0`"]
pub enum TMRB0IE0W {
#[doc = "Disable counter/timer B0 from generating an interrupt based on COMPR0. value."]
DIS,
#[doc = "Enable counter/timer B0 to generate an interrupt based on COMPR0 value."]
EN,
}
impl TMRB0IE0W {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
TMRB0IE0W::DIS => false,
TMRB0IE0W::EN => true,
}
}
}
#[doc = r" Proxy"]
pub struct _TMRB0IE0W<'a> {
w: &'a mut W,
}
impl<'a> _TMRB0IE0W<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: TMRB0IE0W) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Disable counter/timer B0 from generating an interrupt based on COMPR0. value."]
#[inline]
pub fn dis(self) -> &'a mut W {
self.variant(TMRB0IE0W::DIS)
}
#[doc = "Enable counter/timer B0 to generate an interrupt based on COMPR0 value."]
#[inline]
pub fn en(self) -> &'a mut W {
self.variant(TMRB0IE0W::EN)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 25;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `TMRB0FN`"]
pub enum TMRB0FNW {
#[doc = "Single count (output toggles and sticks). Count to CMPR0B0, stop. value."]
SINGLECOUNT,
#[doc = "Repeated count (periodic 1-clock-cycle-wide pulses). Count to CMPR0B0, restart. value."]
REPEATEDCOUNT,
#[doc = "Pulse once (aka one-shot). Count to CMPR0B0, assert, count to CMPR1B0, deassert, stop. value."]
PULSE_ONCE,
#[doc = "Pulse continously. Count to CMPR0B0, assert, count to CMPR1B0, deassert, restart. value."]
PULSE_CONT,
#[doc = "Single pattern. value."]
SINGLEPATTERN,
#[doc = "Repeated pattern. value."]
REPEATPATTERN,
#[doc = "Continuous run (aka Free Run). Count continuously. value."]
CONTINUOUS,
#[doc = "Alternate PWM value."]
ALTPWN,
}
impl TMRB0FNW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> u8 {
match *self {
TMRB0FNW::SINGLECOUNT => 0,
TMRB0FNW::REPEATEDCOUNT => 1,
TMRB0FNW::PULSE_ONCE => 2,
TMRB0FNW::PULSE_CONT => 3,
TMRB0FNW::SINGLEPATTERN => 4,
TMRB0FNW::REPEATPATTERN => 5,
TMRB0FNW::CONTINUOUS => 6,
TMRB0FNW::ALTPWN => 7,
}
}
}
#[doc = r" Proxy"]
pub struct _TMRB0FNW<'a> {
w: &'a mut W,
}
impl<'a> _TMRB0FNW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: TMRB0FNW) -> &'a mut W {
{
self.bits(variant._bits())
}
}
#[doc = "Single count (output toggles and sticks). Count to CMPR0B0, stop. value."]
#[inline]
pub fn singlecount(self) -> &'a mut W {
self.variant(TMRB0FNW::SINGLECOUNT)
}
#[doc = "Repeated count (periodic 1-clock-cycle-wide pulses). Count to CMPR0B0, restart. value."]
#[inline]
pub fn repeatedcount(self) -> &'a mut W {
self.variant(TMRB0FNW::REPEATEDCOUNT)
}
#[doc = "Pulse once (aka one-shot). Count to CMPR0B0, assert, count to CMPR1B0, deassert, stop. value."]
#[inline]
pub fn pulse_once(self) -> &'a mut W {
self.variant(TMRB0FNW::PULSE_ONCE)
}
#[doc = "Pulse continously. Count to CMPR0B0, assert, count to CMPR1B0, deassert, restart. value."]
#[inline]
pub fn pulse_cont(self) -> &'a mut W {
self.variant(TMRB0FNW::PULSE_CONT)
}
#[doc = "Single pattern. value."]
#[inline]
pub fn singlepattern(self) -> &'a mut W {
self.variant(TMRB0FNW::SINGLEPATTERN)
}
#[doc = "Repeated pattern. value."]
#[inline]
pub fn repeatpattern(self) -> &'a mut W {
self.variant(TMRB0FNW::REPEATPATTERN)
}
#[doc = "Continuous run (aka Free Run). Count continuously. value."]
#[inline]
pub fn continuous(self) -> &'a mut W {
self.variant(TMRB0FNW::CONTINUOUS)
}
#[doc = "Alternate PWM value."]
#[inline]
pub fn altpwn(self) -> &'a mut W {
self.variant(TMRB0FNW::ALTPWN)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 7;
const OFFSET: u8 = 22;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `TMRB0CLK`"]
pub enum TMRB0CLKW {
#[doc = "Clock source is TMRPINB. value."]
TMRPIN,
#[doc = "Clock source is the HFRC / 4 value."]
HFRC_DIV4,
#[doc = "Clock source is HFRC / 16 value."]
HFRC_DIV16,
#[doc = "Clock source is HFRC / 256 value."]
HFRC_DIV256,
#[doc = "Clock source is HFRC / 1024 value."]
HFRC_DIV1024,
#[doc = "Clock source is HFRC / 4096 value."]
HFRC_DIV4K,
#[doc = "Clock source is the XT (uncalibrated). value."]
XT,
#[doc = "Clock source is XT / 2 value."]
XT_DIV2,
#[doc = "Clock source is XT / 16 value."]
XT_DIV16,
#[doc = "Clock source is XT / 128 value."]
XT_DIV128,
#[doc = "Clock source is LFRC / 2 value."]
LFRC_DIV2,
#[doc = "Clock source is LFRC / 32 value."]
LFRC_DIV32,
#[doc = "Clock source is LFRC / 1024 value."]
LFRC_DIV1K,
#[doc = "Clock source is LFRC value."]
LFRC,
#[doc = "Clock source is 100 Hz from the current RTC oscillator. value."]
RTC_100HZ,
#[doc = "Clock source is HCLK / 4 (note: this clock is only available when MCU is in active mode) value."]
HCLK_DIV4,
#[doc = "Clock source is XT / 4 value."]
XT_DIV4,
#[doc = "Clock source is XT / 8 value."]
XT_DIV8,
#[doc = "Clock source is XT / 32 value."]
XT_DIV32,
#[doc = "Clock source is CTIMERA0 OUT. value."]
CTMRA0,
#[doc = "Clock source is CTIMERB1 OUT. value."]
CTMRB1,
#[doc = "Clock source is CTIMERA1 OUT. value."]
CTMRA1,
#[doc = "Clock source is CTIMERA2 OUT. value."]
CTMRA2,
#[doc = "Clock source is CTIMERB2 OUT. value."]
CTMRB2,
#[doc = "Clock source is CTIMERB3 OUT. value."]
CTMRB3,
#[doc = "Clock source is CTIMERB4 OUT. value."]
CTMRB4,
#[doc = "Clock source is CTIMERB5 OUT. value."]
CTMRB5,
#[doc = "Clock source is CTIMERB6 OUT. value."]
CTMRB6,
#[doc = "Clock source is BLE buck converter TON pulses. value."]
BUCKBLE,
#[doc = "Clock source is Memory buck converter TON pulses. value."]
BUCKB,
#[doc = "Clock source is CPU buck converter TON pulses. value."]
BUCKA,
}
impl TMRB0CLKW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> u8 {
match *self {
TMRB0CLKW::TMRPIN => 0,
TMRB0CLKW::HFRC_DIV4 => 1,
TMRB0CLKW::HFRC_DIV16 => 2,
TMRB0CLKW::HFRC_DIV256 => 3,
TMRB0CLKW::HFRC_DIV1024 => 4,
TMRB0CLKW::HFRC_DIV4K => 5,
TMRB0CLKW::XT => 6,
TMRB0CLKW::XT_DIV2 => 7,
TMRB0CLKW::XT_DIV16 => 8,
TMRB0CLKW::XT_DIV128 => 9,
TMRB0CLKW::LFRC_DIV2 => 10,
TMRB0CLKW::LFRC_DIV32 => 11,
TMRB0CLKW::LFRC_DIV1K => 12,
TMRB0CLKW::LFRC => 13,
TMRB0CLKW::RTC_100HZ => 14,
TMRB0CLKW::HCLK_DIV4 => 15,
TMRB0CLKW::XT_DIV4 => 16,
TMRB0CLKW::XT_DIV8 => 17,
TMRB0CLKW::XT_DIV32 => 18,
TMRB0CLKW::CTMRA0 => 20,
TMRB0CLKW::CTMRB1 => 21,
TMRB0CLKW::CTMRA1 => 22,
TMRB0CLKW::CTMRA2 => 23,
TMRB0CLKW::CTMRB2 => 24,
TMRB0CLKW::CTMRB3 => 25,
TMRB0CLKW::CTMRB4 => 26,
TMRB0CLKW::CTMRB5 => 27,
TMRB0CLKW::CTMRB6 => 28,
TMRB0CLKW::BUCKBLE => 29,
TMRB0CLKW::BUCKB => 30,
TMRB0CLKW::BUCKA => 31,
}
}
}
#[doc = r" Proxy"]
pub struct _TMRB0CLKW<'a> {
w: &'a mut W,
}
impl<'a> _TMRB0CLKW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: TMRB0CLKW) -> &'a mut W {
unsafe { self.bits(variant._bits()) }
}
#[doc = "Clock source is TMRPINB. value."]
#[inline]
pub fn tmrpin(self) -> &'a mut W {
self.variant(TMRB0CLKW::TMRPIN)
}
#[doc = "Clock source is the HFRC / 4 value."]
#[inline]
pub fn hfrc_div4(self) -> &'a mut W {
self.variant(TMRB0CLKW::HFRC_DIV4)
}
#[doc = "Clock source is HFRC / 16 value."]
#[inline]
pub fn hfrc_div16(self) -> &'a mut W {
self.variant(TMRB0CLKW::HFRC_DIV16)
}
#[doc = "Clock source is HFRC / 256 value."]
#[inline]
pub fn hfrc_div256(self) -> &'a mut W {
self.variant(TMRB0CLKW::HFRC_DIV256)
}
#[doc = "Clock source is HFRC / 1024 value."]
#[inline]
pub fn hfrc_div1024(self) -> &'a mut W {
self.variant(TMRB0CLKW::HFRC_DIV1024)
}
#[doc = "Clock source is HFRC / 4096 value."]
#[inline]
pub fn hfrc_div4k(self) -> &'a mut W {
self.variant(TMRB0CLKW::HFRC_DIV4K)
}
#[doc = "Clock source is the XT (uncalibrated). value."]
#[inline]
pub fn xt(self) -> &'a mut W {
self.variant(TMRB0CLKW::XT)
}
#[doc = "Clock source is XT / 2 value."]
#[inline]
pub fn xt_div2(self) -> &'a mut W {
self.variant(TMRB0CLKW::XT_DIV2)
}
#[doc = "Clock source is XT / 16 value."]
#[inline]
pub fn xt_div16(self) -> &'a mut W {
self.variant(TMRB0CLKW::XT_DIV16)
}
#[doc = "Clock source is XT / 128 value."]
#[inline]
pub fn xt_div128(self) -> &'a mut W {
self.variant(TMRB0CLKW::XT_DIV128)
}
#[doc = "Clock source is LFRC / 2 value."]
#[inline]
pub fn lfrc_div2(self) -> &'a mut W {
self.variant(TMRB0CLKW::LFRC_DIV2)
}
#[doc = "Clock source is LFRC / 32 value."]
#[inline]
pub fn lfrc_div32(self) -> &'a mut W {
self.variant(TMRB0CLKW::LFRC_DIV32)
}
#[doc = "Clock source is LFRC / 1024 value."]
#[inline]
pub fn lfrc_div1k(self) -> &'a mut W {
self.variant(TMRB0CLKW::LFRC_DIV1K)
}
#[doc = "Clock source is LFRC value."]
#[inline]
pub fn lfrc(self) -> &'a mut W {
self.variant(TMRB0CLKW::LFRC)
}
#[doc = "Clock source is 100 Hz from the current RTC oscillator. value."]
#[inline]
pub fn rtc_100hz(self) -> &'a mut W {
self.variant(TMRB0CLKW::RTC_100HZ)
}
#[doc = "Clock source is HCLK / 4 (note: this clock is only available when MCU is in active mode) value."]
#[inline]
pub fn hclk_div4(self) -> &'a mut W {
self.variant(TMRB0CLKW::HCLK_DIV4)
}
#[doc = "Clock source is XT / 4 value."]
#[inline]
pub fn xt_div4(self) -> &'a mut W {
self.variant(TMRB0CLKW::XT_DIV4)
}
#[doc = "Clock source is XT / 8 value."]
#[inline]
pub fn xt_div8(self) -> &'a mut W {
self.variant(TMRB0CLKW::XT_DIV8)
}
#[doc = "Clock source is XT / 32 value."]
#[inline]
pub fn xt_div32(self) -> &'a mut W {
self.variant(TMRB0CLKW::XT_DIV32)
}
#[doc = "Clock source is CTIMERA0 OUT. value."]
#[inline]
pub fn ctmra0(self) -> &'a mut W {
self.variant(TMRB0CLKW::CTMRA0)
}
#[doc = "Clock source is CTIMERB1 OUT. value."]
#[inline]
pub fn ctmrb1(self) -> &'a mut W {
self.variant(TMRB0CLKW::CTMRB1)
}
#[doc = "Clock source is CTIMERA1 OUT. value."]
#[inline]
pub fn ctmra1(self) -> &'a mut W {
self.variant(TMRB0CLKW::CTMRA1)
}
#[doc = "Clock source is CTIMERA2 OUT. value."]
#[inline]
pub fn ctmra2(self) -> &'a mut W {
self.variant(TMRB0CLKW::CTMRA2)
}
#[doc = "Clock source is CTIMERB2 OUT. value."]
#[inline]
pub fn ctmrb2(self) -> &'a mut W {
self.variant(TMRB0CLKW::CTMRB2)
}
#[doc = "Clock source is CTIMERB3 OUT. value."]
#[inline]
pub fn ctmrb3(self) -> &'a mut W {
self.variant(TMRB0CLKW::CTMRB3)
}
#[doc = "Clock source is CTIMERB4 OUT. value."]
#[inline]
pub fn ctmrb4(self) -> &'a mut W {
self.variant(TMRB0CLKW::CTMRB4)
}
#[doc = "Clock source is CTIMERB5 OUT. value."]
#[inline]
pub fn ctmrb5(self) -> &'a mut W {
self.variant(TMRB0CLKW::CTMRB5)
}
#[doc = "Clock source is CTIMERB6 OUT. value."]
#[inline]
pub fn ctmrb6(self) -> &'a mut W {
self.variant(TMRB0CLKW::CTMRB6)
}
#[doc = "Clock source is BLE buck converter TON pulses. value."]
#[inline]
pub fn buckble(self) -> &'a mut W {
self.variant(TMRB0CLKW::BUCKBLE)
}
#[doc = "Clock source is Memory buck converter TON pulses. value."]
#[inline]
pub fn buckb(self) -> &'a mut W {
self.variant(TMRB0CLKW::BUCKB)
}
#[doc = "Clock source is CPU buck converter TON pulses. value."]
#[inline]
pub fn bucka(self) -> &'a mut W {
self.variant(TMRB0CLKW::BUCKA)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 31;
const OFFSET: u8 = 17;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `TMRB0EN`"]
pub enum TMRB0ENW {
#[doc = "Counter/Timer B0 Disable. value."]
DIS,
#[doc = "Counter/Timer B0 Enable. value."]
EN,
}
impl TMRB0ENW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
TMRB0ENW::DIS => false,
TMRB0ENW::EN => true,
}
}
}
#[doc = r" Proxy"]
pub struct _TMRB0ENW<'a> {
w: &'a mut W,
}
impl<'a> _TMRB0ENW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: TMRB0ENW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Counter/Timer B0 Disable. value."]
#[inline]
pub fn dis(self) -> &'a mut W {
self.variant(TMRB0ENW::DIS)
}
#[doc = "Counter/Timer B0 Enable. value."]
#[inline]
pub fn en(self) -> &'a mut W {
self.variant(TMRB0ENW::EN)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 16;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `TMRA0POL`"]
pub enum TMRA0POLW {
#[doc = "The polarity of the TMRPINA0 pin is the same as the timer output. value."]
NORMAL,
#[doc = "The polarity of the TMRPINA0 pin is the inverse of the timer output. value."]
INVERTED,
}
impl TMRA0POLW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
TMRA0POLW::NORMAL => false,
TMRA0POLW::INVERTED => true,
}
}
}
#[doc = r" Proxy"]
pub struct _TMRA0POLW<'a> {
w: &'a mut W,
}
impl<'a> _TMRA0POLW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: TMRA0POLW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "The polarity of the TMRPINA0 pin is the same as the timer output. value."]
#[inline]
pub fn normal(self) -> &'a mut W {
self.variant(TMRA0POLW::NORMAL)
}
#[doc = "The polarity of the TMRPINA0 pin is the inverse of the timer output. value."]
#[inline]
pub fn inverted(self) -> &'a mut W {
self.variant(TMRA0POLW::INVERTED)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 12;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `TMRA0CLR`"]
pub enum TMRA0CLRW {
#[doc = "Allow counter/timer A0 to run value."]
RUN,
#[doc = "Holds counter/timer A0 at 0x0000. value."]
CLEAR,
}
impl TMRA0CLRW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
TMRA0CLRW::RUN => false,
TMRA0CLRW::CLEAR => true,
}
}
}
#[doc = r" Proxy"]
pub struct _TMRA0CLRW<'a> {
w: &'a mut W,
}
impl<'a> _TMRA0CLRW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: TMRA0CLRW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Allow counter/timer A0 to run value."]
#[inline]
pub fn run(self) -> &'a mut W {
self.variant(TMRA0CLRW::RUN)
}
#[doc = "Holds counter/timer A0 at 0x0000. value."]
#[inline]
pub fn clear(self) -> &'a mut W {
self.variant(TMRA0CLRW::CLEAR)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 11;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `TMRA0IE1`"]
pub enum TMRA0IE1W {
#[doc = "Disable counter/timer A0 from generating an interrupt based on COMPR1. value."]
DIS,
#[doc = "Enable counter/timer A0 to generate an interrupt based on COMPR1. value."]
EN,
}
impl TMRA0IE1W {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
TMRA0IE1W::DIS => false,
TMRA0IE1W::EN => true,
}
}
}
#[doc = r" Proxy"]
pub struct _TMRA0IE1W<'a> {
w: &'a mut W,
}
impl<'a> _TMRA0IE1W<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: TMRA0IE1W) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Disable counter/timer A0 from generating an interrupt based on COMPR1. value."]
#[inline]
pub fn dis(self) -> &'a mut W {
self.variant(TMRA0IE1W::DIS)
}
#[doc = "Enable counter/timer A0 to generate an interrupt based on COMPR1. value."]
#[inline]
pub fn en(self) -> &'a mut W {
self.variant(TMRA0IE1W::EN)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 10;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `TMRA0IE0`"]
pub enum TMRA0IE0W {
#[doc = "Disable counter/timer A0 from generating an interrupt based on COMPR0. value."]
DIS,
#[doc = "Enable counter/timer A0 to generate an interrupt based on COMPR0. value."]
EN,
}
impl TMRA0IE0W {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
TMRA0IE0W::DIS => false,
TMRA0IE0W::EN => true,
}
}
}
#[doc = r" Proxy"]
pub struct _TMRA0IE0W<'a> {
w: &'a mut W,
}
impl<'a> _TMRA0IE0W<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: TMRA0IE0W) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Disable counter/timer A0 from generating an interrupt based on COMPR0. value."]
#[inline]
pub fn dis(self) -> &'a mut W {
self.variant(TMRA0IE0W::DIS)
}
#[doc = "Enable counter/timer A0 to generate an interrupt based on COMPR0. value."]
#[inline]
pub fn en(self) -> &'a mut W {
self.variant(TMRA0IE0W::EN)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 9;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `TMRA0FN`"]
pub enum TMRA0FNW {
#[doc = "Single count (output toggles and sticks). Count to CMPR0A0, stop. value."]
SINGLECOUNT,
#[doc = "Repeated count (periodic 1-clock-cycle-wide pulses). Count to CMPR0A0, restart. value."]
REPEATEDCOUNT,
#[doc = "Pulse once (aka one-shot). Count to CMPR0A0, assert, count to CMPR1A0, deassert, stop. value."]
PULSE_ONCE,
#[doc = "Pulse continously. Count to CMPR0A0, assert, count to CMPR1A0, deassert, restart. value."]
PULSE_CONT,
#[doc = "Single pattern. value."]
SINGLEPATTERN,
#[doc = "Repeated pattern. value."]
REPEATPATTERN,
#[doc = "Continuous run (aka Free Run). Count continuously. value."]
CONTINUOUS,
#[doc = "Alternate PWM value."]
ALTPWN,
}
impl TMRA0FNW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> u8 {
match *self {
TMRA0FNW::SINGLECOUNT => 0,
TMRA0FNW::REPEATEDCOUNT => 1,
TMRA0FNW::PULSE_ONCE => 2,
TMRA0FNW::PULSE_CONT => 3,
TMRA0FNW::SINGLEPATTERN => 4,
TMRA0FNW::REPEATPATTERN => 5,
TMRA0FNW::CONTINUOUS => 6,
TMRA0FNW::ALTPWN => 7,
}
}
}
#[doc = r" Proxy"]
pub struct _TMRA0FNW<'a> {
w: &'a mut W,
}
impl<'a> _TMRA0FNW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: TMRA0FNW) -> &'a mut W {
{
self.bits(variant._bits())
}
}
#[doc = "Single count (output toggles and sticks). Count to CMPR0A0, stop. value."]
#[inline]
pub fn singlecount(self) -> &'a mut W {
self.variant(TMRA0FNW::SINGLECOUNT)
}
#[doc = "Repeated count (periodic 1-clock-cycle-wide pulses). Count to CMPR0A0, restart. value."]
#[inline]
pub fn repeatedcount(self) -> &'a mut W {
self.variant(TMRA0FNW::REPEATEDCOUNT)
}
#[doc = "Pulse once (aka one-shot). Count to CMPR0A0, assert, count to CMPR1A0, deassert, stop. value."]
#[inline]
pub fn pulse_once(self) -> &'a mut W {
self.variant(TMRA0FNW::PULSE_ONCE)
}
#[doc = "Pulse continously. Count to CMPR0A0, assert, count to CMPR1A0, deassert, restart. value."]
#[inline]
pub fn pulse_cont(self) -> &'a mut W {
self.variant(TMRA0FNW::PULSE_CONT)
}
#[doc = "Single pattern. value."]
#[inline]
pub fn singlepattern(self) -> &'a mut W {
self.variant(TMRA0FNW::SINGLEPATTERN)
}
#[doc = "Repeated pattern. value."]
#[inline]
pub fn repeatpattern(self) -> &'a mut W {
self.variant(TMRA0FNW::REPEATPATTERN)
}
#[doc = "Continuous run (aka Free Run). Count continuously. value."]
#[inline]
pub fn continuous(self) -> &'a mut W {
self.variant(TMRA0FNW::CONTINUOUS)
}
#[doc = "Alternate PWM value."]
#[inline]
pub fn altpwn(self) -> &'a mut W {
self.variant(TMRA0FNW::ALTPWN)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 7;
const OFFSET: u8 = 6;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `TMRA0CLK`"]
pub enum TMRA0CLKW {
#[doc = "Clock source is TMRPINA. value."]
TMRPIN,
#[doc = "Clock source is the HFRC / 4 value."]
HFRC_DIV4,
#[doc = "Clock source is HFRC / 16 value."]
HFRC_DIV16,
#[doc = "Clock source is HFRC / 256 value."]
HFRC_DIV256,
#[doc = "Clock source is HFRC / 1024 value."]
HFRC_DIV1024,
#[doc = "Clock source is HFRC / 4096 value."]
HFRC_DIV4K,
#[doc = "Clock source is the XT (uncalibrated). value."]
XT,
#[doc = "Clock source is XT / 2 value."]
XT_DIV2,
#[doc = "Clock source is XT / 16 value."]
XT_DIV16,
#[doc = "Clock source is XT / 128 value."]
XT_DIV128,
#[doc = "Clock source is LFRC / 2 value."]
LFRC_DIV2,
#[doc = "Clock source is LFRC / 32 value."]
LFRC_DIV32,
#[doc = "Clock source is LFRC / 1024 value."]
LFRC_DIV1K,
#[doc = "Clock source is LFRC value."]
LFRC,
#[doc = "Clock source is 100 Hz from the current RTC oscillator. value."]
RTC_100HZ,
#[doc = "Clock source is HCLK / 4 (note: this clock is only available when MCU is in active mode) value."]
HCLK_DIV4,
#[doc = "Clock source is XT / 4 value."]
XT_DIV4,
#[doc = "Clock source is XT / 8 value."]
XT_DIV8,
#[doc = "Clock source is XT / 32 value."]
XT_DIV32,
#[doc = "Clock source is CTIMERB0 OUT. value."]
CTMRB0,
#[doc = "Clock source is CTIMERA1 OUT. value."]
CTMRA1,
#[doc = "Clock source is CTIMERB1 OUT. value."]
CTMRB1,
#[doc = "Clock source is CTIMERA2 OUT. value."]
CTMRA2,
#[doc = "Clock source is CTIMERB2 OUT. value."]
CTMRB2,
#[doc = "Clock source is CTIMERB3 OUT. value."]
CTMRB3,
#[doc = "Clock source is CTIMERB4 OUT. value."]
CTMRB4,
#[doc = "Clock source is CTIMERB5 OUT. value."]
CTMRB5,
#[doc = "Clock source is CTIMERB6 OUT. value."]
CTMRB6,
#[doc = "Clock source is BLE buck converter TON pulses. value."]
BUCKBLE,
#[doc = "Clock source is Memory buck converter TON pulses. value."]
BUCKB,
#[doc = "Clock source is CPU buck converter TON pulses. value."]
BUCKA,
}
impl TMRA0CLKW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> u8 {
match *self {
TMRA0CLKW::TMRPIN => 0,
TMRA0CLKW::HFRC_DIV4 => 1,
TMRA0CLKW::HFRC_DIV16 => 2,
TMRA0CLKW::HFRC_DIV256 => 3,
TMRA0CLKW::HFRC_DIV1024 => 4,
TMRA0CLKW::HFRC_DIV4K => 5,
TMRA0CLKW::XT => 6,
TMRA0CLKW::XT_DIV2 => 7,
TMRA0CLKW::XT_DIV16 => 8,
TMRA0CLKW::XT_DIV128 => 9,
TMRA0CLKW::LFRC_DIV2 => 10,
TMRA0CLKW::LFRC_DIV32 => 11,
TMRA0CLKW::LFRC_DIV1K => 12,
TMRA0CLKW::LFRC => 13,
TMRA0CLKW::RTC_100HZ => 14,
TMRA0CLKW::HCLK_DIV4 => 15,
TMRA0CLKW::XT_DIV4 => 16,
TMRA0CLKW::XT_DIV8 => 17,
TMRA0CLKW::XT_DIV32 => 18,
TMRA0CLKW::CTMRB0 => 20,
TMRA0CLKW::CTMRA1 => 21,
TMRA0CLKW::CTMRB1 => 22,
TMRA0CLKW::CTMRA2 => 23,
TMRA0CLKW::CTMRB2 => 24,
TMRA0CLKW::CTMRB3 => 25,
TMRA0CLKW::CTMRB4 => 26,
TMRA0CLKW::CTMRB5 => 27,
TMRA0CLKW::CTMRB6 => 28,
TMRA0CLKW::BUCKBLE => 29,
TMRA0CLKW::BUCKB => 30,
TMRA0CLKW::BUCKA => 31,
}
}
}
#[doc = r" Proxy"]
pub struct _TMRA0CLKW<'a> {
w: &'a mut W,
}
impl<'a> _TMRA0CLKW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: TMRA0CLKW) -> &'a mut W {
unsafe { self.bits(variant._bits()) }
}
#[doc = "Clock source is TMRPINA. value."]
#[inline]
pub fn tmrpin(self) -> &'a mut W {
self.variant(TMRA0CLKW::TMRPIN)
}
#[doc = "Clock source is the HFRC / 4 value."]
#[inline]
pub fn hfrc_div4(self) -> &'a mut W {
self.variant(TMRA0CLKW::HFRC_DIV4)
}
#[doc = "Clock source is HFRC / 16 value."]
#[inline]
pub fn hfrc_div16(self) -> &'a mut W {
self.variant(TMRA0CLKW::HFRC_DIV16)
}
#[doc = "Clock source is HFRC / 256 value."]
#[inline]
pub fn hfrc_div256(self) -> &'a mut W {
self.variant(TMRA0CLKW::HFRC_DIV256)
}
#[doc = "Clock source is HFRC / 1024 value."]
#[inline]
pub fn hfrc_div1024(self) -> &'a mut W {
self.variant(TMRA0CLKW::HFRC_DIV1024)
}
#[doc = "Clock source is HFRC / 4096 value."]
#[inline]
pub fn hfrc_div4k(self) -> &'a mut W {
self.variant(TMRA0CLKW::HFRC_DIV4K)
}
#[doc = "Clock source is the XT (uncalibrated). value."]
#[inline]
pub fn xt(self) -> &'a mut W {
self.variant(TMRA0CLKW::XT)
}
#[doc = "Clock source is XT / 2 value."]
#[inline]
pub fn xt_div2(self) -> &'a mut W {
self.variant(TMRA0CLKW::XT_DIV2)
}
#[doc = "Clock source is XT / 16 value."]
#[inline]
pub fn xt_div16(self) -> &'a mut W {
self.variant(TMRA0CLKW::XT_DIV16)
}
#[doc = "Clock source is XT / 128 value."]
#[inline]
pub fn xt_div128(self) -> &'a mut W {
self.variant(TMRA0CLKW::XT_DIV128)
}
#[doc = "Clock source is LFRC / 2 value."]
#[inline]
pub fn lfrc_div2(self) -> &'a mut W {
self.variant(TMRA0CLKW::LFRC_DIV2)
}
#[doc = "Clock source is LFRC / 32 value."]
#[inline]
pub fn lfrc_div32(self) -> &'a mut W {
self.variant(TMRA0CLKW::LFRC_DIV32)
}
#[doc = "Clock source is LFRC / 1024 value."]
#[inline]
pub fn lfrc_div1k(self) -> &'a mut W {
self.variant(TMRA0CLKW::LFRC_DIV1K)
}
#[doc = "Clock source is LFRC value."]
#[inline]
pub fn lfrc(self) -> &'a mut W {
self.variant(TMRA0CLKW::LFRC)
}
#[doc = "Clock source is 100 Hz from the current RTC oscillator. value."]
#[inline]
pub fn rtc_100hz(self) -> &'a mut W {
self.variant(TMRA0CLKW::RTC_100HZ)
}
#[doc = "Clock source is HCLK / 4 (note: this clock is only available when MCU is in active mode) value."]
#[inline]
pub fn hclk_div4(self) -> &'a mut W {
self.variant(TMRA0CLKW::HCLK_DIV4)
}
#[doc = "Clock source is XT / 4 value."]
#[inline]
pub fn xt_div4(self) -> &'a mut W {
self.variant(TMRA0CLKW::XT_DIV4)
}
#[doc = "Clock source is XT / 8 value."]
#[inline]
pub fn xt_div8(self) -> &'a mut W {
self.variant(TMRA0CLKW::XT_DIV8)
}
#[doc = "Clock source is XT / 32 value."]
#[inline]
pub fn xt_div32(self) -> &'a mut W {
self.variant(TMRA0CLKW::XT_DIV32)
}
#[doc = "Clock source is CTIMERB0 OUT. value."]
#[inline]
pub fn ctmrb0(self) -> &'a mut W {
self.variant(TMRA0CLKW::CTMRB0)
}
#[doc = "Clock source is CTIMERA1 OUT. value."]
#[inline]
pub fn ctmra1(self) -> &'a mut W {
self.variant(TMRA0CLKW::CTMRA1)
}
#[doc = "Clock source is CTIMERB1 OUT. value."]
#[inline]
pub fn ctmrb1(self) -> &'a mut W {
self.variant(TMRA0CLKW::CTMRB1)
}
#[doc = "Clock source is CTIMERA2 OUT. value."]
#[inline]
pub fn ctmra2(self) -> &'a mut W {
self.variant(TMRA0CLKW::CTMRA2)
}
#[doc = "Clock source is CTIMERB2 OUT. value."]
#[inline]
pub fn ctmrb2(self) -> &'a mut W {
self.variant(TMRA0CLKW::CTMRB2)
}
#[doc = "Clock source is CTIMERB3 OUT. value."]
#[inline]
pub fn ctmrb3(self) -> &'a mut W {
self.variant(TMRA0CLKW::CTMRB3)
}
#[doc = "Clock source is CTIMERB4 OUT. value."]
#[inline]
pub fn ctmrb4(self) -> &'a mut W {
self.variant(TMRA0CLKW::CTMRB4)
}
#[doc = "Clock source is CTIMERB5 OUT. value."]
#[inline]
pub fn ctmrb5(self) -> &'a mut W {
self.variant(TMRA0CLKW::CTMRB5)
}
#[doc = "Clock source is CTIMERB6 OUT. value."]
#[inline]
pub fn ctmrb6(self) -> &'a mut W {
self.variant(TMRA0CLKW::CTMRB6)
}
#[doc = "Clock source is BLE buck converter TON pulses. value."]
#[inline]
pub fn buckble(self) -> &'a mut W {
self.variant(TMRA0CLKW::BUCKBLE)
}
#[doc = "Clock source is Memory buck converter TON pulses. value."]
#[inline]
pub fn buckb(self) -> &'a mut W {
self.variant(TMRA0CLKW::BUCKB)
}
#[doc = "Clock source is CPU buck converter TON pulses. value."]
#[inline]
pub fn bucka(self) -> &'a mut W {
self.variant(TMRA0CLKW::BUCKA)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 31;
const OFFSET: u8 = 1;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `TMRA0EN`"]
pub enum TMRA0ENW {
#[doc = "Counter/Timer A0 Disable. value."]
DIS,
#[doc = "Counter/Timer A0 Enable. value."]
EN,
}
impl TMRA0ENW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
TMRA0ENW::DIS => false,
TMRA0ENW::EN => true,
}
}
}
#[doc = r" Proxy"]
pub struct _TMRA0ENW<'a> {
w: &'a mut W,
}
impl<'a> _TMRA0ENW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: TMRA0ENW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Counter/Timer A0 Disable. value."]
#[inline]
pub fn dis(self) -> &'a mut W {
self.variant(TMRA0ENW::DIS)
}
#[doc = "Counter/Timer A0 Enable. value."]
#[inline]
pub fn en(self) -> &'a mut W {
self.variant(TMRA0ENW::EN)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 0;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
impl R {
#[doc = r" Value of the register as raw bits"]
#[inline]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bit 31 - Counter/Timer A0/B0 Link bit."]
#[inline]
pub fn ctlink0(&self) -> CTLINK0R {
CTLINK0R::_from({
const MASK: bool = true;
const OFFSET: u8 = 31;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 28 - Counter/Timer B0 output polarity."]
#[inline]
pub fn tmrb0pol(&self) -> TMRB0POLR {
TMRB0POLR::_from({
const MASK: bool = true;
const OFFSET: u8 = 28;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 27 - Counter/Timer B0 Clear bit."]
#[inline]
pub fn tmrb0clr(&self) -> TMRB0CLRR {
TMRB0CLRR::_from({
const MASK: bool = true;
const OFFSET: u8 = 27;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 26 - Counter/Timer B0 Interrupt Enable bit for COMPR1."]
#[inline]
pub fn tmrb0ie1(&self) -> TMRB0IE1R {
TMRB0IE1R::_from({
const MASK: bool = true;
const OFFSET: u8 = 26;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 25 - Counter/Timer B0 Interrupt Enable bit for COMPR0."]
#[inline]
pub fn tmrb0ie0(&self) -> TMRB0IE0R {
TMRB0IE0R::_from({
const MASK: bool = true;
const OFFSET: u8 = 25;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bits 22:24 - Counter/Timer B0 Function Select."]
#[inline]
pub fn tmrb0fn(&self) -> TMRB0FNR {
TMRB0FNR::_from({
const MASK: u8 = 7;
const OFFSET: u8 = 22;
((self.bits >> OFFSET) & MASK as u32) as u8
})
}
#[doc = "Bits 17:21 - Counter/Timer B0 Clock Select."]
#[inline]
pub fn tmrb0clk(&self) -> TMRB0CLKR {
TMRB0CLKR::_from({
const MASK: u8 = 31;
const OFFSET: u8 = 17;
((self.bits >> OFFSET) & MASK as u32) as u8
})
}
#[doc = "Bit 16 - Counter/Timer B0 Enable bit."]
#[inline]
pub fn tmrb0en(&self) -> TMRB0ENR {
TMRB0ENR::_from({
const MASK: bool = true;
const OFFSET: u8 = 16;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 12 - Counter/Timer A0 output polarity."]
#[inline]
pub fn tmra0pol(&self) -> TMRA0POLR {
TMRA0POLR::_from({
const MASK: bool = true;
const OFFSET: u8 = 12;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 11 - Counter/Timer A0 Clear bit."]
#[inline]
pub fn tmra0clr(&self) -> TMRA0CLRR {
TMRA0CLRR::_from({
const MASK: bool = true;
const OFFSET: u8 = 11;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 10 - Counter/Timer A0 Interrupt Enable bit based on COMPR1."]
#[inline]
pub fn tmra0ie1(&self) -> TMRA0IE1R {
TMRA0IE1R::_from({
const MASK: bool = true;
const OFFSET: u8 = 10;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 9 - Counter/Timer A0 Interrupt Enable bit based on COMPR0."]
#[inline]
pub fn tmra0ie0(&self) -> TMRA0IE0R {
TMRA0IE0R::_from({
const MASK: bool = true;
const OFFSET: u8 = 9;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bits 6:8 - Counter/Timer A0 Function Select."]
#[inline]
pub fn tmra0fn(&self) -> TMRA0FNR {
TMRA0FNR::_from({
const MASK: u8 = 7;
const OFFSET: u8 = 6;
((self.bits >> OFFSET) & MASK as u32) as u8
})
}
#[doc = "Bits 1:5 - Counter/Timer A0 Clock Select."]
#[inline]
pub fn tmra0clk(&self) -> TMRA0CLKR {
TMRA0CLKR::_from({
const MASK: u8 = 31;
const OFFSET: u8 = 1;
((self.bits >> OFFSET) & MASK as u32) as u8
})
}
#[doc = "Bit 0 - Counter/Timer A0 Enable bit."]
#[inline]
pub fn tmra0en(&self) -> TMRA0ENR {
TMRA0ENR::_from({
const MASK: bool = true;
const OFFSET: u8 = 0;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
}
impl W {
#[doc = r" Reset value of the register"]
#[inline]
pub fn reset_value() -> W {
W { bits: 0 }
}
#[doc = r" Writes raw bits to the register"]
#[inline]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bit 31 - Counter/Timer A0/B0 Link bit."]
#[inline]
pub fn ctlink0(&mut self) -> _CTLINK0W {
_CTLINK0W { w: self }
}
#[doc = "Bit 28 - Counter/Timer B0 output polarity."]
#[inline]
pub fn tmrb0pol(&mut self) -> _TMRB0POLW {
_TMRB0POLW { w: self }
}
#[doc = "Bit 27 - Counter/Timer B0 Clear bit."]
#[inline]
pub fn tmrb0clr(&mut self) -> _TMRB0CLRW {
_TMRB0CLRW { w: self }
}
#[doc = "Bit 26 - Counter/Timer B0 Interrupt Enable bit for COMPR1."]
#[inline]
pub fn tmrb0ie1(&mut self) -> _TMRB0IE1W {
_TMRB0IE1W { w: self }
}
#[doc = "Bit 25 - Counter/Timer B0 Interrupt Enable bit for COMPR0."]
#[inline]
pub fn tmrb0ie0(&mut self) -> _TMRB0IE0W {
_TMRB0IE0W { w: self }
}
#[doc = "Bits 22:24 - Counter/Timer B0 Function Select."]
#[inline]
pub fn tmrb0fn(&mut self) -> _TMRB0FNW {
_TMRB0FNW { w: self }
}
#[doc = "Bits 17:21 - Counter/Timer B0 Clock Select."]
#[inline]
pub fn tmrb0clk(&mut self) -> _TMRB0CLKW {
_TMRB0CLKW { w: self }
}
#[doc = "Bit 16 - Counter/Timer B0 Enable bit."]
#[inline]
pub fn tmrb0en(&mut self) -> _TMRB0ENW {
_TMRB0ENW { w: self }
}
#[doc = "Bit 12 - Counter/Timer A0 output polarity."]
#[inline]
pub fn tmra0pol(&mut self) -> _TMRA0POLW {
_TMRA0POLW { w: self }
}
#[doc = "Bit 11 - Counter/Timer A0 Clear bit."]
#[inline]
pub fn tmra0clr(&mut self) -> _TMRA0CLRW {
_TMRA0CLRW { w: self }
}
#[doc = "Bit 10 - Counter/Timer A0 Interrupt Enable bit based on COMPR1."]
#[inline]
pub fn tmra0ie1(&mut self) -> _TMRA0IE1W {
_TMRA0IE1W { w: self }
}
#[doc = "Bit 9 - Counter/Timer A0 Interrupt Enable bit based on COMPR0."]
#[inline]
pub fn tmra0ie0(&mut self) -> _TMRA0IE0W {
_TMRA0IE0W { w: self }
}
#[doc = "Bits 6:8 - Counter/Timer A0 Function Select."]
#[inline]
pub fn tmra0fn(&mut self) -> _TMRA0FNW {
_TMRA0FNW { w: self }
}
#[doc = "Bits 1:5 - Counter/Timer A0 Clock Select."]
#[inline]
pub fn tmra0clk(&mut self) -> _TMRA0CLKW {
_TMRA0CLKW { w: self }
}
#[doc = "Bit 0 - Counter/Timer A0 Enable bit."]
#[inline]
pub fn tmra0en(&mut self) -> _TMRA0ENW {
_TMRA0ENW { w: self }
}
}
|
#[doc = "Register `CFG2` reader"]
pub type R = crate::R<CFG2_SPEC>;
#[doc = "Register `CFG2` writer"]
pub type W = crate::W<CFG2_SPEC>;
#[doc = "Field `RXFILTDIS` reader - RXFILTDIS"]
pub type RXFILTDIS_R = crate::BitReader;
#[doc = "Field `RXFILTDIS` writer - RXFILTDIS"]
pub type RXFILTDIS_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `RXFILT2N3` reader - RXFILT2N3"]
pub type RXFILT2N3_R = crate::BitReader;
#[doc = "Field `RXFILT2N3` writer - RXFILT2N3"]
pub type RXFILT2N3_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `FORCECLK` reader - FORCECLK"]
pub type FORCECLK_R = crate::BitReader;
#[doc = "Field `FORCECLK` writer - FORCECLK"]
pub type FORCECLK_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `WUPEN` reader - WUPEN"]
pub type WUPEN_R = crate::BitReader;
#[doc = "Field `WUPEN` writer - WUPEN"]
pub type WUPEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bit 0 - RXFILTDIS"]
#[inline(always)]
pub fn rxfiltdis(&self) -> RXFILTDIS_R {
RXFILTDIS_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - RXFILT2N3"]
#[inline(always)]
pub fn rxfilt2n3(&self) -> RXFILT2N3_R {
RXFILT2N3_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 2 - FORCECLK"]
#[inline(always)]
pub fn forceclk(&self) -> FORCECLK_R {
FORCECLK_R::new(((self.bits >> 2) & 1) != 0)
}
#[doc = "Bit 3 - WUPEN"]
#[inline(always)]
pub fn wupen(&self) -> WUPEN_R {
WUPEN_R::new(((self.bits >> 3) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - RXFILTDIS"]
#[inline(always)]
#[must_use]
pub fn rxfiltdis(&mut self) -> RXFILTDIS_W<CFG2_SPEC, 0> {
RXFILTDIS_W::new(self)
}
#[doc = "Bit 1 - RXFILT2N3"]
#[inline(always)]
#[must_use]
pub fn rxfilt2n3(&mut self) -> RXFILT2N3_W<CFG2_SPEC, 1> {
RXFILT2N3_W::new(self)
}
#[doc = "Bit 2 - FORCECLK"]
#[inline(always)]
#[must_use]
pub fn forceclk(&mut self) -> FORCECLK_W<CFG2_SPEC, 2> {
FORCECLK_W::new(self)
}
#[doc = "Bit 3 - WUPEN"]
#[inline(always)]
#[must_use]
pub fn wupen(&mut self) -> WUPEN_W<CFG2_SPEC, 3> {
WUPEN_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 = "UCPD configuration register 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cfg2::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 [`cfg2::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct CFG2_SPEC;
impl crate::RegisterSpec for CFG2_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`cfg2::R`](R) reader structure"]
impl crate::Readable for CFG2_SPEC {}
#[doc = "`write(|w| ..)` method takes [`cfg2::W`](W) writer structure"]
impl crate::Writable for CFG2_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets CFG2 to value 0"]
impl crate::Resettable for CFG2_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
#![deny(warnings)]
extern crate pretty_env_logger;
extern crate warp;
use std::error::Error as StdError;
use std::fmt::{self, Display};
use warp::{Filter, reject, Rejection, Reply};
use warp::http::StatusCode;
#[derive(Debug)]
enum Error {
Oops,
NotFound
}
impl Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.description())
}
}
impl StdError for Error {
fn description(&self) -> &str {
match self {
Error::Oops => ":fire: this is fine",
Error::NotFound => "you get a 404, and *you* get a 404...",
}
}
fn cause(&self) -> Option<&StdError> {
None
}
}
fn main() {
let hello = warp::path::index()
.map(warp::reply);
let oops = warp::path("oops")
.and_then(|| {
Err::<StatusCode, _>(reject().with(Error::Oops))
});
let not_found = warp::path("not_found")
.and_then(|| {
Err::<StatusCode, _>(reject().with(Error::NotFound))
});
let routes = warp::get2()
.and(hello.or(oops).or(not_found))
.recover(customize_error);
warp::serve(routes)
.run(([127, 0, 0, 1], 3030));
}
// This function receives a `Rejection` and tries to return a custom
// value, othewise simply passes the rejection along.
//
// NOTE: We don't *need* to return an `impl Reply` here, it's just
// convenient in this specific case.
fn customize_error(err: Rejection) -> Result<impl Reply, Rejection> {
let mut resp = err.json();
let cause = match err.into_cause::<Error>() {
Ok(ok) => ok,
Err(err) => return Err(err)
};
match *cause {
Error::NotFound => *resp.status_mut() = StatusCode::NOT_FOUND,
Error::Oops => *resp.status_mut() = StatusCode::INTERNAL_SERVER_ERROR,
}
Ok(resp)
}
|
use std::borrow::Cow;
use std::fmt::{self, Display};
use std::sync::Arc;
use chrono::Utc;
use discorsd::{async_trait, BotState};
use discorsd::commands::*;
use discorsd::errors::BotError;
use discorsd::http::channel::embed;
use discorsd::model::interaction_response::message;
use discorsd::model::message::Color;
use crate::Bot;
#[derive(Copy, Clone, Debug)]
pub struct UptimeCommand;
#[async_trait]
impl SlashCommand for UptimeCommand {
type Bot = Bot;
type Data = ();
type Use = Used;
const NAME: &'static str = "uptime";
fn description(&self) -> Cow<'static, str> {
"How long has this bot been online for?".into()
}
async fn run(&self,
state: Arc<BotState<Bot>>,
interaction: InteractionUse<AppCommandData, Unused>,
_: (),
) -> Result<InteractionUse<AppCommandData, Used>, BotError> {
let msg = if let Some(ready) = state.bot.first_log_in.get().copied() {
let embed = embed(|e| {
e.color(Color::GOLD);
e.title(Duration(Utc::now().signed_duration_since(ready)).to_string());
});
// `map_or_else` tries to move `embed` in both branches, so it doesn't work
if let Some(resume) = *state.bot.log_in.read().await {
embed.build(|e| e.add_field("Time since last reconnect", Duration(Utc::now().signed_duration_since(resume))))
} else {
embed
}.into()
} else {
log::warn!("somehow not connected, yet /uptime ran???");
message(|m| {
m.content("Not yet connected, somehow :/");
})
};
interaction.respond(&state, msg).await.map_err(Into::into)
}
}
struct Duration(chrono::Duration);
impl Display for Duration {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut dur = self.0;
let days = dur.num_days();
if days > 0 {
if days == 1 { write!(f, "1 day, ")? } else { write!(f, "{days} days, ")? }
dur = dur - chrono::Duration::days(days);
}
let hours = dur.num_hours();
if hours > 0 {
if hours == 1 { write!(f, "1 hour, ")? } else { write!(f, "{hours} hours, ")? }
dur = dur - chrono::Duration::hours(hours);
}
let mins = dur.num_minutes();
if mins > 0 {
if mins == 1 { write!(f, "1 minute, ")? } else { write!(f, "{mins} minutes, ")? }
dur = dur - chrono::Duration::minutes(mins);
}
let secs = dur.num_seconds();
dur = dur - chrono::Duration::seconds(secs);
let millis = dur.num_milliseconds();
write!(f, "{secs}.{millis} seconds")
}
} |
#![no_std]
#[macro_use]
extern crate log;
#[link(name = "user-asm", kind = "static")]
extern "C" {
fn _syscall_launch(branch: u64, argument: u64) -> u64;
}
pub fn release() {
trace!("release");
unsafe {
_syscall_launch(0, 0);
}
}
pub fn exit() -> ! {
trace!("exit");
unsafe {
_syscall_launch(0, 1);
}
unreachable!("Returned to exited task");
}
pub fn wait() {
trace!("wait");
unsafe {
_syscall_launch(0, 2);
}
}
pub fn log() {
unimplemented!();
}
|
pub fn sum(a: usize, b: usize) -> usize {
a + b
}
|
#![no_main]
#![no_std]
#![allow(deprecated)]
use panic_halt as _;
use stm32f0xx_hal as hal;
use cortex_m_rt::entry;
use crate::hal::{i2c::I2c, prelude::*, serial::Serial, spi::Spi, stm32};
use cortex_m::peripheral::Peripherals;
use nb::block;
use core::mem::transmute_copy;
use heapless::{consts::*, Vec};
use postcard::{from_bytes, to_vec};
use bridge_common::encoding::{Reply, Request};
use stm32f0xx_hal::gpio::{gpioa, gpiob, gpiof};
#[cfg(any(feature = "stm32f072",))]
use stm32f0xx_hal::gpio::gpioc;
use stm32f0xx_hal::gpio::{Floating, PushPull};
use stm32f0xx_hal::gpio::{Input, Output};
type BufferLength = U64;
trait PORTExt {
fn clone(&self) -> Self;
}
trait GPIOExt {
fn to_output_push_pull(&self);
fn toggle(&self);
fn set_high(&self);
fn set_low(&self);
}
macro_rules! GPIO {
([$($port:ident : [$(($pin:ident, $name:ident)),+]),+]) => {
$(
impl PORTExt for $port::Parts {
fn clone(&self) -> Self {
unsafe { transmute_copy(&self) }
}
}
$(
struct $pin($port::$pin<Input<Floating>>);
let $name = $pin($port.$name);
impl GPIOExt for $pin {
fn to_output_push_pull(&self) {
cortex_m::interrupt::free(|cs| {
let pin: $port::$pin<Input<Floating>> = unsafe { transmute_copy(&self) };
pin.into_push_pull_output(cs);
});
}
fn toggle(&self) {
let mut pin: $port::$pin<Output<PushPull>> = unsafe { transmute_copy(&self) };
pin.toggle();
}
fn set_high(&self) {
let mut pin: $port::$pin<Output<PushPull>> = unsafe { transmute_copy(&self) };
pin.set_high();
}
fn set_low(&self) {
let mut pin: $port::$pin<Output<PushPull>> = unsafe { transmute_copy(&self) };
pin.set_low();
}
}
)+
)+
};
}
fn send_serial_reply<T: embedded_hal::serial::Write<u8>>(serial: &mut T, reply: &Reply) {
let output: Vec<u8, BufferLength> = to_vec(reply).unwrap();
for c in &output {
serial.write(*c).ok();
}
serial.flush().ok();
}
#[entry]
fn main() -> ! {
if let (Some(mut p), Some(_cp)) = (stm32::Peripherals::take(), Peripherals::take()) {
let mut rcc = p.RCC.configure().sysclk(48.mhz()).freeze(&mut p.FLASH);
// Obtain resources from GPIO ports A, B, C and F
let gpioa = p.GPIOA.split(&mut rcc);
let gpiob = p.GPIOB.split(&mut rcc);
#[cfg(any(feature = "stm32f072",))]
let gpioc = p.GPIOC.split(&mut rcc);
let gpiof = p.GPIOF.split(&mut rcc);
#[cfg(any(feature = "stm32f042",))]
const HAS_I2C_ON_PORT_F: bool = true;
#[cfg(not(feature = "stm32f042",))]
const HAS_I2C_ON_PORT_F: bool = false;
#[cfg(any(feature = "stm32f042",))]
let mut i2c: Option<hal::i2c::I2c<_, _, _>> = None;
let mut spi: Option<hal::spi::Spi<_, _, _, _>> = None;
#[cfg(not(feature = "stm32f042",))]
let i2c: Option<bool> = None;
/* Set up serial port */
let (tx, rx) = cortex_m::interrupt::free(|cs| {
let gpioa = gpioa.clone();
let pa2 = gpioa.pa2;
let pa15 = gpioa.pa15;
(pa2.into_alternate_af1(cs), pa15.into_alternate_af1(cs))
});
let gpioa_clone = gpioa.clone();
let gpiof_clone = gpiof.clone();
let mut serial = Serial::usart2(p.USART2, (tx, rx), 115_200.bps(), &mut rcc);
let mut buffer: Vec<u8, BufferLength> = Default::default();
GPIO!(
[gpioa :
[
(PA0, pa0),
(PA1, pa1),
(PA3, pa3),
(PA4, pa4),
(PA5, pa5),
(PA6, pa6),
(PA7, pa7),
(PA8, pa8),
(PA9, pa9),
(PA10, pa10),
(PA11, pa11),
(PA12, pa12),
(PA13, pa13),
(PA14, pa14)
]
]
);
GPIO!([gpiob : [(PB3, pb3), (PB4, pb4)]]);
GPIO!([gpiof : [(PF0, pf0), (PF1, pf1)]]);
#[cfg(any(feature = "stm32f072",))]
GPIO!([gpioc : [(PC6, pc6), (PC7, pc7), (PC8, pc8), (PC9, pc9)]]);
let apply_gpio = |name: &str, f: &dyn Fn(&dyn GPIOExt)| -> Reply {
match name {
"a0" => f(&pa0),
"a1" => f(&pa1),
"a3" => f(&pa3),
"a4" => f(&pa4),
"a5" => f(&pa5),
"a6" => f(&pa6),
"a7" => f(&pa7),
"a8" => f(&pa8),
"a9" => f(&pa9),
"a10" => f(&pa10),
"a11" => f(&pa11),
"a12" => f(&pa12),
"a13" => f(&pa13),
"a14" => f(&pa14),
"b3" => f(&pb3),
"b4" => f(&pb4),
#[cfg(any(feature = "stm32f072"))]
"c6" => f(&pc6),
#[cfg(any(feature = "stm32f072"))]
"c7" => f(&pc7),
#[cfg(any(feature = "stm32f072"))]
"c8" => f(&pc8),
#[cfg(any(feature = "stm32f072"))]
"c9" => f(&pc9),
"f0" => f(&pf0),
"f1" => f(&pf1),
_ => return Reply::NotImplemented,
}
Reply::Ok
};
loop {
if let Ok(received) = block!(serial.read()) {
if buffer.push(received).is_err() {
send_serial_reply(
&mut serial,
&Reply::ReceiveErr {
bytes: buffer.len() as u8,
},
);
buffer.clear();
continue;
}
}
let reply = match from_bytes::<Request>(&buffer) {
Ok(msg) => {
match msg {
Request::Version => bridge_common::encoding::current_version(),
Request::Clear => Reply::Ok {},
Request::Reset => Reply::NotImplemented {},
Request::GpioInitPP { pin } => {
apply_gpio(pin, &|p: &dyn GPIOExt| p.to_output_push_pull())
}
Request::GpioToggle { pin } => {
apply_gpio(pin, &|p: &dyn GPIOExt| p.toggle())
}
Request::GpioSetLow { pin } => {
apply_gpio(pin, &|p: &dyn GPIOExt| p.set_low())
}
Request::GpioSetHigh { pin } => {
apply_gpio(pin, &|p: &dyn GPIOExt| p.set_high())
}
Request::I2CInit {
scl_pin,
sda_pin,
speed,
} => {
if HAS_I2C_ON_PORT_F
&& scl_pin == "f1"
&& sda_pin == "f0"
&& (speed >= 10 || speed <= 400)
{
#[cfg(any(feature = "stm32f042",))]
{
let gpiof = gpiof_clone.clone();
let (scl, sda) = cortex_m::interrupt::free(|cs| {
let scl = gpiof
.pf1
.into_alternate_af1(cs)
.internal_pull_up(cs, true)
.set_open_drain(cs);
let sda = gpiof
.pf0
.into_alternate_af1(cs)
.internal_pull_up(cs, true)
.set_open_drain(cs);
(scl, sda)
});
let i2c1 = unsafe { transmute_copy(&p.I2C1) };
// Setup I2C1
i2c = Some(I2c::i2c1(i2c1, (scl, sda), speed.khz(), &mut rcc));
}
Reply::Ok {}
} else {
Reply::NotImplemented {}
}
}
Request::I2CWrite {
ident,
address,
data,
} => {
if HAS_I2C_ON_PORT_F && ident == "i2c1" && i2c.is_some() {
#[cfg(any(feature = "stm32f042",))]
{
i2c.as_mut().map(|i2c| i2c.write(address, data));
}
Reply::Ok {}
} else {
Reply::NotImplemented {}
}
}
Request::SPIInit {
sck_pin,
miso_pin,
mosi_pin,
speed,
} => {
if sck_pin == "a5"
&& miso_pin == "a6"
&& mosi_pin == "a7"
&& (speed >= 10 || speed <= 400)
{
let gpioa = gpioa_clone.clone();
let (sck, miso, mosi) = cortex_m::interrupt::free(move |cs| {
(
gpioa.pa5.into_alternate_af0(cs),
gpioa.pa6.into_alternate_af0(cs),
gpioa.pa7.into_alternate_af0(cs),
)
});
let spi1 = unsafe { transmute_copy(&p.SPI1) };
use embedded_hal::spi::{Mode, Phase, Polarity};
/// SPI mode that is needed for this crate
///
/// Provided for convenience
const MODE: Mode = Mode {
polarity: Polarity::IdleHigh,
phase: Phase::CaptureOnSecondTransition,
};
// Setup SPI1
spi = Some(Spi::spi1(
spi1,
(sck, miso, mosi),
MODE,
speed.khz(),
&mut rcc,
));
Reply::Ok {}
} else {
Reply::NotImplemented {}
}
}
Request::SPIWrite { ident, data } => {
if ident == "spi1" && spi.is_some() {
spi.as_mut().map(|spi| spi.write(data));
Reply::Ok {}
} else {
Reply::NotImplemented {}
}
}
}
}
Err(err) => match err {
postcard::Error::DeserializeUnexpectedEnd => continue,
_ => Reply::VerboseErr { err: "some error" },
},
};
/* Clear the buffer after parsing a complete message */
buffer.clear();
/* Send reply over serial connection */
send_serial_reply(&mut serial, &reply);
}
}
loop {
continue;
}
}
|
use diesel::prelude::*;
use diesel::r2d2::{self, ConnectionManager};
use sublime_fuzzy as fuzzy;
use uuid::Uuid;
/// Reference type for money values
pub type Money = i32;
/// Reference type to the current database implementation
pub type DB = diesel::pg::Pg;
/// Reference type to the current database connection
pub type DbConnection = PgConnection;
/// Reference type to the threaded pool of the current database connection
pub type Pool = r2d2::Pool<ConnectionManager<DbConnection>>;
/// Generate a new random uuid
pub fn generate_uuid() -> Uuid {
Uuid::new_v4()
}
pub fn generate_uuid_str() -> String {
generate_uuid()
.to_hyphenated()
.encode_upper(&mut Uuid::encode_buffer())
.to_owned()
}
pub fn fuzzy_vec_match(search: &str, values: &[String]) -> Option<Vec<String>> {
let join = values.join("");
let result = match fuzzy::best_match(search, &join) {
Some(result) => result,
None => return None,
};
let mut start_index = 0;
let vec: Vec<String> = values
.iter()
.map(|v| {
let len = v.chars().count();
let next_start_index = start_index + len;
let matches = result
.matches()
.iter()
.filter(|i| start_index <= **i && **i < next_start_index)
.map(|i| *i - start_index)
.collect();
let m = fuzzy::Match::with(result.score(), matches);
start_index = next_start_index;
fuzzy::format_simple(&m, v, "<b>", "</b>")
})
.collect();
Some(vec)
}
|
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - RCC clock control register"]
pub cr: CR,
_reserved1: [u8; 0x0c],
#[doc = "0x10 - RCC HSI calibration register"]
pub hsicfgr: HSICFGR,
#[doc = "0x14 - RCC clock recovery RC register"]
pub crrcr: CRRCR,
#[doc = "0x18 - RCC CSI calibration register"]
pub csicfgr: CSICFGR,
#[doc = "0x1c - RCC clock configuration register"]
pub cfgr: CFGR,
#[doc = "0x20 - RCC CPU domain clock configuration register 2"]
pub cfgr2: CFGR2,
_reserved6: [u8; 0x04],
#[doc = "0x28 - RCC PLL clock source selection register"]
pub pll1cfgr: PLL1CFGR,
#[doc = "0x2c - RCC PLL clock source selection register"]
pub pll2cfgr: PLL2CFGR,
#[doc = "0x30 - RCC PLL clock source selection register"]
pub pll3cfgr: PLL3CFGR,
#[doc = "0x34 - RCC PLL1 dividers register"]
pub pll1divr: PLL1DIVR,
#[doc = "0x38 - RCC PLL1 fractional divider register"]
pub pll1fracr: PLL1FRACR,
#[doc = "0x3c - RCC PLL1 dividers register"]
pub pll2divr: PLL2DIVR,
#[doc = "0x40 - RCC PLL2 fractional divider register"]
pub pll2fracr: PLL2FRACR,
#[doc = "0x44 - RCC PLL3 dividers register"]
pub pll3divr: PLL3DIVR,
#[doc = "0x48 - RCC PLL3 fractional divider register"]
pub pll3fracr: PLL3FRACR,
_reserved15: [u8; 0x04],
#[doc = "0x50 - RCC clock source interrupt enable register"]
pub cier: CIER,
#[doc = "0x54 - RCC clock source interrupt flag register"]
pub cifr: CIFR,
#[doc = "0x58 - RCC clock source interrupt clear register"]
pub cicr: CICR,
_reserved18: [u8; 0x04],
#[doc = "0x60 - RCC AHB1 reset register"]
pub ahb1rstr: AHB1RSTR,
#[doc = "0x64 - RCC AHB2 peripheral reset register"]
pub ahb2rstr: AHB2RSTR,
_reserved20: [u8; 0x04],
#[doc = "0x6c - RCC AHB4 peripheral reset register"]
pub ahb4rstr: AHB4RSTR,
_reserved21: [u8; 0x04],
#[doc = "0x74 - RCC APB1 peripheral low reset register"]
pub apb1lrstr: APB1LRSTR,
#[doc = "0x78 - RCC APB1 peripheral high reset register"]
pub apb1hrstr: APB1HRSTR,
#[doc = "0x7c - RCC APB2 peripheral reset register"]
pub apb2rstr: APB2RSTR,
#[doc = "0x80 - RCC APB4 peripheral reset register"]
pub apb3rstr: APB3RSTR,
_reserved25: [u8; 0x04],
#[doc = "0x88 - RCC AHB1 peripherals clock register"]
pub ahb1enr: AHB1ENR,
#[doc = "0x8c - RCC AHB2 peripheral clock register"]
pub ahb2enr: AHB2ENR,
_reserved27: [u8; 0x04],
#[doc = "0x94 - RCC AHB4 peripheral clock register"]
pub ahb4enr: AHB4ENR,
_reserved28: [u8; 0x04],
#[doc = "0x9c - RCC APB1 peripheral clock register"]
pub apb1lenr: APB1LENR,
#[doc = "0xa0 - RCC APB1 peripheral clock register"]
pub apb1henr: APB1HENR,
#[doc = "0xa4 - RCC APB2 peripheral clock register"]
pub apb2enr: APB2ENR,
#[doc = "0xa8 - RCC APB4 peripheral clock register"]
pub apb3enr: APB3ENR,
_reserved32: [u8; 0x04],
#[doc = "0xb0 - RCC AHB1 sleep clock register"]
pub ahb1lpenr: AHB1LPENR,
#[doc = "0xb4 - RCC AHB2 sleep clock register"]
pub ahb2lpenr: AHB2LPENR,
_reserved34: [u8; 0x04],
#[doc = "0xbc - RCC AHB4 sleep clock register"]
pub ahb4lpenr: AHB4LPENR,
_reserved35: [u8; 0x04],
#[doc = "0xc4 - RCC APB1 sleep clock register"]
pub apb1llpenr: APB1LLPENR,
#[doc = "0xc8 - RCC APB1 sleep clock register"]
pub apb1hlpenr: APB1HLPENR,
#[doc = "0xcc - RCC APB2 sleep clock register"]
pub apb2lpenr: APB2LPENR,
#[doc = "0xd0 - RCC APB4 sleep clock register"]
pub apb3lpenr: APB3LPENR,
_reserved39: [u8; 0x04],
#[doc = "0xd8 - RCC kernel clock configuration register"]
pub ccipr1: CCIPR1,
#[doc = "0xdc - RCC kernel clock configuration register"]
pub ccipr2: CCIPR2,
#[doc = "0xe0 - RCC kernel clock configuration register"]
pub ccipr3: CCIPR3,
#[doc = "0xe4 - RCC kernel clock configuration register"]
pub ccipr4: CCIPR4,
#[doc = "0xe8 - RCC kernel clock configuration register"]
pub ccipr5: CCIPR5,
_reserved44: [u8; 0x04],
#[doc = "0xf0 - RCC Backup domain control register"]
pub bdcr: BDCR,
#[doc = "0xf4 - RCC reset status register"]
pub rsr: RSR,
_reserved46: [u8; 0x18],
#[doc = "0x110 - RCC secure configuration register"]
pub seccfgr: SECCFGR,
#[doc = "0x114 - RCC privilege configuration register"]
pub privcfgr: PRIVCFGR,
}
#[doc = "CR (rw) register accessor: RCC clock control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cr::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`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cr`]
module"]
pub type CR = crate::Reg<cr::CR_SPEC>;
#[doc = "RCC clock control register"]
pub mod cr;
#[doc = "HSICFGR (rw) register accessor: RCC HSI calibration register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`hsicfgr::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 [`hsicfgr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`hsicfgr`]
module"]
pub type HSICFGR = crate::Reg<hsicfgr::HSICFGR_SPEC>;
#[doc = "RCC HSI calibration register"]
pub mod hsicfgr;
#[doc = "CRRCR (r) register accessor: RCC clock recovery RC register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`crrcr::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`crrcr`]
module"]
pub type CRRCR = crate::Reg<crrcr::CRRCR_SPEC>;
#[doc = "RCC clock recovery RC register"]
pub mod crrcr;
#[doc = "CSICFGR (rw) register accessor: RCC CSI calibration register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`csicfgr::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 [`csicfgr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`csicfgr`]
module"]
pub type CSICFGR = crate::Reg<csicfgr::CSICFGR_SPEC>;
#[doc = "RCC CSI calibration register"]
pub mod csicfgr;
#[doc = "CFGR (rw) register accessor: RCC clock configuration register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cfgr::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 [`cfgr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cfgr`]
module"]
pub type CFGR = crate::Reg<cfgr::CFGR_SPEC>;
#[doc = "RCC clock configuration register"]
pub mod cfgr;
#[doc = "CFGR2 (rw) register accessor: RCC CPU domain clock configuration register 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cfgr2::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 [`cfgr2::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cfgr2`]
module"]
pub type CFGR2 = crate::Reg<cfgr2::CFGR2_SPEC>;
#[doc = "RCC CPU domain clock configuration register 2"]
pub mod cfgr2;
#[doc = "PLL1CFGR (rw) register accessor: RCC PLL clock source selection register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`pll1cfgr::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 [`pll1cfgr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`pll1cfgr`]
module"]
pub type PLL1CFGR = crate::Reg<pll1cfgr::PLL1CFGR_SPEC>;
#[doc = "RCC PLL clock source selection register"]
pub mod pll1cfgr;
#[doc = "PLL2CFGR (rw) register accessor: RCC PLL clock source selection register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`pll2cfgr::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 [`pll2cfgr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`pll2cfgr`]
module"]
pub type PLL2CFGR = crate::Reg<pll2cfgr::PLL2CFGR_SPEC>;
#[doc = "RCC PLL clock source selection register"]
pub mod pll2cfgr;
#[doc = "PLL3CFGR (rw) register accessor: RCC PLL clock source selection register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`pll3cfgr::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 [`pll3cfgr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`pll3cfgr`]
module"]
pub type PLL3CFGR = crate::Reg<pll3cfgr::PLL3CFGR_SPEC>;
#[doc = "RCC PLL clock source selection register"]
pub mod pll3cfgr;
#[doc = "PLL1DIVR (rw) register accessor: RCC PLL1 dividers register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`pll1divr::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 [`pll1divr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`pll1divr`]
module"]
pub type PLL1DIVR = crate::Reg<pll1divr::PLL1DIVR_SPEC>;
#[doc = "RCC PLL1 dividers register"]
pub mod pll1divr;
#[doc = "PLL1FRACR (rw) register accessor: RCC PLL1 fractional divider register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`pll1fracr::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 [`pll1fracr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`pll1fracr`]
module"]
pub type PLL1FRACR = crate::Reg<pll1fracr::PLL1FRACR_SPEC>;
#[doc = "RCC PLL1 fractional divider register"]
pub mod pll1fracr;
#[doc = "PLL2DIVR (rw) register accessor: RCC PLL1 dividers register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`pll2divr::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 [`pll2divr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`pll2divr`]
module"]
pub type PLL2DIVR = crate::Reg<pll2divr::PLL2DIVR_SPEC>;
#[doc = "RCC PLL1 dividers register"]
pub mod pll2divr;
#[doc = "PLL2FRACR (rw) register accessor: RCC PLL2 fractional divider register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`pll2fracr::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 [`pll2fracr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`pll2fracr`]
module"]
pub type PLL2FRACR = crate::Reg<pll2fracr::PLL2FRACR_SPEC>;
#[doc = "RCC PLL2 fractional divider register"]
pub mod pll2fracr;
#[doc = "PLL3DIVR (rw) register accessor: RCC PLL3 dividers register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`pll3divr::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 [`pll3divr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`pll3divr`]
module"]
pub type PLL3DIVR = crate::Reg<pll3divr::PLL3DIVR_SPEC>;
#[doc = "RCC PLL3 dividers register"]
pub mod pll3divr;
#[doc = "PLL3FRACR (rw) register accessor: RCC PLL3 fractional divider register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`pll3fracr::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 [`pll3fracr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`pll3fracr`]
module"]
pub type PLL3FRACR = crate::Reg<pll3fracr::PLL3FRACR_SPEC>;
#[doc = "RCC PLL3 fractional divider register"]
pub mod pll3fracr;
#[doc = "CIER (rw) register accessor: RCC clock source interrupt enable register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cier::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 [`cier::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cier`]
module"]
pub type CIER = crate::Reg<cier::CIER_SPEC>;
#[doc = "RCC clock source interrupt enable register"]
pub mod cier;
#[doc = "CIFR (r) register accessor: RCC clock source interrupt flag register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cifr::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cifr`]
module"]
pub type CIFR = crate::Reg<cifr::CIFR_SPEC>;
#[doc = "RCC clock source interrupt flag register"]
pub mod cifr;
#[doc = "CICR (rw) register accessor: RCC clock source interrupt clear register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cicr::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 [`cicr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cicr`]
module"]
pub type CICR = crate::Reg<cicr::CICR_SPEC>;
#[doc = "RCC clock source interrupt clear register"]
pub mod cicr;
#[doc = "AHB1RSTR (rw) register accessor: RCC AHB1 reset register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ahb1rstr::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 [`ahb1rstr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`ahb1rstr`]
module"]
pub type AHB1RSTR = crate::Reg<ahb1rstr::AHB1RSTR_SPEC>;
#[doc = "RCC AHB1 reset register"]
pub mod ahb1rstr;
#[doc = "AHB2RSTR (rw) register accessor: RCC AHB2 peripheral reset register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ahb2rstr::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 [`ahb2rstr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`ahb2rstr`]
module"]
pub type AHB2RSTR = crate::Reg<ahb2rstr::AHB2RSTR_SPEC>;
#[doc = "RCC AHB2 peripheral reset register"]
pub mod ahb2rstr;
#[doc = "AHB4RSTR (rw) register accessor: RCC AHB4 peripheral reset register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ahb4rstr::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 [`ahb4rstr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`ahb4rstr`]
module"]
pub type AHB4RSTR = crate::Reg<ahb4rstr::AHB4RSTR_SPEC>;
#[doc = "RCC AHB4 peripheral reset register"]
pub mod ahb4rstr;
#[doc = "APB1LRSTR (rw) register accessor: RCC APB1 peripheral low reset register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`apb1lrstr::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 [`apb1lrstr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`apb1lrstr`]
module"]
pub type APB1LRSTR = crate::Reg<apb1lrstr::APB1LRSTR_SPEC>;
#[doc = "RCC APB1 peripheral low reset register"]
pub mod apb1lrstr;
#[doc = "APB1HRSTR (rw) register accessor: RCC APB1 peripheral high reset register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`apb1hrstr::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 [`apb1hrstr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`apb1hrstr`]
module"]
pub type APB1HRSTR = crate::Reg<apb1hrstr::APB1HRSTR_SPEC>;
#[doc = "RCC APB1 peripheral high reset register"]
pub mod apb1hrstr;
#[doc = "APB2RSTR (rw) register accessor: RCC APB2 peripheral reset register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`apb2rstr::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 [`apb2rstr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`apb2rstr`]
module"]
pub type APB2RSTR = crate::Reg<apb2rstr::APB2RSTR_SPEC>;
#[doc = "RCC APB2 peripheral reset register"]
pub mod apb2rstr;
#[doc = "APB3RSTR (rw) register accessor: RCC APB4 peripheral reset register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`apb3rstr::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 [`apb3rstr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`apb3rstr`]
module"]
pub type APB3RSTR = crate::Reg<apb3rstr::APB3RSTR_SPEC>;
#[doc = "RCC APB4 peripheral reset register"]
pub mod apb3rstr;
#[doc = "AHB1ENR (rw) register accessor: RCC AHB1 peripherals clock register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ahb1enr::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 [`ahb1enr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`ahb1enr`]
module"]
pub type AHB1ENR = crate::Reg<ahb1enr::AHB1ENR_SPEC>;
#[doc = "RCC AHB1 peripherals clock register"]
pub mod ahb1enr;
#[doc = "AHB2ENR (rw) register accessor: RCC AHB2 peripheral clock register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ahb2enr::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 [`ahb2enr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`ahb2enr`]
module"]
pub type AHB2ENR = crate::Reg<ahb2enr::AHB2ENR_SPEC>;
#[doc = "RCC AHB2 peripheral clock register"]
pub mod ahb2enr;
#[doc = "AHB4ENR (rw) register accessor: RCC AHB4 peripheral clock register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ahb4enr::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 [`ahb4enr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`ahb4enr`]
module"]
pub type AHB4ENR = crate::Reg<ahb4enr::AHB4ENR_SPEC>;
#[doc = "RCC AHB4 peripheral clock register"]
pub mod ahb4enr;
#[doc = "APB1LENR (rw) register accessor: RCC APB1 peripheral clock register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`apb1lenr::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 [`apb1lenr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`apb1lenr`]
module"]
pub type APB1LENR = crate::Reg<apb1lenr::APB1LENR_SPEC>;
#[doc = "RCC APB1 peripheral clock register"]
pub mod apb1lenr;
#[doc = "APB1HENR (rw) register accessor: RCC APB1 peripheral clock register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`apb1henr::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 [`apb1henr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`apb1henr`]
module"]
pub type APB1HENR = crate::Reg<apb1henr::APB1HENR_SPEC>;
#[doc = "RCC APB1 peripheral clock register"]
pub mod apb1henr;
#[doc = "APB2ENR (rw) register accessor: RCC APB2 peripheral clock register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`apb2enr::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 [`apb2enr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`apb2enr`]
module"]
pub type APB2ENR = crate::Reg<apb2enr::APB2ENR_SPEC>;
#[doc = "RCC APB2 peripheral clock register"]
pub mod apb2enr;
#[doc = "APB3ENR (rw) register accessor: RCC APB4 peripheral clock register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`apb3enr::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 [`apb3enr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`apb3enr`]
module"]
pub type APB3ENR = crate::Reg<apb3enr::APB3ENR_SPEC>;
#[doc = "RCC APB4 peripheral clock register"]
pub mod apb3enr;
#[doc = "AHB1LPENR (rw) register accessor: RCC AHB1 sleep clock register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ahb1lpenr::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 [`ahb1lpenr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`ahb1lpenr`]
module"]
pub type AHB1LPENR = crate::Reg<ahb1lpenr::AHB1LPENR_SPEC>;
#[doc = "RCC AHB1 sleep clock register"]
pub mod ahb1lpenr;
#[doc = "AHB2LPENR (rw) register accessor: RCC AHB2 sleep clock register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ahb2lpenr::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 [`ahb2lpenr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`ahb2lpenr`]
module"]
pub type AHB2LPENR = crate::Reg<ahb2lpenr::AHB2LPENR_SPEC>;
#[doc = "RCC AHB2 sleep clock register"]
pub mod ahb2lpenr;
#[doc = "AHB4LPENR (rw) register accessor: RCC AHB4 sleep clock register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ahb4lpenr::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 [`ahb4lpenr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`ahb4lpenr`]
module"]
pub type AHB4LPENR = crate::Reg<ahb4lpenr::AHB4LPENR_SPEC>;
#[doc = "RCC AHB4 sleep clock register"]
pub mod ahb4lpenr;
#[doc = "APB1LLPENR (rw) register accessor: RCC APB1 sleep clock register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`apb1llpenr::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 [`apb1llpenr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`apb1llpenr`]
module"]
pub type APB1LLPENR = crate::Reg<apb1llpenr::APB1LLPENR_SPEC>;
#[doc = "RCC APB1 sleep clock register"]
pub mod apb1llpenr;
#[doc = "APB1HLPENR (rw) register accessor: RCC APB1 sleep clock register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`apb1hlpenr::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 [`apb1hlpenr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`apb1hlpenr`]
module"]
pub type APB1HLPENR = crate::Reg<apb1hlpenr::APB1HLPENR_SPEC>;
#[doc = "RCC APB1 sleep clock register"]
pub mod apb1hlpenr;
#[doc = "APB2LPENR (rw) register accessor: RCC APB2 sleep clock register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`apb2lpenr::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 [`apb2lpenr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`apb2lpenr`]
module"]
pub type APB2LPENR = crate::Reg<apb2lpenr::APB2LPENR_SPEC>;
#[doc = "RCC APB2 sleep clock register"]
pub mod apb2lpenr;
#[doc = "APB3LPENR (rw) register accessor: RCC APB4 sleep clock register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`apb3lpenr::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 [`apb3lpenr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`apb3lpenr`]
module"]
pub type APB3LPENR = crate::Reg<apb3lpenr::APB3LPENR_SPEC>;
#[doc = "RCC APB4 sleep clock register"]
pub mod apb3lpenr;
#[doc = "CCIPR1 (rw) register accessor: RCC kernel clock configuration register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ccipr1::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 [`ccipr1::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`ccipr1`]
module"]
pub type CCIPR1 = crate::Reg<ccipr1::CCIPR1_SPEC>;
#[doc = "RCC kernel clock configuration register"]
pub mod ccipr1;
#[doc = "CCIPR2 (rw) register accessor: RCC kernel clock configuration register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ccipr2::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 [`ccipr2::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`ccipr2`]
module"]
pub type CCIPR2 = crate::Reg<ccipr2::CCIPR2_SPEC>;
#[doc = "RCC kernel clock configuration register"]
pub mod ccipr2;
#[doc = "CCIPR3 (rw) register accessor: RCC kernel clock configuration register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ccipr3::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 [`ccipr3::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`ccipr3`]
module"]
pub type CCIPR3 = crate::Reg<ccipr3::CCIPR3_SPEC>;
#[doc = "RCC kernel clock configuration register"]
pub mod ccipr3;
#[doc = "CCIPR4 (rw) register accessor: RCC kernel clock configuration register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ccipr4::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 [`ccipr4::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`ccipr4`]
module"]
pub type CCIPR4 = crate::Reg<ccipr4::CCIPR4_SPEC>;
#[doc = "RCC kernel clock configuration register"]
pub mod ccipr4;
#[doc = "CCIPR5 (rw) register accessor: RCC kernel clock configuration register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ccipr5::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 [`ccipr5::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`ccipr5`]
module"]
pub type CCIPR5 = crate::Reg<ccipr5::CCIPR5_SPEC>;
#[doc = "RCC kernel clock configuration register"]
pub mod ccipr5;
#[doc = "BDCR (rw) register accessor: RCC Backup domain control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`bdcr::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 [`bdcr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`bdcr`]
module"]
pub type BDCR = crate::Reg<bdcr::BDCR_SPEC>;
#[doc = "RCC Backup domain control register"]
pub mod bdcr;
#[doc = "RSR (rw) register accessor: RCC reset status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`rsr::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 [`rsr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`rsr`]
module"]
pub type RSR = crate::Reg<rsr::RSR_SPEC>;
#[doc = "RCC reset status register"]
pub mod rsr;
#[doc = "SECCFGR (rw) register accessor: RCC secure configuration register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`seccfgr::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 [`seccfgr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`seccfgr`]
module"]
pub type SECCFGR = crate::Reg<seccfgr::SECCFGR_SPEC>;
#[doc = "RCC secure configuration register"]
pub mod seccfgr;
#[doc = "PRIVCFGR (rw) register accessor: RCC privilege configuration register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`privcfgr::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 [`privcfgr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`privcfgr`]
module"]
pub type PRIVCFGR = crate::Reg<privcfgr::PRIVCFGR_SPEC>;
#[doc = "RCC privilege configuration register"]
pub mod privcfgr;
|
#[doc = "Reader of register RCC_TZAHB6RSTCLRR"]
pub type R = crate::R<u32, super::RCC_TZAHB6RSTCLRR>;
#[doc = "Writer for register RCC_TZAHB6RSTCLRR"]
pub type W = crate::W<u32, super::RCC_TZAHB6RSTCLRR>;
#[doc = "Register RCC_TZAHB6RSTCLRR `reset()`'s with value 0"]
impl crate::ResetValue for super::RCC_TZAHB6RSTCLRR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "MDMARST\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum MDMARST_A {
#[doc = "0: Writing has no effect, reading means\r\n that the block reset is released"]
B_0X0 = 0,
#[doc = "1: Writing releases the block reset,\r\n reading means that the block reset is\r\n asserted"]
B_0X1 = 1,
}
impl From<MDMARST_A> for bool {
#[inline(always)]
fn from(variant: MDMARST_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `MDMARST`"]
pub type MDMARST_R = crate::R<bool, MDMARST_A>;
impl MDMARST_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> MDMARST_A {
match self.bits {
false => MDMARST_A::B_0X0,
true => MDMARST_A::B_0X1,
}
}
#[doc = "Checks if the value of the field is `B_0X0`"]
#[inline(always)]
pub fn is_b_0x0(&self) -> bool {
*self == MDMARST_A::B_0X0
}
#[doc = "Checks if the value of the field is `B_0X1`"]
#[inline(always)]
pub fn is_b_0x1(&self) -> bool {
*self == MDMARST_A::B_0X1
}
}
#[doc = "Write proxy for field `MDMARST`"]
pub struct MDMARST_W<'a> {
w: &'a mut W,
}
impl<'a> MDMARST_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: MDMARST_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Writing has no effect, reading means that the block reset is released"]
#[inline(always)]
pub fn b_0x0(self) -> &'a mut W {
self.variant(MDMARST_A::B_0X0)
}
#[doc = "Writing releases the block reset, reading means that the block reset is asserted"]
#[inline(always)]
pub fn b_0x1(self) -> &'a mut W {
self.variant(MDMARST_A::B_0X1)
}
#[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
}
}
impl R {
#[doc = "Bit 0 - MDMARST"]
#[inline(always)]
pub fn mdmarst(&self) -> MDMARST_R {
MDMARST_R::new((self.bits & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - MDMARST"]
#[inline(always)]
pub fn mdmarst(&mut self) -> MDMARST_W {
MDMARST_W { w: self }
}
}
|
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - Control"]
pub ctl: CTL,
_reserved1: [u8; 12usize],
#[doc = "0x10 - Command"]
pub cmd: CMD,
_reserved2: [u8; 12usize],
#[doc = "0x20 - Sequencer Default value"]
pub seq_default: SEQ_DEFAULT,
_reserved3: [u8; 28usize],
#[doc = "0x40 - Sequencer read control 0"]
pub seq_read_ctl_0: SEQ_READ_CTL_0,
#[doc = "0x44 - Sequencer read control 1"]
pub seq_read_ctl_1: SEQ_READ_CTL_1,
#[doc = "0x48 - Sequencer read control 2"]
pub seq_read_ctl_2: SEQ_READ_CTL_2,
#[doc = "0x4c - Sequencer read control 3"]
pub seq_read_ctl_3: SEQ_READ_CTL_3,
#[doc = "0x50 - Sequencer read control 4"]
pub seq_read_ctl_4: SEQ_READ_CTL_4,
#[doc = "0x54 - Sequencer read control 5"]
pub seq_read_ctl_5: SEQ_READ_CTL_5,
_reserved9: [u8; 8usize],
#[doc = "0x60 - Sequencer program control 0"]
pub seq_program_ctl_0: SEQ_PROGRAM_CTL_0,
#[doc = "0x64 - Sequencer program control 1"]
pub seq_program_ctl_1: SEQ_PROGRAM_CTL_1,
#[doc = "0x68 - Sequencer program control 2"]
pub seq_program_ctl_2: SEQ_PROGRAM_CTL_2,
#[doc = "0x6c - Sequencer program control 3"]
pub seq_program_ctl_3: SEQ_PROGRAM_CTL_3,
#[doc = "0x70 - Sequencer program control 4"]
pub seq_program_ctl_4: SEQ_PROGRAM_CTL_4,
#[doc = "0x74 - Sequencer program control 5"]
pub seq_program_ctl_5: SEQ_PROGRAM_CTL_5,
}
#[doc = "Control\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 avaliable fields see [ctl](ctl) module"]
pub type CTL = crate::Reg<u32, _CTL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CTL;
#[doc = "`read()` method returns [ctl::R](ctl::R) reader structure"]
impl crate::Readable for CTL {}
#[doc = "`write(|w| ..)` method takes [ctl::W](ctl::W) writer structure"]
impl crate::Writable for CTL {}
#[doc = "Control"]
pub mod ctl;
#[doc = "Command\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 avaliable fields see [cmd](cmd) module"]
pub type CMD = crate::Reg<u32, _CMD>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CMD;
#[doc = "`read()` method returns [cmd::R](cmd::R) reader structure"]
impl crate::Readable for CMD {}
#[doc = "`write(|w| ..)` method takes [cmd::W](cmd::W) writer structure"]
impl crate::Writable for CMD {}
#[doc = "Command"]
pub mod cmd;
#[doc = "Sequencer Default value\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 avaliable fields see [seq_default](seq_default) module"]
pub type SEQ_DEFAULT = crate::Reg<u32, _SEQ_DEFAULT>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SEQ_DEFAULT;
#[doc = "`read()` method returns [seq_default::R](seq_default::R) reader structure"]
impl crate::Readable for SEQ_DEFAULT {}
#[doc = "`write(|w| ..)` method takes [seq_default::W](seq_default::W) writer structure"]
impl crate::Writable for SEQ_DEFAULT {}
#[doc = "Sequencer Default value"]
pub mod seq_default;
#[doc = "Sequencer read control 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 avaliable fields see [seq_read_ctl_0](seq_read_ctl_0) module"]
pub type SEQ_READ_CTL_0 = crate::Reg<u32, _SEQ_READ_CTL_0>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SEQ_READ_CTL_0;
#[doc = "`read()` method returns [seq_read_ctl_0::R](seq_read_ctl_0::R) reader structure"]
impl crate::Readable for SEQ_READ_CTL_0 {}
#[doc = "`write(|w| ..)` method takes [seq_read_ctl_0::W](seq_read_ctl_0::W) writer structure"]
impl crate::Writable for SEQ_READ_CTL_0 {}
#[doc = "Sequencer read control 0"]
pub mod seq_read_ctl_0;
#[doc = "Sequencer read control 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 avaliable fields see [seq_read_ctl_1](seq_read_ctl_1) module"]
pub type SEQ_READ_CTL_1 = crate::Reg<u32, _SEQ_READ_CTL_1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SEQ_READ_CTL_1;
#[doc = "`read()` method returns [seq_read_ctl_1::R](seq_read_ctl_1::R) reader structure"]
impl crate::Readable for SEQ_READ_CTL_1 {}
#[doc = "`write(|w| ..)` method takes [seq_read_ctl_1::W](seq_read_ctl_1::W) writer structure"]
impl crate::Writable for SEQ_READ_CTL_1 {}
#[doc = "Sequencer read control 1"]
pub mod seq_read_ctl_1;
#[doc = "Sequencer read control 2\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 avaliable fields see [seq_read_ctl_2](seq_read_ctl_2) module"]
pub type SEQ_READ_CTL_2 = crate::Reg<u32, _SEQ_READ_CTL_2>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SEQ_READ_CTL_2;
#[doc = "`read()` method returns [seq_read_ctl_2::R](seq_read_ctl_2::R) reader structure"]
impl crate::Readable for SEQ_READ_CTL_2 {}
#[doc = "`write(|w| ..)` method takes [seq_read_ctl_2::W](seq_read_ctl_2::W) writer structure"]
impl crate::Writable for SEQ_READ_CTL_2 {}
#[doc = "Sequencer read control 2"]
pub mod seq_read_ctl_2;
#[doc = "Sequencer read control 3\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 avaliable fields see [seq_read_ctl_3](seq_read_ctl_3) module"]
pub type SEQ_READ_CTL_3 = crate::Reg<u32, _SEQ_READ_CTL_3>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SEQ_READ_CTL_3;
#[doc = "`read()` method returns [seq_read_ctl_3::R](seq_read_ctl_3::R) reader structure"]
impl crate::Readable for SEQ_READ_CTL_3 {}
#[doc = "`write(|w| ..)` method takes [seq_read_ctl_3::W](seq_read_ctl_3::W) writer structure"]
impl crate::Writable for SEQ_READ_CTL_3 {}
#[doc = "Sequencer read control 3"]
pub mod seq_read_ctl_3;
#[doc = "Sequencer read control 4\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 avaliable fields see [seq_read_ctl_4](seq_read_ctl_4) module"]
pub type SEQ_READ_CTL_4 = crate::Reg<u32, _SEQ_READ_CTL_4>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SEQ_READ_CTL_4;
#[doc = "`read()` method returns [seq_read_ctl_4::R](seq_read_ctl_4::R) reader structure"]
impl crate::Readable for SEQ_READ_CTL_4 {}
#[doc = "`write(|w| ..)` method takes [seq_read_ctl_4::W](seq_read_ctl_4::W) writer structure"]
impl crate::Writable for SEQ_READ_CTL_4 {}
#[doc = "Sequencer read control 4"]
pub mod seq_read_ctl_4;
#[doc = "Sequencer read control 5\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 avaliable fields see [seq_read_ctl_5](seq_read_ctl_5) module"]
pub type SEQ_READ_CTL_5 = crate::Reg<u32, _SEQ_READ_CTL_5>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SEQ_READ_CTL_5;
#[doc = "`read()` method returns [seq_read_ctl_5::R](seq_read_ctl_5::R) reader structure"]
impl crate::Readable for SEQ_READ_CTL_5 {}
#[doc = "`write(|w| ..)` method takes [seq_read_ctl_5::W](seq_read_ctl_5::W) writer structure"]
impl crate::Writable for SEQ_READ_CTL_5 {}
#[doc = "Sequencer read control 5"]
pub mod seq_read_ctl_5;
#[doc = "Sequencer program control 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 avaliable fields see [seq_program_ctl_0](seq_program_ctl_0) module"]
pub type SEQ_PROGRAM_CTL_0 = crate::Reg<u32, _SEQ_PROGRAM_CTL_0>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SEQ_PROGRAM_CTL_0;
#[doc = "`read()` method returns [seq_program_ctl_0::R](seq_program_ctl_0::R) reader structure"]
impl crate::Readable for SEQ_PROGRAM_CTL_0 {}
#[doc = "`write(|w| ..)` method takes [seq_program_ctl_0::W](seq_program_ctl_0::W) writer structure"]
impl crate::Writable for SEQ_PROGRAM_CTL_0 {}
#[doc = "Sequencer program control 0"]
pub mod seq_program_ctl_0;
#[doc = "Sequencer program control 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 avaliable fields see [seq_program_ctl_1](seq_program_ctl_1) module"]
pub type SEQ_PROGRAM_CTL_1 = crate::Reg<u32, _SEQ_PROGRAM_CTL_1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SEQ_PROGRAM_CTL_1;
#[doc = "`read()` method returns [seq_program_ctl_1::R](seq_program_ctl_1::R) reader structure"]
impl crate::Readable for SEQ_PROGRAM_CTL_1 {}
#[doc = "`write(|w| ..)` method takes [seq_program_ctl_1::W](seq_program_ctl_1::W) writer structure"]
impl crate::Writable for SEQ_PROGRAM_CTL_1 {}
#[doc = "Sequencer program control 1"]
pub mod seq_program_ctl_1;
#[doc = "Sequencer program control 2\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 avaliable fields see [seq_program_ctl_2](seq_program_ctl_2) module"]
pub type SEQ_PROGRAM_CTL_2 = crate::Reg<u32, _SEQ_PROGRAM_CTL_2>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SEQ_PROGRAM_CTL_2;
#[doc = "`read()` method returns [seq_program_ctl_2::R](seq_program_ctl_2::R) reader structure"]
impl crate::Readable for SEQ_PROGRAM_CTL_2 {}
#[doc = "`write(|w| ..)` method takes [seq_program_ctl_2::W](seq_program_ctl_2::W) writer structure"]
impl crate::Writable for SEQ_PROGRAM_CTL_2 {}
#[doc = "Sequencer program control 2"]
pub mod seq_program_ctl_2;
#[doc = "Sequencer program control 3\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 avaliable fields see [seq_program_ctl_3](seq_program_ctl_3) module"]
pub type SEQ_PROGRAM_CTL_3 = crate::Reg<u32, _SEQ_PROGRAM_CTL_3>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SEQ_PROGRAM_CTL_3;
#[doc = "`read()` method returns [seq_program_ctl_3::R](seq_program_ctl_3::R) reader structure"]
impl crate::Readable for SEQ_PROGRAM_CTL_3 {}
#[doc = "`write(|w| ..)` method takes [seq_program_ctl_3::W](seq_program_ctl_3::W) writer structure"]
impl crate::Writable for SEQ_PROGRAM_CTL_3 {}
#[doc = "Sequencer program control 3"]
pub mod seq_program_ctl_3;
#[doc = "Sequencer program control 4\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 avaliable fields see [seq_program_ctl_4](seq_program_ctl_4) module"]
pub type SEQ_PROGRAM_CTL_4 = crate::Reg<u32, _SEQ_PROGRAM_CTL_4>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SEQ_PROGRAM_CTL_4;
#[doc = "`read()` method returns [seq_program_ctl_4::R](seq_program_ctl_4::R) reader structure"]
impl crate::Readable for SEQ_PROGRAM_CTL_4 {}
#[doc = "`write(|w| ..)` method takes [seq_program_ctl_4::W](seq_program_ctl_4::W) writer structure"]
impl crate::Writable for SEQ_PROGRAM_CTL_4 {}
#[doc = "Sequencer program control 4"]
pub mod seq_program_ctl_4;
#[doc = "Sequencer program control 5\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 avaliable fields see [seq_program_ctl_5](seq_program_ctl_5) module"]
pub type SEQ_PROGRAM_CTL_5 = crate::Reg<u32, _SEQ_PROGRAM_CTL_5>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SEQ_PROGRAM_CTL_5;
#[doc = "`read()` method returns [seq_program_ctl_5::R](seq_program_ctl_5::R) reader structure"]
impl crate::Readable for SEQ_PROGRAM_CTL_5 {}
#[doc = "`write(|w| ..)` method takes [seq_program_ctl_5::W](seq_program_ctl_5::W) writer structure"]
impl crate::Writable for SEQ_PROGRAM_CTL_5 {}
#[doc = "Sequencer program control 5"]
pub mod seq_program_ctl_5;
|
use crate::flow;
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
// TODO: Add pretty printing
pub struct GlobalConfig {
pub window: WindowConfig,
pub flow: flow::Uniforms,
}
#[derive(Debug, Copy, Clone, Serialize, Deserialize)]
pub struct WindowConfig {
pub msaa: u32,
}
|
use crate::{inner::Inner, values::Values, Aliased};
use left_right::ReadGuard;
use std::borrow::Borrow;
use std::collections::hash_map::RandomState;
use std::fmt;
use std::hash::{BuildHasher, Hash};
use std::iter::FromIterator;
mod read_ref;
pub use read_ref::{MapReadRef, ReadGuardIter};
mod factory;
pub use factory::ReadHandleFactory;
/// A handle that may be used to read from the eventually consistent map.
///
/// Note that any changes made to the map will not be made visible until the writer calls
/// [`publish`](crate::WriteHandle::publish). In other words, all operations performed on a
/// `ReadHandle` will *only* see writes to the map that preceeded the last call to `publish`.
pub struct ReadHandle<K, V, M = (), S = RandomState>
where
K: Eq + Hash,
S: BuildHasher,
{
pub(crate) handle: left_right::ReadHandle<Inner<K, V, M, S>>,
}
impl<K, V, M, S> fmt::Debug for ReadHandle<K, V, M, S>
where
K: Eq + Hash + fmt::Debug,
S: BuildHasher,
M: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ReadHandle")
.field("handle", &self.handle)
.finish()
}
}
impl<K, V, M, S> Clone for ReadHandle<K, V, M, S>
where
K: Eq + Hash,
S: BuildHasher,
{
fn clone(&self) -> Self {
Self {
handle: self.handle.clone(),
}
}
}
impl<K, V, M, S> ReadHandle<K, V, M, S>
where
K: Eq + Hash,
S: BuildHasher,
{
pub(crate) fn new(handle: left_right::ReadHandle<Inner<K, V, M, S>>) -> Self {
Self { handle }
}
}
impl<K, V, M, S> ReadHandle<K, V, M, S>
where
K: Eq + Hash,
V: Eq + Hash,
S: BuildHasher,
M: Clone,
{
/// Take out a guarded live reference to the read side of the map.
///
/// This lets you perform more complex read operations on the map.
///
/// While the reference lives, changes to the map cannot be published.
///
/// If no publish has happened, or the map has been destroyed, this function returns `None`.
///
/// See [`MapReadRef`].
pub fn enter(&self) -> Option<MapReadRef<'_, K, V, M, S>> {
let guard = self.handle.enter()?;
if !guard.ready {
return None;
}
Some(MapReadRef { guard })
}
/// Returns the number of non-empty keys present in the map.
pub fn len(&self) -> usize {
self.enter().map_or(0, |x| x.len())
}
/// Returns true if the map contains no elements.
pub fn is_empty(&self) -> bool {
self.enter().map_or(true, |x| x.is_empty())
}
/// Get the current meta value.
pub fn meta(&self) -> Option<ReadGuard<'_, M>> {
Some(ReadGuard::map(self.handle.enter()?, |inner| &inner.meta))
}
/// Internal version of `get_and`
fn get_raw<Q: ?Sized>(&self, key: &Q) -> Option<ReadGuard<'_, Values<V, S>>>
where
K: Borrow<Q>,
Q: Hash + Eq,
{
let inner = self.handle.enter()?;
if !inner.ready {
return None;
}
ReadGuard::try_map(inner, |inner| inner.data.get(key).map(AsRef::as_ref))
}
/// Returns a guarded reference to the values corresponding to the key.
///
/// While the guard lives, changes to the map cannot be published.
///
/// The key may be any borrowed form of the map's key type, but `Hash` and `Eq` on the borrowed
/// form must match those for the key type.
///
/// Note that not all writes will be included with this read -- only those that have been
/// published by the writer. If no publish has happened, or the map has been destroyed, this
/// function returns `None`.
#[inline]
pub fn get<'rh, Q: ?Sized>(&'rh self, key: &'_ Q) -> Option<ReadGuard<'rh, Values<V, S>>>
where
K: Borrow<Q>,
Q: Hash + Eq,
{
// call `borrow` here to monomorphize `get_raw` fewer times
self.get_raw(key.borrow())
}
/// Returns a guarded reference to _one_ value corresponding to the key.
///
/// This is mostly intended for use when you are working with no more than one value per key.
/// If there are multiple values stored for this key, there are no guarantees to which element
/// is returned.
///
/// While the guard lives, changes to the map cannot be published.
///
/// The key may be any borrowed form of the map's key type, but `Hash` and `Eq` on the borrowed
/// form must match those for the key type.
///
/// Note that not all writes will be included with this read -- only those that have been
/// refreshed by the writer. If no refresh has happened, or the map has been destroyed, this
/// function returns `None`.
#[inline]
pub fn get_one<'rh, Q: ?Sized>(&'rh self, key: &'_ Q) -> Option<ReadGuard<'rh, V>>
where
K: Borrow<Q>,
Q: Hash + Eq,
{
ReadGuard::try_map(self.get_raw(key.borrow())?, |x| x.get_one())
}
/// Returns a guarded reference to the values corresponding to the key along with the map
/// meta.
///
/// While the guard lives, changes to the map cannot be published.
///
/// The key may be any borrowed form of the map's key type, but `Hash` and `Eq` on the borrowed
/// form *must* match those for the key type.
///
/// Note that not all writes will be included with this read -- only those that have been
/// refreshed by the writer. If no refresh has happened, or the map has been destroyed, this
/// function returns `None`.
///
/// If no values exist for the given key, `Some(None, _)` is returned.
pub fn meta_get<Q: ?Sized>(&self, key: &Q) -> Option<(Option<ReadGuard<'_, Values<V, S>>>, M)>
where
K: Borrow<Q>,
Q: Hash + Eq,
{
let inner = self.handle.enter()?;
if !inner.ready {
return None;
}
let meta = inner.meta.clone();
let res = ReadGuard::try_map(inner, |inner| inner.data.get(key).map(AsRef::as_ref));
Some((res, meta))
}
/// Returns true if the [`WriteHandle`](crate::WriteHandle) has been dropped.
pub fn was_dropped(&self) -> bool {
self.handle.was_dropped()
}
/// Returns true if the map contains any values for the specified key.
///
/// The key may be any borrowed form of the map's key type, but `Hash` and `Eq` on the borrowed
/// form *must* match those for the key type.
pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool
where
K: Borrow<Q>,
Q: Hash + Eq,
{
self.enter().map_or(false, |x| x.contains_key(key))
}
/// Returns true if the map contains the specified value for the specified key.
///
/// The key and value may be any borrowed form of the map's respective types, but `Hash` and
/// `Eq` on the borrowed form *must* match.
pub fn contains_value<Q: ?Sized, W: ?Sized>(&self, key: &Q, value: &W) -> bool
where
K: Borrow<Q>,
Aliased<V, crate::aliasing::NoDrop>: Borrow<W>,
Q: Hash + Eq,
W: Hash + Eq,
V: Hash + Eq,
{
self.get_raw(key.borrow())
.map(|x| x.contains(value))
.unwrap_or(false)
}
/// Read all values in the map, and transform them into a new collection.
pub fn map_into<Map, Collector, Target>(&self, mut f: Map) -> Collector
where
Map: FnMut(&K, &Values<V, S>) -> Target,
Collector: FromIterator<Target>,
{
self.enter()
.iter()
.flatten()
.map(|(k, v)| f(k, v))
.collect()
}
}
#[cfg(test)]
mod test {
use crate::new;
// the idea of this test is to allocate 64 elements, and only use 17. The vector will
// probably try to fit either exactly the length, to the next highest power of 2 from
// the length, or something else entirely, E.g. 17, 32, etc.,
// but it should always end up being smaller than the original 64 elements reserved.
#[test]
fn reserve_and_fit() {
const MIN: usize = (1 << 4) + 1;
const MAX: usize = 1 << 6;
let (mut w, r) = new();
w.reserve(0, MAX).publish();
assert!(r.get_raw(&0).unwrap().capacity() >= MAX);
for i in 0..MIN {
w.insert(0, i);
}
w.fit_all().publish();
assert!(r.get_raw(&0).unwrap().capacity() < MAX);
}
}
|
use cssparser::RGBA;
use super::{
font::Font,
pattern::Pattern,
sk::{BlendMode, FilterQuality, Paint, TextAlign, TextBaseline},
};
#[derive(Debug, Clone)]
pub struct Context2dRenderingState {
pub line_dash_list: Vec<f32>,
pub stroke_style: Pattern,
pub fill_style: Pattern,
pub shadow_offset_x: f32,
pub shadow_offset_y: f32,
pub shadow_blur: f32,
pub shadow_color: RGBA,
pub shadow_color_string: String,
pub global_alpha: f32,
pub line_dash_offset: f32,
pub global_composite_operation: BlendMode,
pub image_smoothing_enabled: bool,
pub image_smoothing_quality: FilterQuality,
pub paint: Paint,
pub font: String,
pub font_style: Font,
pub text_align: TextAlign,
pub text_baseline: TextBaseline,
}
impl Default for Context2dRenderingState {
fn default() -> Context2dRenderingState {
Context2dRenderingState {
line_dash_list: vec![],
stroke_style: Pattern::Color(RGBA::new(0, 0, 0, 255), "#000".to_owned()),
fill_style: Pattern::Color(RGBA::new(0, 0, 0, 255), "#000".to_owned()),
shadow_offset_x: 0f32,
shadow_offset_y: 0f32,
shadow_blur: 0f32,
shadow_color: RGBA::new(0, 0, 0, 255),
shadow_color_string: "#000000".to_owned(),
/// 0.0 ~ 1.0
global_alpha: 1.0,
/// A float specifying the amount of the line dash offset. The default value is 0.0.
line_dash_offset: 0.0,
global_composite_operation: BlendMode::SourceOver,
image_smoothing_enabled: true,
image_smoothing_quality: FilterQuality::Low,
paint: Paint::default(),
font: "10px sans-serif".to_owned(),
font_style: Font::default(),
text_align: TextAlign::Start,
text_baseline: TextBaseline::Alphabetic,
}
}
}
|
use chiropterm::*;
use euclid::{rect, size2};
use crate::{InternalWidgetDimensions, UI, Widget, WidgetCommon, WidgetMenu, Widgetlike, widget::LayoutHacks};
pub type Button = Widget<ButtonState>;
// TODO: Hotkeys
pub struct ButtonState {
pub hotkey: Option<Keycode>,
pub text: String,
pub command: Option<Box<dyn FnMut(UI, &mut WidgetCommon<ButtonState>, InputEvent) -> Signal>>,
pub layout_hacks: LayoutHacks,
}
impl ButtonState {
pub fn set_command(&mut self, cmd: impl 'static+FnMut(UI, &mut WidgetCommon<ButtonState>, InputEvent) -> Signal) {
self.command = Some(Box::new(cmd))
}
}
impl Widgetlike for ButtonState {
fn create() -> Self {
Self {
hotkey: None,
text: "".to_owned(),
command: None,
layout_hacks: LayoutHacks::new(),
}
}
fn draw<'frame>(&self, _selected: bool, brush: Brush, menu: WidgetMenu<'frame, Self>) {
let click_interactor = menu.on_mouse(move |ui, this, click: MouseEvent| {
match click {
MouseEvent::Click(_, _, _) => {
return ButtonState::click(ui, this, InputEvent::Mouse(click));
},
MouseEvent::Up(_, _, _) => {}
MouseEvent::Drag {..} => {}
MouseEvent::Scroll(_, _, _) => {}
MouseEvent::Wiggle {..} => {}
};
Signal::Refresh
});
if let Some(hotkey) = self.hotkey {
menu.on_key(OnKey::only(hotkey).pressed(), move |ui, this, key| {
ButtonState::click(ui, this, InputEvent::Keyboard(key))
});
}
let theme = menu.ui.theme().button;
brush.bevel_w95(theme.bevel);
brush.interactor(click_interactor, theme.preclick).putfs(&self.text);
}
fn estimate_dimensions(&self, _ui: &UI, width: isize) -> InternalWidgetDimensions {
// TODO: Find a more efficient way to do this
let stamp = Stamp::new();
let brush = stamp.brush_at(rect(0, 0, width, isize::MAX));
brush.putfs(&self.text);
InternalWidgetDimensions {
min: size2(8.min(self.text.len() as isize), 2),
preferred: stamp.rect().size,
// TODO: Better foundation for this number
max: Some(size2(self.text.len() as isize, 2)),
align_size_to: size2(1, 2),
horizontal_spacer_count: 0,
vertical_spacer_count: 0,
}
}
fn clear_layout_cache(&self, _: &UI) { }
fn layout_hacks(&self) -> LayoutHacks { self.layout_hacks }
}
impl ButtonState {
fn click(ui: UI, this: &mut WidgetCommon<Self>, input: InputEvent) -> Signal {
ui.select(this); // this button can be selected, not that it matters. just deselect other stuff
let command = this.unique.command.take();
if let Some(mut c) = command {
let result = c(ui, this, input);
this.unique.command.replace(c);
return result
}
Signal::Refresh
}
} |
// https://adventofcode.com/2017/day/3
const INPUT: i32 = 312051;
fn main() {
// First star
// Go through spiral with full "strides", length increases by one in two corners
// * < * * *
// * * < * ^
// * v > ^ *
// v * * > *
// * * * * >
let mut stride_len = 1;
let mut remaining = INPUT;
let mut x: i32 = 0;
let mut y: i32 = 0;
let mut dir = Direction::Right;
while remaining - stride_len > 0 {
remaining -= stride_len;
match dir {
Direction::Up => {
y += stride_len;
dir = Direction::Left;
stride_len += 1;
}
Direction::Left => {
x -= stride_len;
dir = Direction::Down;
}
Direction::Down => {
y -= stride_len;
dir = Direction::Right;
stride_len += 1;
}
Direction::Right => {
x += stride_len;
dir = Direction::Up;
}
}
}
// Take remaining steps
match dir {
Direction::Up => y += remaining - 1,
Direction::Left => x -= remaining - 1,
Direction::Down => y -= remaining - 1,
Direction::Right => x += remaining - 1,
}
let path_len = x.abs() + y.abs();
// Assert to facilitate further tweaks
assert_eq!(430, path_len);
println!(
"Square located at x:{} y:{}, shortest path to start is {}",
x,
y,
path_len
);
// Second star
let mut stride_len = 1;
let mut steps = 0;
let mut current = 1;
let mut x: i32 = 1;
let mut y: i32 = 0;
let mut dir = Direction::Up;
let mut sums: Vec<i32> = Vec::new();
sums.push(1);
// Take single steps from first square until one past given index
while *sums.last().expect("Empty vector") <= INPUT {
// Get neighbors
let neighbors = match dir {
Direction::Up => [
get_tile_index(x, y - 1),
get_tile_index(x - 1, y - 1),
get_tile_index(x - 1, y),
get_tile_index(x - 1, y + 1),
],
Direction::Left => [
get_tile_index(x + 1, y),
get_tile_index(x - 1, y - 1),
get_tile_index(x, y - 1),
get_tile_index(x + 1, y - 1),
],
Direction::Down => [
get_tile_index(x, y + 1),
get_tile_index(x + 1, y + 1),
get_tile_index(x + 1, y),
get_tile_index(x + 1, y - 1),
],
Direction::Right => [
get_tile_index(x - 1, y),
get_tile_index(x - 1, y + 1),
get_tile_index(x, y + 1),
get_tile_index(x + 1, y + 1),
],
};
// Sum valid neighbors
let mut sum: i32 = 0;
for i in 0..4 {
if neighbors[i] < current {
sum += sums[neighbors[i] as usize];
}
}
// Set value of current node
sums.push(sum);
// Step
steps += 1;
current += 1;
match dir {
Direction::Up => y += 1,
Direction::Left => x -= 1,
Direction::Down => y -= 1,
Direction::Right => x += 1,
}
// Handle corners
if steps >= stride_len {
match dir {
Direction::Up => {
dir = Direction::Left;
stride_len += 1;
}
Direction::Left => dir = Direction::Down,
Direction::Down => {
dir = Direction::Right;
stride_len += 1;
}
Direction::Right => dir = Direction::Up,
}
steps = 0;
}
}
let next = *sums.last().expect("Sums empty");
// Assert to facilitate further tweaks
assert_eq!(312453, next);
println!("Next written value would be {}", next);
}
// Returns linear tile index based on coordinates
fn get_tile_index(x: i32, y: i32) -> i32 {
if y * y >= x * x {
if y < x {
4 * y * y - y - x - 2 * (y - x)
} else {
4 * y * y - y - x
}
} else {
if y < x {
4 * x * x - y - x + 2 * (y - x)
} else {
4 * x * x - y - x
}
}
}
enum Direction {
Up,
Left,
Down,
Right,
}
|
extern crate ssh;
pub fn main() {
println!("Hello from ssh!");
}
|
struct Triangle {
base: u32,
height: u32,
}
impl Triangle {
fn area(&self) -> u32 {
let a = &self.base * &self.height / 2;
a
}
fn info() {
println!("A triangle has 3 sides. All its angles must make 360 degrees.");
}
}
pub fn runner() {
let triangle = Triangle {
base: 10,
height: 20
};
Triangle::info();
println!("{:?}", triangle.area());
} |
pub enum SortOrder {
Acending,
Decending,
}
pub mod first;
pub mod second;
pub mod third;
|
use std::collections::HashMap;
use std::env::args;
use std::result::Result;
fn part1(content: &String) -> usize {
customs_forms_anyone(content)
}
fn part2(content: &String) -> usize {
customs_forms_everyone(content)
}
fn customs_forms_anyone(content: &String) -> usize {
let mut questions: HashMap<char, usize> = HashMap::new();
let mut count: usize = 0;
content.lines().for_each(|s: &str| {
if s == "" {
count += questions.values().sum::<usize>();
questions = HashMap::new();
} else {
s.chars().filter(|x| x.is_ascii_alphabetic()).for_each(|t| {
questions.insert(t, 1);
()
});
}
});
count
}
fn customs_forms_everyone(content: &String) -> usize {
let mut questions: HashMap<char, usize> = HashMap::new();
let mut count: usize = 0;
let mut people: usize = 0;
content.lines().for_each(|s: &str| {
if s == "" {
count += questions
.values()
.map(|v| if *v == people { 1 } else { 0 })
.sum::<usize>();
questions = HashMap::new();
people = 0;
} else {
s.chars().filter(|x| x.is_ascii_alphabetic()).for_each(|t| {
match questions.get(&t) {
Some(v) => questions.insert(t, v + 1),
None => questions.insert(t, 1),
};
()
});
people += 1;
}
});
count
}
#[cfg(test)]
mod test {
use super::*;
const TEST_INPUT: &str = r#"abc
a
b
c
ab
ac
a
a
a
a
b
"#;
#[test]
fn testcase1() {
let content = String::from(TEST_INPUT);
let part1_answer = part1(&content);
assert_eq!(part1_answer, 11);
}
#[test]
fn testcase2() {
let content = String::from(TEST_INPUT);
let part2_answer = part2(&content);
assert_eq!(part2_answer, 6);
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let filename = args().nth(1).ok_or("I need a filename")?;
let content = std::fs::read_to_string(&filename)?;
let part1_answer = part1(&content);
println!("Part1 Answer: {}", part1_answer);
let part2_answer = part2(&content);
println!("Part2 Answer: {}", part2_answer);
Ok(())
}
|
//! **mumble-link** provides an API for using the [Mumble Link][link] plugin
//! for position-aware VoIP communications.
//!
//! [link]: https://wiki.mumble.info/wiki/Link
//!
//! Connect to Mumble link with `MumbleLink::new()`, set the context or player
//! identity as needed, and call `update()` every frame with the position data.
use std::{io, ptr, mem};
use libc::{c_float, wchar_t};
#[cfg(any(test, windows))]
macro_rules! wide {
($($ch:ident)*) => {
[$(stringify!($ch).as_bytes()[0] as ::libc::wchar_t,)* 0]
}
}
#[cfg_attr(windows, path="windows.rs")]
#[cfg_attr(not(windows), path="unix.rs")]
mod imp;
/// A position in three-dimensional space.
///
/// The vectors are in a left-handed coordinate system: X positive towards
/// "right", Y positive towards "up", and Z positive towards "front". One unit
/// is treated as one meter by the sound engine.
///
/// `front` and `top` should be unit vectors and perpendicular to each other.
#[derive(Copy, Clone)]
#[repr(C)]
pub struct Position {
/// The character's position in space.
pub position: [f32; 3],
/// A unit vector pointing out of the character's eyes.
pub front: [f32; 3],
/// A unit vector pointing out of the top of the character's head.
pub top: [f32; 3],
}
// `f32` is used above for tidyness; assert that it matches c_float.
const _ASSERT_CFLOAT_IS_F32: c_float = 0f32;
impl Default for Position {
fn default() -> Self {
Position {
position: [0., 0., 0.],
front: [0., 0., 1.],
top: [0., 1., 0.],
}
}
}
#[derive(Copy)]
#[repr(C)]
struct LinkedMem {
ui_version: u32,
ui_tick: u32,
avatar: Position,
name: [wchar_t; 256],
camera: Position,
identity: [wchar_t; 256],
context_len: u32,
context: [u8; 256],
description: [wchar_t; 2048],
}
impl Clone for LinkedMem {
fn clone(&self) -> Self { *self }
}
impl LinkedMem {
fn new(name: &str, description: &str) -> LinkedMem {
let mut result = LinkedMem {
ui_version: 2,
ui_tick: 0,
avatar: Position::default(),
name: [0; 256],
camera: Position::default(),
identity: [0; 256],
context_len: 0,
context: [0; 256],
description: [0; 2048],
};
imp::copy(&mut result.name, name);
imp::copy(&mut result.description, description);
result
}
fn set_context(&mut self, context: &[u8]) {
let len = std::cmp::min(context.len(), self.context.len());
self.context[..len].copy_from_slice(&context[..len]);
self.context_len = len as u32;
}
#[inline]
fn set_identity(&mut self, identity: &str) {
imp::copy(&mut self.identity, identity);
}
fn update(&mut self, avatar: Position, camera: Position) {
self.ui_tick = self.ui_tick.wrapping_add(1);
self.avatar = avatar;
self.camera = camera;
}
}
macro_rules! docs {
($(#[$attr:meta])* pub fn set_context(&mut $s:ident, $c:ident: &[u8]) $b:block) => {
/// Update the context string, used to determine which users on a Mumble
/// server should hear each other positionally.
///
/// If context between two Mumble users does not match, the positional audio
/// data is stripped server-side and voice will be received as
/// non-positional. Accordingly, the context should only match for players
/// on the same game, server, and map, depending on the game itself. When
/// in doubt, err on the side of including less; this allows for more
/// flexibility in the future.
///
/// The context should be changed infrequently, at most a few times per
/// second.
///
/// The context has a maximum length of 256 bytes.
$(#[$attr])*
pub fn set_context(&mut $s, $c: &[u8]) $b
};
($(#[$attr:meta])* pub fn set_identity(&mut $s:ident, $i:ident: &str) $b:block) => {
/// Update the identity, uniquely identifying the player in the given
/// context. This is usually the in-game name or ID.
///
/// The identity may also contain any additional information about the
/// player which might be useful for the Mumble server, for example to move
/// teammates to the same channel or give squad leaders additional powers.
/// It is recommended that a parseable format like JSON or CSV is used for
/// this.
///
/// The identity should be changed infrequently, at most a few times per
/// second.
///
/// The identity has a maximum length of 255 UTF-16 code units.
$(#[$attr])*
pub fn set_identity(&mut $s, $i: &str) $b
};
($(#[$attr:meta])* pub fn update(&mut $s:ident, $a:ident: Position, $c:ident: Position) $b:block) => {
/// Update the link with the latest position information. Should be called
/// once per frame.
///
/// `avatar` should be the position of the player. If it is all zero,
/// positional audio will be disabled. `camera` should be the position of
/// the camera, which may be the same as `avatar`.
$(#[$attr])*
pub fn update(&mut $s, $a: Position, $c: Position) $b
};
}
/// An active Mumble link connection.
pub struct MumbleLink {
map: imp::Map,
local: LinkedMem,
}
impl MumbleLink {
/// Attempt to open the Mumble link, providing the specified application
/// name and description.
///
/// Opening the link will fail if Mumble is not running. If another
/// application is also using Mumble link, its data may be overwritten or
/// conflict with this link. To avoid this, use `SharedLink`.
pub fn new(name: &str, description: &str) -> io::Result<MumbleLink> {
Ok(MumbleLink {
map: (imp::Map::new(std::mem::size_of::<LinkedMem>()))?,
local: LinkedMem::new(name, description),
})
}
docs! {
#[inline]
pub fn set_context(&mut self, context: &[u8]) {
self.local.set_context(context)
}
}
docs! {
#[inline]
pub fn set_identity(&mut self, identity: &str) {
self.local.set_identity(identity)
}
}
docs! {
#[inline]
pub fn update(&mut self, avatar: Position, camera: Position) {
self.local.update(avatar, camera);
unsafe {
ptr::write_volatile(self.map.ptr as *mut LinkedMem, self.local);
}
}
}
}
unsafe impl Send for MumbleLink {}
impl Drop for MumbleLink {
fn drop(&mut self) {
unsafe {
// zero the linked memory
ptr::write_volatile(self.map.ptr as *mut LinkedMem, mem::zeroed());
}
}
}
/// A weak Mumble link connection.
///
/// Constructing a `SharedLink` always succeeds, even if Mumble is not running
/// or another application is writing to the link. If this happens, `update()`
/// will retry opening the link on a regular basis, succeeding if Mumble is
/// started or the other application stops using the link.
pub struct SharedLink {
inner: Inner,
local: LinkedMem,
}
impl SharedLink {
/// Open the Mumble link, providing the specified application name and
/// description.
pub fn new(name: &str, description: &str) -> SharedLink {
SharedLink {
inner: Inner::open(),
local: LinkedMem::new(name, description),
}
}
docs! {
#[inline]
pub fn set_context(&mut self, context: &[u8]) {
self.local.set_context(context)
}
}
docs! {
#[inline]
pub fn set_identity(&mut self, identity: &str) {
self.local.set_identity(identity)
}
}
docs! {
pub fn update(&mut self, avatar: Position, camera: Position) {
self.local.update(avatar, camera);
// If it's been a hundred ticks, try to reopen the link
if self.local.ui_tick % 100 == 0 {
self.inner = match mem::replace(&mut self.inner, Inner::Unset) {
Inner::Closed(_) => Inner::open(),
Inner::InUse(map, last_tick) => {
let previous = unsafe { ptr::read_volatile(map.ptr as *mut LinkedMem) };
if previous.ui_version == 0 || last_tick == previous.ui_tick {
Inner::Active(map)
} else {
Inner::InUse(map, previous.ui_tick)
}
}
Inner::Active(map) => Inner::Active(map),
Inner::Unset => unreachable!(),
};
}
// If the link is active, write to it
if let Inner::Active(ref mut map) = self.inner {
unsafe {
ptr::write_volatile(map.ptr as *mut LinkedMem, self.local);
}
}
}
}
/// Get the status of the shared link. See `Status` for details.
pub fn status(&self) -> Status {
match self.inner {
Inner::Closed(ref err) => Status::Closed(err),
Inner::InUse(ref map, _) => {
let previous = unsafe { ptr::read_volatile(map.ptr as *mut LinkedMem) };
Status::InUse {
name: imp::read(&previous.name),
description: imp::read(&previous.description)
}
},
Inner::Active(_) => Status::Active,
Inner::Unset => unreachable!(),
}
}
/// Deactivate the shared link.
///
/// Should be called when `update()` will not be called again for a while,
/// such as if the player is no longer in-game.
pub fn deactivate(&mut self) {
if let Inner::Active(ref mut map) = self.inner {
unsafe {
ptr::write_volatile(map.ptr as *mut LinkedMem, mem::zeroed());
}
}
self.inner = Inner::Closed(io::Error::new(io::ErrorKind::Other, "Manually closed"));
}
}
unsafe impl Send for SharedLink {}
impl Drop for SharedLink {
fn drop(&mut self) {
self.deactivate();
}
}
enum Inner {
Unset,
Closed(io::Error),
InUse(imp::Map, u32),
Active(imp::Map),
}
impl Inner {
fn open() -> Inner {
match imp::Map::new(std::mem::size_of::<LinkedMem>()) {
Err(err) => Inner::Closed(err),
Ok(map) => {
let previous = unsafe { ptr::read_volatile(map.ptr as *mut LinkedMem) };
if previous.ui_version != 0 {
Inner::InUse(map, previous.ui_tick)
} else {
Inner::Active(map)
}
}
}
}
}
/// The status of a `SharedLink`.
#[derive(Debug)]
pub enum Status<'a> {
/// The link is closed. This is usually because Mumble is not running or
/// the link was closed manually with `deactivate()`.
Closed(&'a io::Error),
/// The link is in use by another application.
InUse {
/// The name of the other application.
name: String,
/// The description of the other application.
description: String,
},
/// The link is active.
Active,
}
#[test]
fn test_wide() {
let wide = wide!(M u m b l e L i n k);
for (i, b) in "MumbleLink".bytes().enumerate() {
assert_eq!(b as wchar_t, wide[i]);
}
assert_eq!(0, wide[wide.len() - 1]);
let mut wide = [1; 32];
imp::copy(&mut wide, "FooBar");
assert_eq!(&wide[..7], wide!(F o o B a r));
assert_eq!("FooBar", imp::read(&wide));
let mut wide = [1; 3];
imp::copy(&mut wide, "ABC");
assert_eq!(&wide[..], wide!(A B));
assert_eq!("AB", imp::read(&wide));
assert_eq!("BarFoo", imp::read(&wide!(B a r F o o)));
}
|
fn main() {
println!("Hello, world!");
// println! calls a Rust macro.
// println would call a Rust function.
// The best explanation of macros in Rust I could find can be found here:
// https://medium.com/@phoomparin/a-beginners-guide-to-rust-macros-5c75594498f1
}
|
use ash::extensions::khr;
use ash::prelude::VkResult;
use ash::version::{DeviceV1_0, InstanceV1_0};
use ash::{self, vk};
use super::debug;
use super::util;
fn device_extension_names() -> [&'static [i8]; 1] {
[unsafe { &*(khr::Swapchain::name().to_bytes_with_nul() as *const [u8] as *const [i8]) }]
}
pub struct DeviceWrapper {
pub logical: ash::Device,
pub physical: vk::PhysicalDevice,
pub queues: Queues,
}
pub struct Queues {
pub graphics: vk::Queue,
pub graphics_family_index: u32,
pub presentation: vk::Queue,
pub present_family_index: u32,
}
// private helper struct to avoid having
// to pass around tuples everywhere
struct QueueFamilyIndices {
graphics: u32,
presentation: u32,
}
impl DeviceWrapper {
#[allow(unused_unsafe)]
pub unsafe fn new(
instance: &ash::Instance,
surface_entry: &khr::Surface,
surface: vk::SurfaceKHR,
) -> VkResult<Self> {
let (phys_device, queue_fam_indices) =
unsafe { pick_physical(instance, surface_entry, surface)? };
let logical_device = //`
unsafe { create_logical(instance, phys_device, &queue_fam_indices)? };
let graphics_queue =
// NOTE: we pass 0 for queue index
unsafe { logical_device.get_device_queue(queue_fam_indices.graphics, 0) };
let present_queue =
unsafe { logical_device.get_device_queue(queue_fam_indices.presentation, 0) };
Ok(Self {
logical: logical_device,
physical: phys_device,
queues: Queues {
graphics: graphics_queue,
graphics_family_index: queue_fam_indices.graphics,
presentation: present_queue,
present_family_index: queue_fam_indices.presentation,
},
})
}
pub unsafe fn destroy(&self) {
self.logical.destroy_device(None);
}
}
#[allow(unused_unsafe)]
unsafe fn pick_physical(
instance: &ash::Instance,
surface_entry: &khr::Surface,
surface: vk::SurfaceKHR,
) -> VkResult<(vk::PhysicalDevice, QueueFamilyIndices)> {
// entry to rest of function. calls the other subfunctions
{
return _pick_physical(instance, surface_entry, surface);
}
fn _pick_physical(
instance: &ash::Instance,
surface_entry: &khr::Surface,
surface: vk::SurfaceKHR,
) -> VkResult<(vk::PhysicalDevice, QueueFamilyIndices)> {
let phys_devices = unsafe { instance.enumerate_physical_devices()? };
let mut preferred: Option<vk::PhysicalDevice> = None;
let mut mem_largest = 0;
let mut queue_fam_indices = QueueFamilyIndices {
graphics: 0,
presentation: 0,
};
for d in phys_devices {
let props: vk::PhysicalDeviceProperties =
unsafe { instance.get_physical_device_properties(d) };
let mem_props: vk::PhysicalDeviceMemoryProperties =
unsafe { instance.get_physical_device_memory_properties(d) };
let queue_fam_props: Vec<vk::QueueFamilyProperties> =
unsafe { instance.get_physical_device_queue_family_properties(d) };
let exts = unsafe { instance.enumerate_device_extension_properties(d)? };
queue_fam_indices =
match _find_queue_fam_indices(d, &queue_fam_props, &surface_entry, surface)? {
Some(q) => q,
// require appropriate queue families
None => continue,
};
if _has_required_exts(exts) == false {
// require appropriate extensions (only swapchain, as of now)
continue;
} else {
// swapchain/surface support is present
let _capabilities: vk::SurfaceCapabilitiesKHR =
unsafe { surface_entry.get_physical_device_surface_capabilities(d, surface)? };
let formats: Vec<vk::SurfaceFormatKHR> =
unsafe { surface_entry.get_physical_device_surface_formats(d, surface)? };
let present_modes: Vec<vk::PresentModeKHR> =
unsafe { surface_entry.get_physical_device_surface_present_modes(d, surface)? };
// require more than 0 formats and present modes
if formats.is_empty() || present_modes.is_empty() {
continue;
}
}
// prefer discrete gpus
if props.device_type == vk::PhysicalDeviceType::DISCRETE_GPU {
preferred = Some(d);
break;
}
// or pick the device with the most memory
let mut mem_size = 0;
for i in 0..mem_props.memory_heap_count {
let heap = mem_props.memory_heaps[i as usize];
if heap.flags.contains(vk::MemoryHeapFlags::DEVICE_LOCAL) {
mem_size += heap.size;
}
}
if mem_size > mem_largest {
mem_largest = mem_size;
preferred = Some(d);
}
}
match preferred {
None => panic!(/* FIXME: handle err */),
Some(pref) => return Ok((pref, queue_fam_indices)),
}
}
// search for queue families supporting graphics and presentation
// and return their indices (or None, if none are found)
fn _find_queue_fam_indices(
device: vk::PhysicalDevice,
queue_fam_props: &Vec<vk::QueueFamilyProperties>,
surface_entry: &khr::Surface,
surface: vk::SurfaceKHR,
) -> VkResult<Option<QueueFamilyIndices>> {
let mut graphics_ndx: Option<u32> = None;
let mut present_ndx: Option<u32> = None;
for (i, q) in queue_fam_props.iter().enumerate() {
if q.queue_flags.contains(vk::QueueFlags::GRAPHICS) {
graphics_ndx = Some(i as u32);
}
let supports_presentation = unsafe {
surface_entry.get_physical_device_surface_support(device, i as u32, surface)?
};
if supports_presentation {
present_ndx = Some(i as u32);
}
if let (Some(g), Some(p)) = (graphics_ndx, present_ndx) {
return Ok(Some(QueueFamilyIndices {
graphics: g,
presentation: p,
}));
}
}
Ok(None)
}
// determine if device has the required
// extensions (as given by device_extension_names())
fn _has_required_exts(exts: Vec<vk::ExtensionProperties>) -> bool {
for n in device_extension_names().iter() {
let mut found = false;
for ext in &exts {
if util::strcmp(n, &ext.extension_name) {
found = true;
break;
}
}
if found == false {
return false;
}
}
true
}
}
// FIXME: unsafe?
#[allow(unused_unsafe)]
unsafe fn create_logical(
instance: &ash::Instance,
phys_device: vk::PhysicalDevice,
queue_fam_indices: &QueueFamilyIndices,
) -> VkResult<ash::Device> {
let graphics_queue_info = vk::DeviceQueueCreateInfo::builder()
.queue_family_index(queue_fam_indices.graphics)
.queue_priorities(&[1.0]);
let present_queue_info = vk::DeviceQueueCreateInfo::builder()
.queue_family_index(queue_fam_indices.presentation)
.queue_priorities(&[1.0]);
let queue_infos = [graphics_queue_info.build(), present_queue_info.build()];
let ext_names = util::to_raw_ptrs(&device_extension_names());
let mut create_info = if queue_fam_indices.graphics == queue_fam_indices.presentation {
vk::DeviceCreateInfo::builder()
// only pass one of the queue_create_infos
// if their queue family indices are the same
.queue_create_infos(&queue_infos[0..1])
.enabled_extension_names(&ext_names)
} else {
vk::DeviceCreateInfo::builder()
.queue_create_infos(&queue_infos)
.enabled_extension_names(&ext_names)
// TODO: device features? if we require any specific ones
};
// validation layers
let enabled_layer_names = util::to_raw_ptrs(&debug::validation_layer_names());
if cfg!(debug_assertions) {
create_info = create_info.enabled_layer_names(&enabled_layer_names)
}
Ok(unsafe { instance.create_device(phys_device, &create_info, None)? })
}
#[test]
fn device_extension_names_test() {
assert_eq!(
device_extension_names()[0].len(),
khr::Swapchain::name().to_bytes_with_nul().len()
);
}
|
// Copyright 2018-2020, Wayfair GmbH
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::language;
use tower_lsp::lsp_types::{DiagnosticSeverity, Position};
use crate::backend::file_dbg;
pub fn to_lsp_position(location: &language::Location) -> Position {
// position in language server protocol is zero-based
Position::new((location.line() - 1) as u64, (location.column() - 1) as u64)
}
#[allow(clippy::cast_possible_truncation)]
pub fn to_language_location(position: &Position) -> language::Location {
// location numbers in our languages starts from one
language::Location::new(
(position.line + 1) as usize, // we should never have line positions > 32 bit
(position.character + 1) as usize, // we should never have character positions > 32 bit
0,
0, // absolute byte offset -- we don't use it here so setting to 0
)
}
pub fn to_lsp_severity(error_level: &language::ErrorLevel) -> DiagnosticSeverity {
match error_level {
language::ErrorLevel::Error => DiagnosticSeverity::Error,
language::ErrorLevel::Warning => DiagnosticSeverity::Warning,
language::ErrorLevel::Hint => DiagnosticSeverity::Hint,
}
}
pub fn get_token(tokens: &[language::TokenSpan], position: Position) -> Option<String> {
let location = to_language_location(&position);
//file_dbg("get_token_location_line", &location.line.to_string());
//file_dbg("get_token_location_column", &location.column.to_string());
let mut token = None;
for (i, t) in tokens.iter().enumerate() {
if t.span.end.line() == location.line() && t.span.end.column() > location.column() {
//file_dbg("get_token_span_end", &token.span.end.line.to_string());
//file_dbg("get_token_location_end", &location.line.to_string());
file_dbg("get_token_t_value", &t.value.to_string());
token = match t.value {
language::Token::Ident(_, _) => {
if language::Token::ColonColon == tokens[i - 1].value {
Some(format!(
"{}{}{}",
tokens[i - 2].value,
tokens[i - 1].value,
tokens[i].value
))
} else if language::Token::ColonColon == tokens[i + 1].value {
Some(format!(
"{}{}{}",
tokens[i].value,
tokens[i + 1].value,
tokens[i + 2].value,
))
} else {
None
}
}
language::Token::ColonColon => Some(format!(
"{}{}{}",
tokens[i - 1].value,
//t.value,
tokens[i].value,
tokens[i + 1].value
)),
_ => None,
};
break;
}
}
//file_dbg("get_token_return", &token.clone().unwrap_or_default());
token
}
|
use std::collections::HashMap;
use std::fs;
use std::io::{Write, BufReader, Read};
use std::path::PathBuf;
use std::process::Command;
use std::sync::{Arc, RwLock};
use failure::Fail;
use serde::{Deserialize, Serialize};
use warp::reject;
use warp::http::StatusCode;
use slog::{info, warn, Logger};
use itertools::Itertools;
use super::TEZOS_CLIENT_DIR;
use crate::handlers::ErrorMessage;
#[derive(Debug, Fail)]
pub enum TezosClientRunnerError {
/// IO Error.
#[fail(display = "IO error during process creation")]
IOError { reason: std::io::Error },
/// Protocol parameters json error
#[fail(display = "Error while deserializing parameters json")]
ProtocolParameterError,
/// Wallet does not exists error
#[fail(display = "Alias does not exists among the known wallets")]
NonexistantWallet,
/// Wallet already exists error
#[fail(display = "Alias already exists among the known wallets")]
WalletAlreadyExistsError,
/// Serde Error.
#[fail(display = "Error in serde")]
SerdeError { reason: serde_json::Error },
/// Call Error.
#[fail(display = "Tezos-client call error")]
CallError { message: ErrorMessage },
}
impl From<std::io::Error> for TezosClientRunnerError {
fn from(err: std::io::Error) -> TezosClientRunnerError {
TezosClientRunnerError::IOError { reason: err }
}
}
impl From<serde_json::Error> for TezosClientRunnerError {
fn from(err: serde_json::Error) -> TezosClientRunnerError {
TezosClientRunnerError::SerdeError { reason: err }
}
}
impl From<TezosClientRunnerError> for reject::Rejection {
fn from(err: TezosClientRunnerError) -> reject::Rejection {
reject::custom(err)
}
}
impl reject::Reject for TezosClientRunnerError {}
/// Type alias for a vecotr of Wallets
pub type SandboxWallets = Vec<Wallet>;
/// Structure holding data used by tezos client
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Wallet {
alias: String,
public_key_hash: String,
public_key: String,
secret_key: String,
initial_balance: String,
}
/// The json body incoming with the bake request containing the alias for the wallet to bake with
#[derive(Clone, Debug, Deserialize)]
pub struct BakeRequest {
alias: String,
}
#[derive(Serialize)]
pub struct TezosClientErrorReply {
pub message: String,
pub field_name: String,
}
/// Thread-safe reference to the client runner
pub type TezosClientRunnerRef = Arc<RwLock<TezosClientRunner>>;
/// Structure holding data to use a tezos-client binary
#[derive(Clone)]
pub struct TezosClientRunner {
pub name: String,
pub executable_path: PathBuf,
pub base_dir_path: PathBuf,
pub wallets: HashMap<String, Wallet>,
}
/// A structure holding all the required parameters to activate an economic protocol
#[derive(Clone, Debug, Deserialize)]
pub struct TezosProtcolActivationParameters {
timestamp: String,
protocol_hash: String,
protocol_parameters: serde_json::Value,
}
#[derive(Serialize, Clone)]
pub struct TezosClientReply {
pub output: String,
pub error: String,
}
impl TezosClientReply {
pub fn new(output: String, error: String) -> Self {
Self {
output,
error,
}
}
}
impl Default for TezosClientReply {
fn default() -> TezosClientReply {
TezosClientReply::new(String::new(), String::new())
}
}
impl TezosClientRunner {
pub fn new(name: &str, executable_path: PathBuf, base_dir_path: PathBuf) -> Self {
Self {
name: name.to_string(),
executable_path,
base_dir_path,
wallets: HashMap::new(),
}
}
/// Activate a protocol with the provided parameters
pub fn activate_protocol(
&self,
mut activation_parameters: TezosProtcolActivationParameters,
) -> Result<TezosClientReply, reject::Rejection> {
let mut client_output: TezosClientReply = Default::default();
// create a temporary file, the tezos-client requires the parameters to be passed in a .json file
let mut file = fs::File::create("protocol_parameters.json")
.map_err(|err| reject::custom(TezosClientRunnerError::IOError { reason: err }))?;
// get as mutable object, so we can insert the hardcoded bootstrap accounts
let params = if let Some(params) = activation_parameters.protocol_parameters.as_object_mut()
{
params
} else {
return Err(TezosClientRunnerError::ProtocolParameterError.into());
};
let wallet_activation: Vec<[String; 2]> = self
.wallets
.clone()
.into_iter()
.map(|(_, w)| [w.public_key, w.initial_balance])
.collect();
// serialize the harcoded accounts as json array and include it in protocol_parameters
let sandbox_accounts = serde_json::json!(wallet_activation);
params.insert("bootstrap_accounts".to_string(), sandbox_accounts);
// write to a file for the tezos-client
writeln!(file, "{}", activation_parameters.protocol_parameters)
.map_err(|err| reject::custom(TezosClientRunnerError::IOError { reason: err }))?;
self.run_client(
[
"--base-dir",
TEZOS_CLIENT_DIR,
"-A",
"localhost",
"-P",
"18732",
"--block",
"genesis",
"activate",
"protocol",
&activation_parameters.protocol_hash,
"with",
"fitness",
"1",
"and",
"key",
"activator",
"and",
"parameters",
"./protocol_parameters.json",
"--timestamp",
&activation_parameters.timestamp,
]
.to_vec(),
&mut client_output,
)?;
// remove the file after activation
fs::remove_file("./protocol_parameters.json")
.map_err(|err| reject::custom(TezosClientRunnerError::IOError { reason: err }))?;
Ok(client_output)
}
/// Bake a block with the bootstrap1 account
pub fn bake_block(&self, request: Option<BakeRequest>) -> Result<TezosClientReply, reject::Rejection> {
let mut client_output: TezosClientReply = Default::default();
let alias = if let Some(request) = request {
if let Some(wallet) = self.wallets.get(&request.alias) {
&wallet.alias
} else {
return Err(TezosClientRunnerError::NonexistantWallet.into());
}
} else {
// if there is no wallet provided in the request (GET) set the alias to be an arbitrary wallet
if let Some(wallet) = self.wallets.values().next() {
&wallet.alias
} else {
return Err(TezosClientRunnerError::NonexistantWallet.into());
}
};
self.run_client(
[
"--base-dir",
TEZOS_CLIENT_DIR,
"-A",
"localhost",
"-P",
"18732",
"bake",
"for",
&alias,
]
.to_vec(),
&mut client_output,
)?;
Ok(client_output)
}
/// Initialize the accounts in the tezos-client
pub fn init_client_data(
&mut self,
requested_wallets: SandboxWallets,
) -> Result<TezosClientReply, reject::Rejection> {
let mut client_output: TezosClientReply = Default::default();
self.run_client(
[
"--base-dir",
TEZOS_CLIENT_DIR,
"-A",
"localhost",
"-P",
"18732",
"import",
"secret",
"key",
"activator",
"unencrypted:edsk31vznjHSSpGExDMHYASz45VZqXN4DPxvsa4hAyY8dHM28cZzp6",
]
.to_vec(),
&mut client_output,
)?;
for wallet in requested_wallets {
self.run_client(
[
"--base-dir",
TEZOS_CLIENT_DIR,
"-A",
"localhost",
"-P",
"18732",
"import",
"secret",
"key",
&wallet.alias,
&format!("unencrypted:{}", &wallet.secret_key),
]
.to_vec(),
&mut client_output,
)?;
self.wallets.insert(wallet.alias.clone(), wallet);
}
Ok(client_output)
}
/// Cleanup the tezos-client directory
pub fn cleanup(&mut self) -> Result<(), reject::Rejection> {
fs::remove_dir_all(TEZOS_CLIENT_DIR)
.map_err(|err| reject::custom(TezosClientRunnerError::IOError { reason: err }))?;
fs::create_dir(TEZOS_CLIENT_DIR)
.map_err(|err| reject::custom(TezosClientRunnerError::IOError { reason: err }))?;
self.wallets.clear();
Ok(())
}
/// Private method to run the tezos-client as a subprocess and wait for its completion
fn run_client(&self, args: Vec<&str>, client_output: &mut TezosClientReply) -> Result<(), reject::Rejection> {
let output = Command::new(&self.executable_path)
.args(args)
.output()
.map_err(|err| reject::custom(TezosClientRunnerError::IOError { reason: err }))?;
let _ = BufReader::new(output.stdout.as_slice()).read_to_string(&mut client_output.output);
let _ = BufReader::new(output.stderr.as_slice()).read_to_string(&mut client_output.error);
Ok(())
}
}
/// Construct a reply using the output from the tezos-client
pub fn reply_with_client_output(reply: TezosClientReply, log: &Logger) -> Result<impl warp::Reply, reject::Rejection> {
if reply.error.is_empty() {
info!(log, "Successfull tezos-client call: {}", reply.output);
Ok(StatusCode::OK)
} else {
if reply.output.is_empty() {
// error
if let Some((field_name, message)) = extract_field_name_and_message_ocaml(&reply) {
Err(TezosClientRunnerError::CallError { message: ErrorMessage::validation(500, message, field_name)}.into())
} else {
// generic
warn!(log, "GENERIC ERROR in tezos-client, log: {}", reply.error);
Err(TezosClientRunnerError::CallError { message: ErrorMessage::generic(500, "Unexpexted error in tezos-client call".to_string())}.into())
}
} else {
// this is just a warning
warn!(log, "Succesfull call with a warning: {} -> WARNING: {}", reply.output, reply.error);
Ok(StatusCode::OK)
}
}
}
/// Parse the returned error string from the tezos client
fn extract_field_name_and_message_ocaml(reply: &TezosClientReply) -> Option<(String, String)>{
let parsed_message = reply.error.replace("\\", "").split("\"").filter(|s| s.contains("Invalid protocol_parameters")).join("").replace(" n{ ", "").replace("{", "");
// extract the field name depending on the parsed error
let field_name = if parsed_message.contains("Missing object field") {
Some(parsed_message.split_whitespace().last().unwrap_or("").to_string())
} else if parsed_message.contains("/") {
Some(parsed_message.split_whitespace().filter(|s| s.contains("/")).join("").replace("/", "").replace(",", ""))
} else {
None
};
if let Some(field_name) = field_name {
// simply remove the field name from the error message
let message = parsed_message.replace(&field_name, "").replace("At /, ", "").trim().to_string();
Some((field_name, message))
} else {
None
}
}
|
use serde::{Serialize, Deserialize};
use chrono::{DateTime, Utc};
#[derive(Clone, Serialize, Deserialize)]
pub struct PeerInfo {
// on connect
pub connected: DateTime<Utc>,
}
|
extern crate termion;
use std::io::{Write, stdin};
use crate::Items;
use termion::{input::TermRead, event::Key, raw::IntoRawMode};
use termion::{style, cursor, clear};
/*
* the main ui run function
* adapted from
* https://github.com/Munksgaard/inquirer-rs/blob/master/src/list.rs
*
* takes in the items struct and adds elements to
* the sel_items vector
*/
pub fn run(items: &mut Items) {
let mut screen = termion::get_tty().unwrap()
.into_raw_mode()
.unwrap();
let stdin = stdin();
let aitems = items.get_items();
let nitms = aitems.len() - 1;
write!(screen, "\n\r{}", cursor::Hide).unwrap();
for _ in 0..nitms {
write!(screen, "\n").unwrap();
}
/* the cursor position variable */
let mut cur: usize = 0;
let mut input = stdin.keys();
/* the main loop */
loop {
/* delete the previous text */
write!(screen, "\r\x1b[K").unwrap();
/* move up back to the start */
write!(screen, "{}", cursor::Up((nitms + 1) as u16)).unwrap();
for (n, item) in aitems.iter().enumerate() {
write!(screen, "\n\r{}", clear::CurrentLine).unwrap();
let cur_item = aitems.get(n)
.unwrap();
write!(screen, "\t\t").unwrap();
if items.sel_items.contains(cur_item) {
write!(screen, "{}", style::Invert).unwrap();
}
if cur == n {
/* highlighted item */
write!(screen, ">").unwrap();
}
write!(screen, "{}{}", item, style::Reset).unwrap();
}
screen.flush()
.unwrap();
/* get input */
let inp = input.next()
.unwrap();
/* see what the user has input-ed */
match inp.unwrap() {
/* down */
Key::Char('j')|Key::Ctrl('n') => {
/* if in bottom item */
if cur == nitms { cur = 0; }
else { cur += 1; }
}
/* up */
Key::Char('k')|Key::Ctrl('p') => {
/* if in top item */
if cur == 0 { cur = nitms; }
else { cur -= 1; }
}
/* exit loop */
Key::Esc|Key::Ctrl('c')|Key::Char('q') => {
break;
}
/* space for selecting */
Key::Char(' ') => {
items.add_rm_sel(aitems.get(cur).unwrap());
}
/* first element */
Key::Char('g')|Key::Alt('<') => {
cur = 0;
}
/* last element */
Key::Char('G')|Key::Alt('>') => {
cur = nitms;
}
/* something else */
_ => {}
}
}
write!(screen, "\n\r{}", cursor::Show).unwrap();
}
|
use super::cli_types::{Address, LiveCell, SignatureOutput};
use super::collector::Collector;
use super::password::Password;
use super::util;
use anyhow::Result;
use ckb_tool::ckb_jsonrpc_types::TransactionWithStatus;
use ckb_tool::ckb_types::{
bytes::Bytes,
core::{BlockView, Capacity, DepType, TransactionView},
packed,
prelude::*,
H256,
};
use ckb_tool::faster_hex::hex_decode;
use ckb_tool::faster_hex::hex_encode;
use ckb_tool::rpc_client::RpcClient;
use std::collections::HashSet;
use std::io::Write;
use std::process::{Command, Stdio};
pub const DEFAULT_CKB_CLI_BIN_NAME: &str = "ckb-cli";
pub const DEFAULT_CKB_RPC_URL: &str = "http://localhost:8114";
pub struct Wallet {
ckb_cli_bin: String,
api_uri: String,
rpc_client: RpcClient,
address: Address,
genesis: BlockView,
collector: Collector,
}
impl Wallet {
pub fn load(uri: String, ckb_cli_bin: String, address: Address) -> Self {
let rpc_client = RpcClient::new(&uri);
let genesis = rpc_client
.get_block_by_number(0u64.into())
.expect("genesis");
let collector = Collector::new(uri.clone(), ckb_cli_bin.clone());
Wallet {
ckb_cli_bin,
api_uri: uri,
rpc_client,
address,
genesis: genesis.into(),
collector,
}
}
pub fn complete_tx_lock_deps(&self, tx: TransactionView) -> TransactionView {
let tx_hash = self.genesis.transactions().get(1).unwrap().hash();
let out_point = packed::OutPoint::new_builder()
.tx_hash(tx_hash)
.index(0u32.pack())
.build();
let cell_dep = packed::CellDep::new_builder()
.out_point(out_point)
.dep_type(DepType::DepGroup.into())
.build();
tx.as_advanced_builder().cell_dep(cell_dep).build()
}
pub fn complete_tx_inputs<'a>(
&self,
tx: TransactionView,
original_inputs_capacity: Capacity,
fee: Capacity,
) -> TransactionView {
// create change cell
let (change_output, change_occupied_capacity) = {
let change_output = packed::CellOutput::new_builder()
.lock(self.lock_script())
.build();
let capacity: Capacity = change_output.occupied_capacity(Capacity::zero()).unwrap();
let change_output = change_output
.as_builder()
.capacity(capacity.as_u64().pack())
.build();
(change_output, capacity)
};
// calculate required capacity
let required_capacity = tx
.outputs_capacity()
.expect("outputs_capacity")
.safe_add(fee)
.expect("capacity")
.safe_add(change_occupied_capacity)
.expect("capacity");
// collect inputs
let live_cells = self.collect_live_cells(required_capacity);
let inputs_capacity = live_cells.iter().map(|c| c.capacity).sum::<u64>();
let mut inputs: Vec<_> = tx.inputs().into_iter().collect();
inputs.extend(live_cells.into_iter().map(|cell| cell.input()));
// calculate change capacity
let change_capacity =
original_inputs_capacity.as_u64() + inputs_capacity - required_capacity.as_u64();
let change_output = change_output
.as_builder()
.capacity(change_capacity.pack())
.build();
let tx = tx
.as_advanced_builder()
.set_inputs(inputs)
.output(change_output)
.output_data(Default::default())
.build();
tx
}
pub fn read_password(&self) -> Result<Password> {
let password =
rpassword::read_password_from_tty(Some("Password: ")).expect("read password");
Ok(Password::new(password))
}
pub fn sign_tx(&self, tx: TransactionView, password: Password) -> Result<TransactionView> {
// complete witnesses
let mut witnesses: Vec<Bytes> = tx.witnesses().unpack();
if witnesses.is_empty() {
// input group witness
witnesses.push(packed::WitnessArgs::default().as_bytes());
}
witnesses.extend(
(witnesses.len()..tx.inputs().len())
.into_iter()
.map(|_| Bytes::new()),
);
let tx = tx.as_advanced_builder().witnesses(witnesses.pack()).build();
let witnesses_len = tx.witnesses().len();
let message: [u8; 32] = util::tx_sign_message(&tx, 0, witnesses_len).into();
let address_hex = self
.address()
.display_with_network(self.address().network());
let message_hex = {
let mut dst = [0u8; 64];
hex_encode(&message, &mut dst).expect("hex");
String::from_utf8(dst.to_vec()).expect("utf8")
};
let mut child = Command::new(&self.ckb_cli_bin)
.stdin(Stdio::piped())
.stderr(Stdio::piped())
.stdout(Stdio::piped())
.arg("--url")
.arg(&self.api_uri)
.arg("util")
.arg("sign-message")
.arg("--recoverable")
.arg("--output-format")
.arg("json")
.arg("--from-account")
.arg(address_hex)
.arg("--message")
.arg(message_hex)
.spawn()?;
unsafe {
let stdin = child.stdin.as_mut().expect("Failed to open stdin");
stdin
.write_all(password.take().as_bytes())
.expect("Failed to write to stdin");
}
let output = util::handle_cmd(child.wait_with_output()?).expect("sign tx");
let output = String::from_utf8(output).expect("parse utf8");
let output = output.trim_start_matches("Password:").trim();
let output: SignatureOutput = serde_json::from_str(output).expect("parse json");
if !output.recoverable {
panic!("expect recoverable signature")
}
let output_signature = output.signature.trim_start_matches("0x");
let mut signature = [0u8; 65];
hex_decode(output_signature.as_bytes(), &mut signature).expect("dehex");
let tx = util::attach_signature(tx, signature.to_vec().into(), 0);
Ok(tx)
}
pub fn query_transaction(&self, tx_hash: &H256) -> Result<Option<TransactionWithStatus>> {
let tx_opt = self.rpc_client().get_transaction(tx_hash.to_owned());
Ok(tx_opt)
}
pub fn send_transaction(&mut self, tx: TransactionView) -> Result<H256> {
let tx_hash: packed::Byte32 = self.rpc_client().send_transaction(tx.data().into());
self.lock_tx_inputs(&tx);
Ok(tx_hash.unpack())
}
pub fn lock_out_points(&mut self, out_points: impl Iterator<Item = packed::OutPoint>) {
for out_point in out_points {
self.collector.lock_cell(out_point);
}
}
pub fn lock_tx_inputs(&mut self, tx: &TransactionView) {
self.lock_out_points(tx.input_pts_iter());
}
pub fn collect_live_cells(&self, capacity: Capacity) -> HashSet<LiveCell> {
self.collector
.collect_live_cells(self.address().to_owned(), capacity)
}
fn lock_script(&self) -> packed::Script {
self.address().payload().into()
}
fn address(&self) -> &Address {
&self.address
}
fn rpc_client(&self) -> &RpcClient {
&self.rpc_client
}
}
|
use log::{info, warn};
use proxy_wasm::traits::*;
use proxy_wasm::types::*;
use serde_json::Value;
#[no_mangle]
pub fn _start() {
proxy_wasm::set_log_level(LogLevel::Info);
proxy_wasm::set_root_context(|_| -> Box<dyn RootContext> {
Box::new(PropagandaHeaderRoot {
config: FilterConfig {
head_tag_name: "".to_string(),
head_tag_value: "".to_string(),
},
})
});
}
struct PropagandaHeaderFilter {
context_id: u32,
config: FilterConfig,
}
struct PropagandaHeaderRoot {
config: FilterConfig,
}
struct FilterConfig {
head_tag_name: String,
head_tag_value: String,
}
impl HttpContext for PropagandaHeaderFilter {
fn on_http_request_headers(&mut self, _: usize) -> Action {
let head_tag_key = self.config.head_tag_name.as_str();
info!("::::head_tag_key={}", head_tag_key);
if !head_tag_key.is_empty() {
self.set_http_request_header(head_tag_key, Some(self.config.head_tag_value.as_str()));
//https://github.com/istio/istio/issues/30545#issuecomment-783518257
//https://github.com/proxy-wasm/spec/issues/16 &
//https://www.elvinefendi.com/2020/12/09/dynamic-routing-envoy-wasm.html
self.clear_http_route_cache();
}
for (name, value) in &self.get_http_request_headers() {
info!("::::H[{}] -> {}: {}", self.context_id, name, value);
}
Action::Continue
}
}
impl RootContext for PropagandaHeaderRoot {
fn on_configure(&mut self, _plugin_configuration_size: usize) -> bool {
if self.config.head_tag_name == "" {
match self.get_configuration() {
Some(config_bytes) => {
let cfg: Value = serde_json::from_slice(config_bytes.as_slice()).unwrap();
self.config.head_tag_name = cfg
.get("head_tag_name")
.unwrap()
.as_str()
.unwrap()
.to_string();
self.config.head_tag_value = cfg
.get("head_tag_value")
.unwrap()
.as_str()
.unwrap()
.to_string();
}
None => {
warn!("NO CONFIG");
}
}
}
true
}
fn create_http_context(&self, context_id: u32) -> Option<Box<dyn HttpContext>> {
info!(
"::::create_http_context head_tag_name={},head_tag_value={}",
self.config.head_tag_name, self.config.head_tag_value
);
Some(Box::new(PropagandaHeaderFilter {
context_id,
config: FilterConfig {
head_tag_name: self.config.head_tag_name.clone(),
head_tag_value: self.config.head_tag_value.clone(),
},
}))
}
fn get_type(&self) -> Option<ContextType> {
Some(ContextType::HttpContext)
}
}
impl Context for PropagandaHeaderFilter {}
impl Context for PropagandaHeaderRoot {}
|
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - Floating-point context control register"]
pub fpccr: FPCCR,
#[doc = "0x04 - Floating-point context address register"]
pub fpcar: FPCAR,
#[doc = "0x08 - Floating-point status control register"]
pub fpscr: FPSCR,
}
#[doc = "FPCCR (rw) register accessor: Floating-point context control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`fpccr::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 [`fpccr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`fpccr`]
module"]
pub type FPCCR = crate::Reg<fpccr::FPCCR_SPEC>;
#[doc = "Floating-point context control register"]
pub mod fpccr;
#[doc = "FPCAR (rw) register accessor: Floating-point context address register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`fpcar::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 [`fpcar::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`fpcar`]
module"]
pub type FPCAR = crate::Reg<fpcar::FPCAR_SPEC>;
#[doc = "Floating-point context address register"]
pub mod fpcar;
#[doc = "FPSCR (rw) register accessor: Floating-point status control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`fpscr::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 [`fpscr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`fpscr`]
module"]
pub type FPSCR = crate::Reg<fpscr::FPSCR_SPEC>;
#[doc = "Floating-point status control register"]
pub mod fpscr;
|
// https://adventofcode.com/2017/day/7
extern crate regex;
use std::io::{BufRead, BufReader};
use std::fs::File;
use std::collections::HashMap;
use std::collections::HashSet;
use regex::Regex;
fn main() {
// Regex for matching program and weight
let node_re = Regex::new(r"(\D+[a-z]) \((\d+)\)").unwrap();
// Read input to a map of name -> (weight, children) and set of all names
let f = BufReader::new(File::open("input.txt").expect("Opening input.txt failed"));
let mut program_nodes = HashMap::new();
let mut program_names = HashSet::new();
for line in f.lines() {
let raw_line = line.expect("Reading line failed");
// Split node info and children list
let main_split: Vec<&str> = raw_line.split(" -> ").collect();
// Match regex on node info
let cap = node_re.captures_iter(main_split[0]).last().unwrap();
let name = cap[1].to_string();
let weight = cap[2].parse::<i32>().unwrap();
// Get list of children
let children = match main_split.get(1) {
Some(split) => split.split(", ").map(|child| child.to_string()).collect(),
None => Vec::new(),
};
// Insert to map
program_nodes.insert(name.clone(), (weight, children));
program_names.insert(name);
}
let program_nodes = program_nodes;
// First star
// Find root by removing all children from set of names
for (_, value) in program_nodes.iter() {
if value.1.len() > 0 {
// Children can't be root
for child in &value.1 {
program_names.remove(child);
}
}
}
let root = program_names.into_iter().last().unwrap();
// Assert to facilitate further tweaks
assert_eq!("gynfwly", root);
println!("The root is {}", root);
// Second star
// Init DFS with root
let mut node_stack = Vec::new();
let mut weight_stack = Vec::new();
node_stack.push(vec![root; 1]);
// Do dfs while accumulating stack sums until the incorrect node is found
let mut corrected_weight = 0;
'dfs: while node_stack.len() > 0 {
// Check if unhandled nodes remain in topmost list
if node_stack.last_mut().unwrap().len() > 0 {
// Get the next node
let next_name = node_stack.last_mut().unwrap().last().unwrap().clone();
let next_info = program_nodes.get(&next_name).unwrap();
if next_info.1.len() > 0 {
// Parents
// Push children to stack
node_stack.push(next_info.1.clone());
// Init weights for this node's children
weight_stack.push(Vec::new());
} else {
// Leaf nodes
// Push own weight to topmost weights
weight_stack
.last_mut()
.unwrap()
.push((next_info.0, next_info.0));
// Pop self from nodes
node_stack.last_mut().unwrap().pop().unwrap();
}
} else {
// Pop empty node list
node_stack.pop().unwrap();
// Pop weights
let weights = weight_stack.pop().unwrap();
// Pop parent the children weights belong to
let parent_name = node_stack.last_mut().unwrap().pop().unwrap();
// Compare children's weights
for i in 1..(weights.len() - 1) {
if weights[i - 1].1 != weights[i].1 {
corrected_weight = if weights[i].1 != weights[i + 1].1 {
// Current weight is incorrect
weights[i].0 + (weights[i - 1].1 - weights[i].1)
} else {
// Previous weight is incorrect
weights[i - 1].0 + (weights[i].1 - weights[i - 1].1)
};
break 'dfs;
}
}
// Calculate combined stack weight and push to parent's parent's weight frame
let weight = program_nodes.get(&parent_name).unwrap().0;
weight_stack
.last_mut()
.unwrap()
.push((weight, weight + weights[0].1 * weights.len() as i32));
}
}
// Assert to facilitate further tweaks
assert_eq!(1526, corrected_weight);
println!("Corrected weight should be {}", corrected_weight);
}
|
use std::collections::HashMap;
use std::collections::hashmap::{Occupied, Vacant};
pub fn count(nucleotide: char, input: &str) -> uint {
input.chars().filter(|&c| c == nucleotide).count()
}
pub fn nucleotide_counts(input: &str) -> HashMap<char, uint> {
let mut map: HashMap<char, uint> = "ACGT".chars().map(|c| (c, 0)).collect();
for nucleotide in input.chars() {
match map.entry(nucleotide) {
Vacant(entry) => entry.set(1),
Occupied(mut entry) => {
*entry.get_mut() += 1;
entry.into_mut()
}
};
}
map
}
|
// This file is part of Substrate.
// Copyright (C) 2017-2020 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// 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.
//! The preimage tests.
use super::*;
#[test]
fn missing_preimage_should_fail() {
new_test_ext().execute_with(|| {
let r = Democracy::inject_referendum(
2,
set_balance_proposal_hash(2),
VoteThreshold::SuperMajorityApprove,
0,
);
assert_ok!(Democracy::vote(Origin::signed(1), r, aye(1)));
next_block();
next_block();
assert_eq!(Balances::free_balance(42), 0);
});
}
#[test]
fn preimage_deposit_should_be_required_and_returned() {
new_test_ext_execute_with_cond(|operational| {
// fee of 100 is too much.
PREIMAGE_BYTE_DEPOSIT.with(|v| *v.borrow_mut() = 100);
assert_noop!(
if operational {
Democracy::note_preimage_operational(Origin::signed(6), vec![0; 500])
} else {
Democracy::note_preimage(Origin::signed(6), vec![0; 500])
},
BalancesError::<Test, _>::InsufficientBalance,
);
// fee of 1 is reasonable.
PREIMAGE_BYTE_DEPOSIT.with(|v| *v.borrow_mut() = 1);
let r = Democracy::inject_referendum(
2,
set_balance_proposal_hash_and_note(2),
VoteThreshold::SuperMajorityApprove,
0,
);
assert_ok!(Democracy::vote(Origin::signed(1), r, aye(1)));
assert_eq!(Balances::reserved_balance(6), 12);
next_block();
next_block();
assert_eq!(Balances::reserved_balance(6), 0);
assert_eq!(Balances::free_balance(6), 60);
assert_eq!(Balances::free_balance(42), 2);
});
}
#[test]
fn preimage_deposit_should_be_reapable_earlier_by_owner() {
new_test_ext_execute_with_cond(|operational| {
PREIMAGE_BYTE_DEPOSIT.with(|v| *v.borrow_mut() = 1);
assert_ok!(if operational {
Democracy::note_preimage_operational(Origin::signed(6), set_balance_proposal(2))
} else {
Democracy::note_preimage(Origin::signed(6), set_balance_proposal(2))
});
assert_eq!(Balances::reserved_balance(6), 12);
next_block();
assert_noop!(
Democracy::reap_preimage(
Origin::signed(6),
set_balance_proposal_hash(2),
u32::max_value()
),
Error::<Test>::TooEarly
);
next_block();
assert_ok!(Democracy::reap_preimage(
Origin::signed(6),
set_balance_proposal_hash(2),
u32::max_value()
));
assert_eq!(Balances::free_balance(6), 60);
assert_eq!(Balances::reserved_balance(6), 0);
});
}
#[test]
fn preimage_deposit_should_be_reapable() {
new_test_ext_execute_with_cond(|operational| {
assert_noop!(
Democracy::reap_preimage(
Origin::signed(5),
set_balance_proposal_hash(2),
u32::max_value()
),
Error::<Test>::PreimageMissing
);
PREIMAGE_BYTE_DEPOSIT.with(|v| *v.borrow_mut() = 1);
assert_ok!(if operational {
Democracy::note_preimage_operational(Origin::signed(6), set_balance_proposal(2))
} else {
Democracy::note_preimage(Origin::signed(6), set_balance_proposal(2))
});
assert_eq!(Balances::reserved_balance(6), 12);
next_block();
next_block();
next_block();
assert_noop!(
Democracy::reap_preimage(
Origin::signed(5),
set_balance_proposal_hash(2),
u32::max_value()
),
Error::<Test>::TooEarly
);
next_block();
assert_ok!(Democracy::reap_preimage(
Origin::signed(5),
set_balance_proposal_hash(2),
u32::max_value()
));
assert_eq!(Balances::reserved_balance(6), 0);
assert_eq!(Balances::free_balance(6), 48);
assert_eq!(Balances::free_balance(5), 62);
});
}
#[test]
fn noting_imminent_preimage_for_free_should_work() {
new_test_ext_execute_with_cond(|operational| {
PREIMAGE_BYTE_DEPOSIT.with(|v| *v.borrow_mut() = 1);
let r = Democracy::inject_referendum(
2,
set_balance_proposal_hash(2),
VoteThreshold::SuperMajorityApprove,
1,
);
assert_ok!(Democracy::vote(Origin::signed(1), r, aye(1)));
assert_noop!(
if operational {
Democracy::note_imminent_preimage_operational(
Origin::signed(6),
set_balance_proposal(2),
)
} else {
Democracy::note_imminent_preimage(Origin::signed(6), set_balance_proposal(2))
},
Error::<Test>::NotImminent
);
next_block();
// Now we're in the dispatch queue it's all good.
assert_ok!(Democracy::note_imminent_preimage(Origin::signed(6), set_balance_proposal(2)));
next_block();
assert_eq!(Balances::free_balance(42), 2);
});
}
#[test]
fn reaping_imminent_preimage_should_fail() {
new_test_ext().execute_with(|| {
let h = set_balance_proposal_hash_and_note(2);
let r = Democracy::inject_referendum(3, h, VoteThreshold::SuperMajorityApprove, 1);
assert_ok!(Democracy::vote(Origin::signed(1), r, aye(1)));
next_block();
next_block();
assert_noop!(
Democracy::reap_preimage(Origin::signed(6), h, u32::max_value()),
Error::<Test>::Imminent
);
});
}
#[test]
fn note_imminent_preimage_can_only_be_successful_once() {
new_test_ext().execute_with(|| {
PREIMAGE_BYTE_DEPOSIT.with(|v| *v.borrow_mut() = 1);
let r = Democracy::inject_referendum(
2,
set_balance_proposal_hash(2),
VoteThreshold::SuperMajorityApprove,
1,
);
assert_ok!(Democracy::vote(Origin::signed(1), r, aye(1)));
next_block();
// First time works
assert_ok!(Democracy::note_imminent_preimage(Origin::signed(6), set_balance_proposal(2)));
// Second time fails
assert_noop!(
Democracy::note_imminent_preimage(Origin::signed(6), set_balance_proposal(2)),
Error::<Test>::DuplicatePreimage
);
// Fails from any user
assert_noop!(
Democracy::note_imminent_preimage(Origin::signed(5), set_balance_proposal(2)),
Error::<Test>::DuplicatePreimage
);
});
}
|
pub mod game;
pub mod io;
pub mod map;
pub mod math;
pub mod render;
pub mod things;
pub mod world;
|
use std::collections::HashSet;
const INPUT: &'static str = include_str!("../../../data/01");
fn main() {
println!("Part 1: {}", part1());
println!("Part 2: {}", part2());
}
fn part1() -> isize {
INPUT
.lines()
.map(|line| line.parse::<isize>().unwrap())
.sum()
}
fn part2() -> isize {
let mut frequency: isize = 0;
let mut frequencies_seen = HashSet::new();
frequencies_seen.insert(0);
for modulation in INPUT.lines().cycle() {
let modulation: isize = modulation.parse().expect("NaN");
frequency += modulation;
let was_not_set = frequencies_seen.insert(frequency);
if was_not_set == false {
break;
}
}
frequency
}
|
// `Structure` 구조체를 위한 `fmt::Debug` 구현을 얻는다.
// `Structure` 구조체는 단일 32비트 정수형 데이터를 포함하고 있는 구조체이다.
#[derive(Debug)]
struct Structure(i32);
// `Structure` 를 `Deep` 구조체 안에 넣는다.
// 그리고 역시 출력 가능하게 만든다.
#[derive(Debug)]
struct Deep(Structure);
#[derive(Debug)]
struct Person<'a> {
name: &'a str,
age: u8
}
fn main() {
// `{:?}`와 함께 출력하는 것은 `{}`와 함께 출력하는 것과 유사하다.
println!("{:?} months in a year.", 12);
println!("{1:?} {0:?} is the {actor:?} name.", "Slater", "Christian", actor="actor's");
// `Structure`는 이제 출력 가능하다!
println!("Now {:?} will print!", Structure(3));
// `derive`의 문제는 결과를 둘러볼 방법이 없다는 것이다. 만약 구조체 안의 '7'만 출력하길 원한다면??
println!("Now {:?} will print!", Deep(Structure(7)));
// 그래서 `fmt::debug`는 약간의 우아함을 희생해서 이를 출력 가능하게 만든다. Rust는 `{:#?}`를 통해 "pretty printing"을 제공한다.
println!("It is {:#?}", Structure(7));
let name = "Peter";
let age = 27;
let peter = Person {name, age};
// Pretty printing
println!("{:#?}", peter);
}
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
use core::mem::MaybeUninit;
use serde::Deserialize;
use serde::Serialize;
use super::super::response::*;
/// GDB-specific definition of the general purpose registers. This is only
/// *slightly* different from `libc::user_regs_struct`.
#[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
pub struct GeneralRegs {
// General purpose registers
pub x0: u64,
pub x1: u64,
pub x2: u64,
pub x3: u64,
pub x4: u64,
pub x5: u64,
pub x6: u64,
pub x7: u64,
pub x8: u64,
pub x9: u64,
pub x10: u64,
pub x11: u64,
pub x12: u64,
pub x13: u64,
pub x14: u64,
pub x15: u64,
pub x16: u64,
pub x17: u64,
pub x18: u64,
pub x19: u64,
pub x20: u64,
pub x21: u64,
pub x22: u64,
pub x23: u64,
pub x24: u64,
pub x25: u64,
pub x26: u64,
pub x27: u64,
pub x28: u64,
pub x29: u64,
pub x30: u64,
pub sp: u64,
pub pc: u64,
pub cpsr_flags: u32,
}
/// GDB-specific definition of the FPU registers.
#[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
pub struct FpRegs {
pub vregs: [u128; 32],
pub fpsr: u32,
pub fpcr: u32,
}
/// GDB-specific definition of the registers. This is only *slightly* different
/// from `libc::user_regs_struct`.
#[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
pub struct CoreRegs {
// General purpose registers
pub gpr: GeneralRegs,
// FPU registers
pub fpr: FpRegs,
}
impl From<libc::user_regs_struct> for GeneralRegs {
fn from(regs: libc::user_regs_struct) -> Self {
Self {
x0: regs.regs[0],
x1: regs.regs[1],
x2: regs.regs[2],
x3: regs.regs[3],
x4: regs.regs[4],
x5: regs.regs[5],
x6: regs.regs[6],
x7: regs.regs[7],
x8: regs.regs[8],
x9: regs.regs[9],
x10: regs.regs[10],
x11: regs.regs[11],
x12: regs.regs[12],
x13: regs.regs[13],
x14: regs.regs[14],
x15: regs.regs[15],
x16: regs.regs[16],
x17: regs.regs[17],
x18: regs.regs[18],
x19: regs.regs[19],
x20: regs.regs[20],
x21: regs.regs[21],
x22: regs.regs[22],
x23: regs.regs[23],
x24: regs.regs[24],
x25: regs.regs[25],
x26: regs.regs[26],
x27: regs.regs[27],
x28: regs.regs[28],
x29: regs.regs[29],
x30: regs.regs[30],
sp: regs.sp,
pc: regs.pc,
cpsr_flags: regs.pstate as u32,
}
}
}
impl From<GeneralRegs> for libc::user_regs_struct {
fn from(regs: GeneralRegs) -> Self {
let mut out = unsafe { MaybeUninit::<Self>::zeroed().assume_init() };
out.regs[0] = regs.x0;
out.regs[1] = regs.x1;
out.regs[2] = regs.x2;
out.regs[3] = regs.x3;
out.regs[4] = regs.x4;
out.regs[5] = regs.x5;
out.regs[6] = regs.x6;
out.regs[7] = regs.x7;
out.regs[8] = regs.x8;
out.regs[9] = regs.x9;
out.regs[10] = regs.x10;
out.regs[11] = regs.x11;
out.regs[12] = regs.x12;
out.regs[13] = regs.x13;
out.regs[14] = regs.x14;
out.regs[15] = regs.x15;
out.regs[16] = regs.x16;
out.regs[17] = regs.x17;
out.regs[18] = regs.x18;
out.regs[19] = regs.x19;
out.regs[20] = regs.x20;
out.regs[21] = regs.x21;
out.regs[22] = regs.x22;
out.regs[23] = regs.x23;
out.regs[24] = regs.x24;
out.regs[25] = regs.x25;
out.regs[26] = regs.x26;
out.regs[27] = regs.x27;
out.regs[28] = regs.x28;
out.regs[29] = regs.x29;
out.regs[30] = regs.x30;
out.sp = regs.sp;
out.pc = regs.pc;
out.pstate = regs.cpsr_flags as u64;
out
}
}
impl From<safeptrace::FpRegs> for FpRegs {
fn from(regs: safeptrace::FpRegs) -> Self {
Self {
vregs: regs.vregs,
fpsr: regs.fpsr,
fpcr: regs.fpcr,
}
}
}
impl From<FpRegs> for safeptrace::FpRegs {
fn from(regs: FpRegs) -> Self {
let mut out = unsafe { MaybeUninit::<Self>::zeroed().assume_init() };
out.vregs = regs.vregs;
out.fpsr = regs.fpsr;
out.fpcr = regs.fpcr;
out
}
}
impl CoreRegs {
pub fn from_parts(gpr: libc::user_regs_struct, fpr: safeptrace::FpRegs) -> Self {
Self {
gpr: gpr.into(),
fpr: fpr.into(),
}
}
pub fn into_parts(self) -> (libc::user_regs_struct, safeptrace::FpRegs) {
(self.gpr.into(), self.fpr.into())
}
}
impl WriteResponse for ResponseAsHex<CoreRegs> {
fn write_response(&self, f: &mut ResponseWriter) {
let encoded: Vec<u8> = bincode::serialize(&self.0).unwrap();
ResponseAsHex(encoded.as_slice()).write_response(f)
}
}
impl WriteResponse for ResponseAsBinary<CoreRegs> {
fn write_response(&self, f: &mut ResponseWriter) {
let encoded: Vec<u8> = bincode::serialize(&self.0).unwrap();
ResponseAsBinary(encoded.as_slice()).write_response(f)
}
}
|
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
extern crate fidl;
extern crate failure;
extern crate fuchsia_app as component;
extern crate fuchsia_async as async;
extern crate fuchsia_zircon as zx;
extern crate futures;
extern crate fidl_fidl_examples_echo;
use component::server::ServicesServer;
use failure::{Error, ResultExt};
use futures::future;
use futures::prelude::*;
use fidl::endpoints2::{ServiceMarker, RequestStream};
use fidl_fidl_examples_echo::{EchoMarker, EchoRequest, EchoRequestStream};
use std::env;
fn spawn_echo_server(chan: async::Channel, quiet: bool) {
async::spawn(EchoRequestStream::from_channel(chan)
.for_each(move |EchoRequest::EchoString { value, responder }| {
if !quiet {
println!("Received echo request for string {:?}", value);
}
responder.send(value.as_ref().map(|s| &**s))
.into_future()
.map(move |_| if !quiet {
println!("echo response sent successfully");
})
.recover(|e| eprintln!("error sending response: {:?}", e))
})
.map(|_| ())
.recover(|e| eprintln!("error running echo server: {:?}", e)))
}
fn main() -> Result<(), Error> {
let mut executor = async::Executor::new().context("Error creating executor")?;
let quiet = env::args().any(|arg| arg == "-q");
let fut = ServicesServer::new()
.add_service((EchoMarker::NAME, move |chan| spawn_echo_server(chan, quiet)))
.start()
.context("Error starting echo services server")?;
executor.run_singlethreaded(fut).context("failed to execute echo future")?;
Ok(())
}
|
use std::ops::{Add, Sub, Mul};
use std::num::Float;
/// A vector in 3D. What operations are available depends on the traits
/// implemented by the scalar type, N.
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Vector3<N> {
pub x: N,
pub y: N,
pub z: N,
}
impl<'a, N> Add for &'a Vector3<N> where N: Add<Output=N> + Copy {
type Output = Vector3<N>;
fn add(self, rhs: &Vector3<N>) -> Vector3<N> {
Vector3::<N> { x: self.x + rhs.x,
y: self.y + rhs.y,
z: self.z + rhs.z }
}
}
impl<'a, N> Sub for &'a Vector3<N> where N: Sub<Output=N> + Copy {
type Output = Vector3<N>;
fn sub(self, rhs: &Vector3<N>) -> Vector3<N> {
Vector3::<N> { x: self.x - rhs.x,
y: self.y - rhs.y,
z: self.z - rhs.z }
}
}
impl<'a, N> Mul<N> for &'a Vector3<N> where N: Mul<Output=N> + Copy {
type Output = Vector3<N>;
/// Multiplication by a scalar. Because of how traits over generic types
/// work, you should do `V * n`, not `n * V`.
fn mul(self, rhs: N) -> Vector3<N> {
Vector3::<N> { x: self.x * rhs,
y: self.y * rhs,
z: self.z * rhs }
}
}
impl<N> Vector3<N> where N: Mul<Output=N> + Add<Output=N> + Copy {
/// Dot-product of two vectors.
pub fn dot(&self, rhs: &Vector3<N>) -> N {
self.x * rhs.x + self.y * rhs.y + self.z * rhs.z
}
}
impl<N> Vector3<N> where N: Mul<Output=N> + Add<Output=N> +
Sub<Output=N> + Copy {
/// Cross-product of two vectors.
pub fn cross(&self, rhs: &Vector3<N>) -> Vector3<N> {
Vector3::<N> { x: self.y * rhs.z - self.z * rhs.y,
y: self.z * rhs.x - self.x * rhs.z,
z: self.x * rhs.y - self.y * rhs.x }
}
}
impl<N> Vector3<N> where N: Float {
/// Magnitude (length) of the vector. Expensive, because a square root is
/// involved.
pub fn mag(&self) -> N {
Float::sqrt(self.x * self.x + self.y * self.y + self.z * self.z)
}
}
impl<N> Vector3<N> where N: Float {
/// Normalized version of a vector: a vector with the same direction, but
/// a magnitude equal to 1.
pub fn norm(&self) -> Vector3<N> {
let mag: N = self.mag();
if mag == <N as Float>::zero() {
panic!("Norming 0-length vector");
}
let div: N = <N as Float>::one() / mag;
self * div
}
}
#[test]
pub fn test_ivec() {
type Vi = Vector3<i32>;
let a = Vi { x: 1, y: 2, z: -3 };
let b = Vi { x: 2, y: -2, z: 5 };
assert!(a != b);
assert!(a == a);
assert!(&a * 3 == Vi { x: 3, y: 6, z: -9 });
}
|
/// This program takes a MIPS instruction and reads it from a file. For each line, the program calls disassemble.
///
/// Usage: cargo run [filename]
/// To compile run cargo build, to run the program run cargo run (this will compile and run the program).
/// where filename is the name of the file you wish to translate from MIPS to assembly.
/// this argument is optional.
///
/// Input:
/// The program reads its input from a file passed in as a parameter
/// on the command line, or it reads from the standard input.
///
/// Output:
/// For each valid line, the program prints the mips instruction.
/// For each invalid line, the program prints an error message saying what the error was and
/// on what line it occurred.
///
/// AUTHOR: Zach LeBlanc
/// DATE: 2017-7-12
extern crate disassembler;
use std::env;
use std::fs::File;
use std::io::*;
use std::io;
fn main() {
//Get arguments from the command line
let args: Vec<String> = env::args().collect();
// if there is an argument process it
// only argument that should be passed is a filename
if args.len() > 1 {
let filename = &args[1];
let f = File::open(filename).expect("Error: file not found.");
let reader = BufReader::new(f);
let mut i = 0;
for line in reader.lines() {
let input = line.unwrap(); //have to unwrap it
let input_slice: &str = &input[..]; // disassemble_mips takes an input slice as argument, this creates the slice for the input
disassembler::disassemble::disassemble_mips(input_slice, i);
i += 1;
}
} else {
// no arguments passed
let mut counter = 1;
println!("Enter a 32 bit MIPS instruction:\nType exit to stop the program (or control-c on Unix operating systems):",);
loop {
let mut input = String::new();
io::stdin()
.read_line(&mut input)
.expect("Failed to read line");
let output = input.trim(); // need to trim input or it will not be able to find the file
if output.to_lowercase() == "exit" {
break;
}
disassembler::disassemble::disassemble_mips(output, counter);
counter += 1;
}
}
}
|
#[doc = r"Register block"]
#[repr(C)]
pub struct FB {
#[doc = "0x00 - Filter bank 0 register 1"]
pub fr1: FR1,
#[doc = "0x04 - Filter bank 0 register 2"]
pub fr2: FR2,
}
#[doc = "FR1 (rw) register accessor: Filter bank 0 register 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`fr1::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 [`fr1::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`fr1`]
module"]
pub type FR1 = crate::Reg<fr1::FR1_SPEC>;
#[doc = "Filter bank 0 register 1"]
pub mod fr1;
#[doc = "FR2 (rw) register accessor: Filter bank 0 register 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`fr2::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 [`fr2::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`fr2`]
module"]
pub type FR2 = crate::Reg<fr2::FR2_SPEC>;
#[doc = "Filter bank 0 register 2"]
pub mod fr2;
|
use yew::prelude::*;
mod home;
mod product_detail;
pub use home::Home;
pub use product_detail::ProductDetail;
fn spinner() -> Html {
html! {
<div class="loading_spinner_container">
<div class="loading_spinner"></div>
<div class="loading_spinner_text">{"Loading ..."}</div>
</div>
}
}
fn error(error: &str) -> Html {
html! {
<div>
<span>{error}</span>
</div>
}
}
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
use serde::Deserialize;
use serde::Serialize;
use super::super::response::*;
/// 80-bit FPU register, see gdb/64bit-core.xml
#[repr(transparent)]
#[derive(Copy, Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
pub struct Fp80([u8; 10]);
#[derive(Copy, Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
#[repr(transparent)]
pub struct St([Fp80; 8]);
/// Xmm registers.
#[derive(Copy, Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
#[repr(transparent)]
pub struct Xmm([u128; 16]);
/// i387 regs, gdb layout.
#[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
pub struct X87Regs {
/// fctrl
pub fctrl: u32,
/// fstat
pub fstat: u32,
/// ftag
pub ftag: u32,
/// fiseg
pub fiseg: u32,
/// fioff
pub fioff: u32,
/// foseg
pub foseg: u32,
/// fooff
pub fooff: u32,
/// fop
pub fop: u32,
}
/// AMD64 core/sse regs, see gdb/64bit-{core,sse}-linux.xml.
/// This is the same as: 64bit-core+64bit-sse+64bit-linux.
#[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
pub struct CoreRegs {
/// general purpose regsiters
/// rax/rbx/rcx/rdx/rsi/rdi/rbp/rsp/r8..r15
pub regs: [u64; 16],
/// rip aka instruction pointer
pub rip: u64,
/// eflags
pub eflags: u32,
/// cs, ss, ds, es, fs, gs
pub segments: [u32; 6],
/// 80-bit fpu regs
pub st: St,
/// fpu control regs
pub x87: X87Regs,
/// SSE registers
pub xmm: Xmm,
/// Sse status/control
pub mxcsr: u32,
pub orig_rax: u64,
pub fs_base: u64,
pub gs_base: u64,
}
/// amd64 avx regs
#[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
pub struct ExtraRegs {
/// avx registers
pub ymm: [u128; 32],
/// avx512 registers
pub ymmh: [u128; 32],
}
// NB: st from `libc::user_fpregs_struct' has a different representation.
fn from_u32s(st: &[u32]) -> Fp80 {
Fp80([
(st[0] & 0xff) as u8,
((st[0] >> 8) & 0xff) as u8,
((st[0] >> 16) & 0xff) as u8,
((st[0] >> 24) & 0xff) as u8,
(st[1] & 0xff) as u8,
((st[1] >> 8) & 0xff) as u8,
((st[1] >> 16) & 0xff) as u8,
((st[1] >> 24) & 0xff) as u8,
(st[2] & 0xff) as u8,
((st[2] >> 8) & 0xff) as u8,
])
}
impl From<[u32; 4]> for Fp80 {
fn from(v: [u32; 4]) -> Fp80 {
from_u32s(&v)
}
}
fn from_fp80(fp: &Fp80, u32s: &mut [u32]) {
u32s[0] =
fp.0[0] as u32 | (fp.0[1] as u32) << 8 | (fp.0[2] as u32) << 16 | (fp.0[3] as u32) << 24;
u32s[1] =
fp.0[4] as u32 | (fp.0[5] as u32) << 8 | (fp.0[6] as u32) << 16 | (fp.0[7] as u32) << 24;
u32s[2] = fp.0[8] as u32 | (fp.0[9] as u32) << 8;
u32s[3] = 0;
}
impl From<Fp80> for [u32; 4] {
fn from(fp: Fp80) -> [u32; 4] {
let mut res: [u32; 4] = [0; 4];
from_fp80(&fp, &mut res);
res
}
}
impl From<[u32; 32]> for St {
fn from(st: [u32; 32]) -> Self {
Self([
from_u32s(&st[0..]),
from_u32s(&st[4..]),
from_u32s(&st[8..]),
from_u32s(&st[12..]),
from_u32s(&st[16..]),
from_u32s(&st[20..]),
from_u32s(&st[24..]),
from_u32s(&st[28..]),
])
}
}
impl From<St> for [u32; 32] {
fn from(st: St) -> [u32; 32] {
let mut res: [u32; 32] = [0; 32];
from_fp80(&st.0[0], &mut res[0..]);
from_fp80(&st.0[1], &mut res[4..]);
from_fp80(&st.0[2], &mut res[8..]);
from_fp80(&st.0[3], &mut res[12..]);
from_fp80(&st.0[4], &mut res[16..]);
from_fp80(&st.0[5], &mut res[20..]);
from_fp80(&st.0[6], &mut res[24..]);
from_fp80(&st.0[7], &mut res[28..]);
res
}
}
#[inline]
fn u32s_to_u128(xs: &[u32]) -> u128 {
(xs[3] as u128) << 96 | (xs[2] as u128) << 64 | (xs[1] as u128) << 32 | (xs[0] as u128)
}
#[inline]
fn u128_to_u32s(u: u128, u32s: &mut [u32]) {
u32s[0] = u as u32;
u32s[1] = (u >> 32) as u32;
u32s[2] = (u >> 64) as u32;
u32s[3] = (u >> 96) as u32;
}
impl From<[u32; 64]> for Xmm {
fn from(xmm: [u32; 64]) -> Self {
Self([
u32s_to_u128(&xmm[0..4]),
u32s_to_u128(&xmm[4..8]),
u32s_to_u128(&xmm[8..12]),
u32s_to_u128(&xmm[12..16]),
u32s_to_u128(&xmm[16..20]),
u32s_to_u128(&xmm[20..24]),
u32s_to_u128(&xmm[24..28]),
u32s_to_u128(&xmm[28..32]),
u32s_to_u128(&xmm[32..36]),
u32s_to_u128(&xmm[36..40]),
u32s_to_u128(&xmm[40..44]),
u32s_to_u128(&xmm[44..48]),
u32s_to_u128(&xmm[48..52]),
u32s_to_u128(&xmm[52..56]),
u32s_to_u128(&xmm[56..60]),
u32s_to_u128(&xmm[60..64]),
])
}
}
impl From<Xmm> for [u32; 64] {
fn from(xmm: Xmm) -> [u32; 64] {
let mut res: [u32; 64] = [0; 64];
u128_to_u32s(xmm.0[0], &mut res[0..]);
u128_to_u32s(xmm.0[1], &mut res[4..]);
u128_to_u32s(xmm.0[2], &mut res[8..]);
u128_to_u32s(xmm.0[3], &mut res[12..]);
u128_to_u32s(xmm.0[4], &mut res[16..]);
u128_to_u32s(xmm.0[5], &mut res[20..]);
u128_to_u32s(xmm.0[6], &mut res[24..]);
u128_to_u32s(xmm.0[7], &mut res[28..]);
u128_to_u32s(xmm.0[8], &mut res[32..]);
u128_to_u32s(xmm.0[9], &mut res[36..]);
u128_to_u32s(xmm.0[10], &mut res[40..]);
u128_to_u32s(xmm.0[11], &mut res[44..]);
u128_to_u32s(xmm.0[12], &mut res[48..]);
u128_to_u32s(xmm.0[13], &mut res[52..]);
u128_to_u32s(xmm.0[14], &mut res[56..]);
u128_to_u32s(xmm.0[15], &mut res[60..]);
res
}
}
impl CoreRegs {
/// create `CoreRegs` from user and fp regs.
pub fn from_parts(regs: libc::user_regs_struct, i387: libc::user_fpregs_struct) -> Self {
Self {
regs: [
regs.rax, regs.rbx, regs.rcx, regs.rdx, regs.rsi, regs.rdi, regs.rbp, regs.rsp,
regs.r8, regs.r9, regs.r10, regs.r11, regs.r12, regs.r13, regs.r14, regs.r15,
],
rip: regs.rip,
eflags: regs.eflags as u32,
segments: [
regs.cs as u32,
regs.ss as u32,
regs.ds as u32,
regs.es as u32,
regs.fs as u32,
regs.fs as u32,
],
st: St::from(i387.st_space),
// NB: fpu/fxsave layout, see https://github.com/rr-debugger/rr/blob/master/src/ExtraRegisters.cc and
// https://elixir.bootlin.com/linux/latest/source/arch/x86/include/asm/user_64.h#L51
x87: X87Regs {
fctrl: i387.cwd as u32, // 0, short
fstat: i387.swd as u32, // 2, short
ftag: i387.ftw as u32, // 4, short
fiseg: (i387.rip >> 32) as u32, // 12,
fioff: (i387.rip & 0xffffffff) as u32, // 8,
foseg: (i387.rdp >> 32) as u32, // 20,
fooff: (i387.rdp & 0xffffffff) as u32, // 16,
fop: i387.fop as u32, // 6, short
},
xmm: Xmm::from(i387.xmm_space),
mxcsr: i387.mxcsr,
orig_rax: regs.orig_rax,
fs_base: regs.fs_base,
gs_base: regs.gs_base,
}
}
pub fn into_parts(self) -> (libc::user_regs_struct, libc::user_fpregs_struct) {
// NB: `padding` is private so we cannot use struct literal syntax.
let mut fpregs_intializer: libc::user_fpregs_struct =
unsafe { std::mem::MaybeUninit::zeroed().assume_init() };
fpregs_intializer.cwd = self.x87.fctrl as u16;
fpregs_intializer.swd = self.x87.fstat as u16;
fpregs_intializer.ftw = self.x87.ftag as u16;
fpregs_intializer.fop = self.x87.fop as u16;
fpregs_intializer.rip = self.x87.fioff as u64 | ((self.x87.fiseg as u64) << 32);
fpregs_intializer.rdp = self.x87.fooff as u64 | ((self.x87.foseg as u64) << 32);
fpregs_intializer.mxcsr = self.mxcsr;
fpregs_intializer.mxcr_mask = 0xffff; // only bit 0-15 are valid.
fpregs_intializer.st_space = self.st.into();
fpregs_intializer.xmm_space = self.xmm.into();
(
libc::user_regs_struct {
rax: self.regs[0],
rbx: self.regs[1],
rcx: self.regs[2],
rdx: self.regs[3],
rsi: self.regs[4],
rdi: self.regs[5],
rbp: self.regs[6],
rsp: self.regs[7],
r8: self.regs[8],
r9: self.regs[9],
r10: self.regs[10],
r11: self.regs[11],
r12: self.regs[12],
r13: self.regs[13],
r14: self.regs[14],
r15: self.regs[15],
orig_rax: self.orig_rax,
rip: self.rip,
cs: self.segments[0] as u64,
ss: self.segments[1] as u64,
ds: self.segments[2] as u64,
es: self.segments[3] as u64,
fs: self.segments[4] as u64,
gs: self.segments[5] as u64,
eflags: self.eflags as u64,
fs_base: self.fs_base,
gs_base: self.gs_base,
},
fpregs_intializer,
)
}
}
impl WriteResponse for ResponseAsHex<CoreRegs> {
fn write_response(&self, f: &mut ResponseWriter) {
let encoded: Vec<u8> = bincode::serialize(&self.0).unwrap();
ResponseAsHex(encoded.as_slice()).write_response(f)
}
}
impl WriteResponse for ResponseAsBinary<CoreRegs> {
fn write_response(&self, f: &mut ResponseWriter) {
let encoded: Vec<u8> = bincode::serialize(&self.0).unwrap();
ResponseAsBinary(encoded.as_slice()).write_response(f)
}
}
#[cfg(test)]
mod test {
use std::mem;
use super::*;
#[test]
fn fp80_sanity() {
assert_eq!(mem::size_of::<Fp80>(), 10);
let u32s: [u32; 4] = [0x12345678, 0x87654321, 0xabcd, 0];
let fp80: Fp80 = Fp80::from(u32s);
let u32s_1: [u32; 4] = fp80.into();
assert_eq!(u32s, u32s_1);
}
#[test]
fn st_sanity() {
let u32s: [u32; 32] = [
0x12345678, 0x87654321, 0xabcd, 0, 0x34127856, 0x56781234, 0xcdab, 0, 0x11223344,
0x44332211, 0xcadb, 0, 0x55667788, 0xaabbccdd, 0x1423, 0, 0x44332211, 0x11223344,
0x5678, 0, 0xaabbccdd, 0xddccbbaa, 0x1234, 0, 0xabcdabcd, 0xdeadbeef, 0x9876, 0,
0xdeadbeef, 0xdcbadcba, 0xac12, 0,
];
let st: St = St::from(u32s);
let u32s_1: [u32; 32] = st.into();
assert_eq!(u32s, u32s_1);
}
#[test]
fn xmm_sanity() {
let u32s: [u32; 64] = [
0x12345678, 0x87654321, 0xaabbccdd, 0xddccbbaa, 0x34127856, 0x65872143, 0xbbaaddcc,
0xccddaabb, 0xccddaabb, 0xbbaaddcc, 0x65872143, 0x34127856, 0xddccbbaa, 0xaabbccdd,
0x87654321, 0x12345678, 0x12345678, 0x87654321, 0xaabbccdd, 0xddccbbaa, 0x34127856,
0x65872143, 0xbbaaddcc, 0xccddaabb, 0xccddaabb, 0xbbaaddcc, 0x65872143, 0x34127856,
0xddccbbaa, 0xaabbccdd, 0x87654321, 0x12345678, 0x12345678, 0x87654321, 0xaabbccdd,
0xddccbbaa, 0x34127856, 0x65872143, 0xbbaaddcc, 0xccddaabb, 0xccddaabb, 0xbbaaddcc,
0x65872143, 0x34127856, 0xddccbbaa, 0xaabbccdd, 0x87654321, 0x12345678, 0x12345678,
0x87654321, 0xaabbccdd, 0xddccbbaa, 0x34127856, 0x65872143, 0xbbaaddcc, 0xccddaabb,
0xccddaabb, 0xbbaaddcc, 0x65872143, 0x34127856, 0xddccbbaa, 0xaabbccdd, 0x87654321,
0x12345678,
];
let xmm: Xmm = Xmm::from(u32s);
let u32s_1: [u32; 64] = xmm.into();
assert_eq!(u32s, u32s_1);
}
#[test]
fn amd64_core_regs_sanity() {
const EXPECTED_SIZE: usize = 16 * 8 + 8 + 4 + 4 * 6 + 10 * 8 + 8 * 4 + 16 * 16 + 4 + 8 * 3; // 560.
assert_eq!(mem::size_of::<CoreRegs>(), EXPECTED_SIZE);
let core_regs: CoreRegs = Default::default();
let encoded: Vec<u8> = bincode::serialize(&core_regs).unwrap();
assert_eq!(encoded.len(), EXPECTED_SIZE);
}
#[test]
fn amd64_core_regs_serde() {
let core_regs: CoreRegs = CoreRegs {
regs: [
0x1c,
0,
0,
0x7ffff7fe2f80,
0x7ffff7ffe6c8,
0x7ffff7ffe130,
0,
0x7fffffffdd20,
0x4d,
0x7ffff7f91860,
0xc2,
0,
0x401040,
0x7fffffffdd20,
0,
0,
],
rip: 0x401040,
eflags: 0x206,
segments: [0x33, 0x2b, 0, 0, 0, 0],
st: St([
Fp80([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]),
Fp80([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]),
Fp80([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]),
Fp80([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]),
Fp80([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]),
Fp80([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]),
Fp80([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]),
Fp80([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]),
]),
x87: X87Regs {
fctrl: 0x37f,
fstat: 0,
ftag: 0,
fiseg: 0,
fioff: 0,
foseg: 0,
fooff: 0,
fop: 0,
},
xmm: Xmm([
0xff000000,
0x2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f,
0xff000000000000,
0xff0000000000000000ff000000ff0000,
0,
0,
6,
0,
0,
0,
0,
0,
0,
0,
0,
0,
]),
mxcsr: 0x1f80,
orig_rax: 0xffffffffffffffff,
fs_base: 0x7ffff7fcd540,
gs_base: 0,
};
let encoded: Vec<u8> = bincode::serialize(&core_regs).unwrap();
// NB: keep this so that we can *visualize* how core regs are
// serialized.
let expected: Vec<u8> = vec![
0x1c, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x80, 0x2f, 0xfe, 0xf7, 0xff, 0x7f, 0x0, 0x0, 0xc8,
0xe6, 0xff, 0xf7, 0xff, 0x7f, 0x0, 0x0, 0x30, 0xe1, 0xff, 0xf7, 0xff, 0x7f, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x20, 0xdd, 0xff, 0xff, 0xff, 0x7f, 0x0, 0x0,
0x4d, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x60, 0x18, 0xf9, 0xf7, 0xff, 0x7f, 0x0, 0x0,
0xc2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40,
0x10, 0x40, 0x0, 0x0, 0x0, 0x0, 0x0, 0x20, 0xdd, 0xff, 0xff, 0xff, 0x7f, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x10,
0x40, 0x0, 0x0, 0x0, 0x0, 0x0, 0x6, 0x2, 0x0, 0x0, 0x33, 0x0, 0x0, 0x0, 0x2b, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x7f, 0x3, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xff, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f,
0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0xff, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xff, 0x0, 0x0, 0x0, 0xff,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xff, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x6, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x80, 0x1f, 0x0,
0x0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x40, 0xd5, 0xfc, 0xf7, 0xff,
0x7f, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
];
assert_eq!(encoded, expected);
let core_regs2 = bincode::deserialize(&encoded).unwrap();
assert_eq!(core_regs, core_regs2);
}
}
|
pub type ApuData = super::Apu;
impl super::Apu{
pub fn save_state(&self) -> ApuData {
self.clone()
}
pub fn load_state(&mut self, data: ApuData) {
self.square1 = data.square1;
self.square2 = data.square2;
self.triangle = data.triangle;
self.noise = data.noise;
self.dmc = data.dmc;
self.square_table = data.square_table;
self.tnd_table = data.tnd_table;
self.frame_sequence = data.frame_sequence;
self.frame_counter = data.frame_counter;
self.interrupt_inhibit = data.interrupt_inhibit;
self.frame_interrupt = data.frame_interrupt;
self.cycle = data.cycle;
self.trigger_irq = data.trigger_irq;
}
}
|
use hydroflow::hydroflow_syntax;
pub fn main() {
// An edge in the input data = a pair of `usize` vertex IDs.
let (edges_send, edges_recv) = hydroflow::util::unbounded_channel::<(usize, usize)>();
let mut flow = hydroflow_syntax! {
// inputs: the origin vertex (vertex 0) and stream of input edges
origin = source_iter(vec![0]);
stream_of_edges = source_stream(edges_recv);
// the join
reached_vertices -> map(|v| (v, ())) -> [0]my_join_tee;
stream_of_edges -> [1]my_join_tee;
my_join_tee = join() -> flat_map(|(src, ((), dst))| [src, dst]) -> tee();
// the cycle: my_join_tee gets data from reached_vertices
// and provides data back to reached_vertices!
origin -> [base]reached_vertices;
my_join_tee -> [cycle]reached_vertices;
reached_vertices = union();
// the output
my_join_tee[print] -> unique() -> for_each(|x| println!("Reached: {}", x));
};
println!(
"{}",
flow.meta_graph()
.expect("No graph found, maybe failed to parse.")
.to_mermaid()
);
edges_send.send((0, 1)).unwrap();
edges_send.send((2, 4)).unwrap();
edges_send.send((3, 4)).unwrap();
edges_send.send((1, 2)).unwrap();
edges_send.send((0, 3)).unwrap();
edges_send.send((0, 3)).unwrap();
edges_send.send((4, 0)).unwrap();
flow.run_available();
}
|
#[macro_use]
extern crate diesel;
extern crate dotenv;
pub mod models;
pub mod schema;
use diesel::prelude::*;
use dotenv::dotenv;
use models::NewUser;
pub fn establish_connection() -> SqliteConnection {
dotenv().ok();
let database_url = "database/test.db";
SqliteConnection::establish(&database_url)
.unwrap_or_else(|_| panic!("Error connecting to {}", database_url))
}
pub fn create_user(conn: &SqliteConnection, name: &str, email: &str, password: &str) -> bool {
use schema::users;
let new_user = NewUser { name, email, password };
let rows_inserted=diesel::insert_into(users::table)
.values(&new_user)
.execute(conn);
match rows_inserted {
Err(_) => return false,
Ok(_) => return true,
}
}
|
#[derive(Debug)]
pub struct UserInfo {
pub age: Option<u32>,
pub county: Option<String>,
pub child_count: Option<u32>,
pub child_info: Option<Vec<UserInfo>>,
pub annual_income: Option<u32>,
pub single_parent: Option<bool>,
}
impl UserInfo {
pub fn new() -> UserInfo {
UserInfo {
age: None,
county: None,
child_count: None,
child_info: None,
annual_income: None,
single_parent: None,
}
}
pub fn set_age<'a>(&'a mut self, age: u32) -> &'a mut Self {
self.age = Some(age);
self
}
pub fn set_county<'a>(&'a mut self, county: &str) -> &'a mut Self {
self.county = Some(county.to_string());
self
}
// TODO: should probably just be updated by changing the child_info field
pub fn set_child_count<'a>(&'a mut self, count: u32) -> &'a mut Self {
self.child_count = Some(count);
self
}
pub fn set_annual_income<'a>(&'a mut self, income: u32) -> &'a mut Self {
self.annual_income = Some(income);
self
}
pub fn set_single_parent<'a>(&'a mut self, value: bool) -> &'a mut Self {
self.single_parent = Some(value);
self
}
}
|
#![allow(unused_variables)]
use chrono::NaiveDateTime;
use sqlx_helper::{Create, Delete, Get, Update};
#[derive(Debug, Clone, Get, Create, Delete, Update)]
pub struct Submission {
#[get(pk)]
pub id: i32,
pub epoch_second: NaiveDateTime,
pub problem_id: String,
pub contest_id: String,
pub result: String,
pub atcoder_id: String,
pub language: String,
pub point: i32,
pub length: i32,
pub execution_time: i32,
pub account_id: i64,
}
fn main() {}
|
use amethyst::{
core::Transform,
core::ecs::{Join, System, WriteStorage, ReadStorage, Entities},
};
use crate::components::player::Player;
use crate::components::block::Block;
use crate::components::object::*;
use crate::components::score::Score;
use amethyst::core::ecs::WriteExpect;
pub struct CollisionSystem;
impl<'a> System<'a> for CollisionSystem {
type SystemData = (
WriteExpect<'a, Score>,
ReadStorage<'a, Transform>,
ReadStorage<'a, Block>,
ReadStorage<'a, Player>,
Entities<'a>,
);
fn run(&mut self, (mut score, transforms, blocks, players, entities): Self::SystemData) {
if !score.is_start || score.is_dead {
return;
}
for (player_transform, player) in (&transforms, &players).join() {
for (block_transform, block, entity) in (&transforms, &blocks, &*entities).join() {
let is_hit = is_hit(player_transform, &player.size, block_transform, &block.size);
if is_hit {
if block.is_rock {
score.is_dead = true;
} else {
if score.is_dead {
return;
}
score.score += 100;
}
entities.delete(entity);
}
}
}
}
}
|
use core::time;
use rand::prelude::SliceRandom;
use rand::thread_rng;
use std::{io, thread};
pub struct Util;
impl Util {
pub fn shuffle_vec<T: std::clone::Clone>(mut items: Vec<T>) -> Vec<T> {
let slice = items.as_mut_slice();
let mut rng = thread_rng();
slice.shuffle(&mut rng);
slice.to_vec()
}
pub fn print_wizard_ascii_art() {
println!(" _ _\n (_) | |\n __ ___ ______ _ _ __ __| |\n \\ \\ /\\ / / |_ / _` | \'__/ _` |\n \\ V V /| |/ / (_| | | | (_| |\n \\_/\\_/ |_/___\\__,_|_| \\__,_|\n");
}
pub fn cli_next_string() -> String {
let mut buffer = String::new();
loop {
io::stdin().read_line(&mut buffer).unwrap();
match buffer.trim().parse::<String>() {
Ok(input) => {
if !input.is_empty() {
return input;
}
}
Err(_) => {}
}
}
}
pub fn cli_next_num() -> u8 {
loop {
match Util::cli_next_string().parse::<u8>() {
Ok(num) => {
return num;
}
Err(_) => {
println!(" * Input must be a whole number * ");
}
}
}
}
pub fn cli_next_pos_num() -> u8 {
loop {
let num = Util::cli_next_num();
if num == 0 {
println!(" * Input must be a positive number * ");
continue;
}
return num;
}
}
pub fn press_enter_to_(verb: &str) {
println!("\nPress Enter to {}...", verb);
let mut buffer = String::new();
io::stdin().read_line(&mut buffer).unwrap();
}
pub fn sleep() {
thread::sleep(time::Duration::from_millis(500));
}
}
|
#[doc = "Register `HWCFGR1` reader"]
pub type R = crate::R<HWCFGR1_SPEC>;
#[doc = "Field `CFG1` reader - CFG1"]
pub type CFG1_R = crate::FieldReader;
#[doc = "Field `CFG2` reader - CFG2"]
pub type CFG2_R = crate::FieldReader;
#[doc = "Field `CFG3` reader - CFG3"]
pub type CFG3_R = crate::FieldReader;
#[doc = "Field `CFG4` reader - CFG4"]
pub type CFG4_R = crate::FieldReader;
#[doc = "Field `CFG5` reader - CFG5"]
pub type CFG5_R = crate::FieldReader;
#[doc = "Field `CFG6` reader - CFG6"]
pub type CFG6_R = crate::FieldReader;
#[doc = "Field `CFG7` reader - CFG7"]
pub type CFG7_R = crate::FieldReader;
#[doc = "Field `CFG8` reader - CFG8"]
pub type CFG8_R = crate::FieldReader;
impl R {
#[doc = "Bits 0:3 - CFG1"]
#[inline(always)]
pub fn cfg1(&self) -> CFG1_R {
CFG1_R::new((self.bits & 0x0f) as u8)
}
#[doc = "Bits 4:7 - CFG2"]
#[inline(always)]
pub fn cfg2(&self) -> CFG2_R {
CFG2_R::new(((self.bits >> 4) & 0x0f) as u8)
}
#[doc = "Bits 8:11 - CFG3"]
#[inline(always)]
pub fn cfg3(&self) -> CFG3_R {
CFG3_R::new(((self.bits >> 8) & 0x0f) as u8)
}
#[doc = "Bits 12:15 - CFG4"]
#[inline(always)]
pub fn cfg4(&self) -> CFG4_R {
CFG4_R::new(((self.bits >> 12) & 0x0f) as u8)
}
#[doc = "Bits 16:19 - CFG5"]
#[inline(always)]
pub fn cfg5(&self) -> CFG5_R {
CFG5_R::new(((self.bits >> 16) & 0x0f) as u8)
}
#[doc = "Bits 20:23 - CFG6"]
#[inline(always)]
pub fn cfg6(&self) -> CFG6_R {
CFG6_R::new(((self.bits >> 20) & 0x0f) as u8)
}
#[doc = "Bits 24:27 - CFG7"]
#[inline(always)]
pub fn cfg7(&self) -> CFG7_R {
CFG7_R::new(((self.bits >> 24) & 0x0f) as u8)
}
#[doc = "Bits 28:31 - CFG8"]
#[inline(always)]
pub fn cfg8(&self) -> CFG8_R {
CFG8_R::new(((self.bits >> 28) & 0x0f) as u8)
}
}
#[doc = "USART Hardware Configuration register 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`hwcfgr1::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct HWCFGR1_SPEC;
impl crate::RegisterSpec for HWCFGR1_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`hwcfgr1::R`](R) reader structure"]
impl crate::Readable for HWCFGR1_SPEC {}
#[doc = "`reset()` method sets HWCFGR1 to value 0x14"]
impl crate::Resettable for HWCFGR1_SPEC {
const RESET_VALUE: Self::Ux = 0x14;
}
|
use std::cmp::min;
use proconio::input;
fn main() {
input! {
n: usize,
}
let mut min_p = -1;
for _i in 0..n {
input!{
a: i64,
p: i64,
x: i64,
}
let stock = x - a;
if stock > 0 {
if min_p < 0 {
min_p = p;
} else {
min_p = min(p, min_p);
}
}
}
println!("{}", min_p);
}
|
use crate::util::Part;
use std::collections::{HashSet, HashMap};
pub fn solve(input:String, part:Part) -> String {
let result = match part {
Part::Part1 => part1(input),
Part::Part2 => part2(input,200)
};
format!("{}",result)
}
fn part1(input:String) -> usize {
let mut state = parse(input.as_str());
let mut set = HashSet::new();
set.insert(state);
loop {
state = next_state(state);
if set.contains(&state) {
return state as usize;
} else {
set.insert(state);
}
}
}
fn part2(input:String, iterations:i32) -> usize {
let state = parse(input.as_str());
let level_min = -iterations ;
let level_max = iterations;
let mut map:HashMap<i32,u32> = HashMap::new();
// Init states
let mut i:i32 = level_min;
while i <= level_max {
map.insert(i,0);
i += 1;
}
// init state
map.insert(0, state);
// Mutate state
for _ in 0..iterations {
let mut next_state = map.clone();
i = level_min+1;
while i < level_max as i32 {
let state = *map.get(&i).unwrap();
let outer_state = *map.get(&(i-1)).unwrap();
let inner_state = *map.get( &(i+1)).unwrap();
let next = next_state_rec(inner_state, outer_state, state);
// Update new map
next_state.insert( i , next);
i+=1;
}
// Update states
map = next_state;
}
map.iter().map(|(_,v)| count_bits(*v)).sum()
}
fn count_bits(state:u32) -> usize {
let mut res = 0;
for n in 0..32 {
if n != 12 && (1 << n & state) > 0 {
res += 1;
}
}
res
}
fn parse(input:&str) -> u32 {
let state:u32 = input.chars().filter(|ch| *ch == '.' || *ch == '#')
.enumerate()
.map(|(n, ch)| {
match ch {
'#' => 1 << n,
_ => 0,
}
}).sum();
state
}
fn next_state(state:u32) -> u32 {
let mut next_state:u32 = 0;
for n in 0..25 {
// Up
let up = if n > 4 {
state & 1 << (n-5)
} else {
0
};
let right = if (n+1) % 5 == 0 && n != 0 {
0
} else {
state & 1 << (n+1)
};
let left = if n % 5 == 0 {
0
} else {
state & 1 << (n-1)
};
let down = if n < 20 {
state & 1 << (n+5)
} else {
0
};
let adjacent = [up,down,left,right].iter().filter(|item| **item > 0).count();
let has_bug = (state & 1 << n) > 0;
//println!("Pos:{}, up:{},down:{},left:{},right:{}", n, up>0,down>0,left>0,right>0);
//println!("pos {} has {} adjacent bugs",n,sum);
if adjacent != 1 && has_bug {
// Has bug that should vanish
next_state &= !(state & (1 << n));
//println!("pos {} Bug should die, mask = {:#b}",n,!(state & (1 << n)));
} else if !has_bug && (adjacent == 1 || adjacent == 2){
// No bug, new bug should pop up
next_state |= 1 << n;
//println!("pos {} Should have NEW bug, next state={:#b}, mask={:#b}",n,next_state,state & (1 << n));
} else if adjacent == 1 && has_bug {
//println!("pos {} Should LIVE",n);
// Bug should live
next_state |= 1 << n;
}
}
next_state
}
fn next_state_rec(inner:u32,outer:u32,state:u32) -> u32 {
let mut next_state = 0;
for n in 0..25 {
if n == 12 {
continue;
}
// Up ?
let up = if n > 4 && n != 17 {
vec![(state & 1 << (n-5)) > 0]
} else if n < 5 {
get_inner_up(outer)
} else {
get_outer_bottom(inner)
};
// Right
let right = if (n+1) % 5 == 0 && n != 0 {
get_inner_right(outer)
} else if n == 11 {
get_outer_left(inner)
} else {
vec![(state & 1 << (n+1)) > 0]
};
// Left
let left = if n % 5 == 0 {
get_inner_left(outer)
} else if n == 13 {
get_outer_right(inner)
} else {
vec![(state & 1 << (n-1))>0]
};
// Down
let down = if n < 20 && n != 7{
vec![ (state & 1 << (n+5)) > 0]
} else if n == 7 {
get_outer_top(inner)
} else {
get_inner_down(outer)
};
let adjacent = [up,down,left,right].iter().flatten().filter(|p| **p).count();
let has_bug = (state & 1 << n) > 0;
if adjacent != 1 && has_bug {
// Has bug that should vanish
next_state &= !(state & (1 << n));
//println!("pos {} Bug should die, mask = {:#b}",n,!(state & (1 << n)));
} else if !has_bug && (adjacent == 1 || adjacent == 2){
// No bug, new bug should pop up
next_state |= 1 << n;
//println!("pos {} Should have NEW bug, next state={:#b}, mask={:#b}",n,next_state,state & (1 << n));
} else if adjacent == 1 && has_bug {
//println!("pos {} Should LIVE",n);
// Bug should live
next_state |= 1 << n;
}
}
next_state
}
fn get_outer_left(state:u32) -> Vec<bool> {
let n = [0,5,10,15,20];
n.iter().map( |bit_no| (state & 1 << *bit_no) > 0).collect()
}
fn get_outer_right(state:u32) -> Vec<bool> {
let n = [4,9,14,19,24];
n.iter().map( |bit_no| (state & 1 << *bit_no) > 0).collect()
}
fn get_outer_top(state:u32) -> Vec<bool> {
let n = [0,1,2,3,4];
n.iter().map( |bit_no| (state & 1 << *bit_no) > 0).collect()
}
fn get_outer_bottom(state:u32) -> Vec<bool> {
let n = [20,21,22,23,24];
n.iter().map( |bit_no| (state & 1 << *bit_no) > 0).collect()
}
fn get_inner_left(state:u32) -> Vec<bool> {
vec![(state & 1 << 11) > 0]
}
fn get_inner_up(state:u32) -> Vec<bool> {
vec![(state & 1 << 7) > 0]
}
fn get_inner_down(state:u32) -> Vec<bool> {
vec![(state & 1 << 17) > 0]
}
fn get_inner_right(state:u32) -> Vec<bool> {
vec![(state & 1 << 13) > 0]
}
fn to_string(state:u32) -> String {
let mut s = String::new();
for n in 0..25 {
if n % 5 == 0 && n > 0 {
s.push('\n');
}
if state & 1 << n == 0 {
s.push('.');
} else {
s.push('#');
}
}
s
}
#[cfg(test)]
mod tests {
// Note this useful idiom: importing names from outer (for mod tests) scope.
use super::*;
#[test]
fn test1() {
let input = "....#
#..#.
#..##
..#..
#....";
let res = parse(input);
println!("res={}",res);
}
#[test]
fn test2() {
let input = ".....
.....
.....
#....
.#...";
assert_eq!(2129920,parse(input));
}
#[test]
fn test3() {
let input = "....#
#..#.
#..##
..#..
#....";
let state = parse(input);
let state1 = next_state(state);
let state2 = next_state(state1);
let state3 = next_state(state2);
let state4 = next_state(state3);
let state1_str = to_string(state1);
let state2_str = to_string(state2);
let state3_str = to_string(state3);
let state4_str = to_string(state4);
assert_eq!(state1_str,"#..#.
####.
###.#
##.##
.##..");
assert_eq!(state2_str,"#####
....#
....#
...#.
#.###");
assert_eq!(state3_str,"#....
####.
...##
#.##.
.##.#");
assert_eq!(state4_str,"####.
....#
##..#
.....
##...");
}
#[test]
fn test4() {
let input = "....#
#..#.
#..##
..#..
#....";
let res = part1(input.to_string());
println!("{}",res);
assert_eq!(res,2129920)
}
#[test]
fn test_part1() {
let input = "#.#..
.#.#.
#...#
.#..#
##.#.";
let res = part1(input.to_string());
println!("{}",res);
assert_eq!(res,25719471)
}
#[test]
fn test_part2_test1() {
let input = "....#
#..#.
#..##
..#..
#....";
let res = part2(input.to_string(),10);
println!("{}",res);
assert_eq!(res,99)
}
#[test]
fn test_part2() {
let input = "#.#..
.#.#.
#...#
.#..#
##.#.";
let res = part2(input.to_string(),200);
println!("{}",res);
assert_eq!(res,1916)
}
}
|
use ocl;
use super::{OpenCLBuf, OpenCLMemory};
use super::super::super::compute_device::{Allocate, ComputeDevice};
use super::super::super::error::Result;
use super::super::super::memory::Memory;
use super::super::super::tensor::{TensorShape, TensorType};
/// Represents an Open CL device.
#[derive(Clone, Debug)]
pub struct OpenCLDevice {
pub(in frameworks::open_cl) device: ocl::Device,
pub(in frameworks::open_cl) context: ocl::Context,
/// A command queue
///
/// A command queue is the mechanism for interaction with the device. The queue is used for
/// operations such as kernel launches and memory copies. At least one command queue per device
/// is required. Queues are used by the host application to submit work to devices and
/// associated with devices within a context.
///
/// __commands__:
///
/// - memory copy or mapping
/// - device code execution
/// - synchronization point
///
/// __modes__:
///
/// - in-order
/// - out-of-order
///
/// ## TODO
///
/// * Use events to synchronize
pub(in frameworks::open_cl) queue: ocl::Queue,
}
impl OpenCLDevice {
pub fn queue(&self) -> &ocl::Queue {
&self.queue
}
}
impl ComputeDevice for OpenCLDevice { }
impl<T> Allocate<T> for OpenCLDevice where T: TensorType + 'static {
fn allocate(&self, shape: &TensorShape) -> Result<Box<Memory<T>>> {
let ctx = &self.context;
let flags_opt = Some(ocl::flags::MEM_READ_WRITE);
let dims = ocl::SpatialDims::One(shape.capacity);
let host_data = None;
let buf: OpenCLBuf<T> = OpenCLBuf {
buf: ocl::Buffer::new(ctx, flags_opt, dims, host_data)?
};
let device = self.clone();
let memory = Box::new(OpenCLMemory {
buf,
device,
});
return Ok(memory);
}
} |
extern crate conrod;
|
// Copyright (c) 2015 Y. T. Chung <zonyitoo@gmail.com>
// 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. All files in the project carrying such
// notice may not be copied, modified, or distributed except
// according to those terms.
#![crate_type = "lib"]
#![crate_name = "memcached"]
#![cfg_attr(feature = "nightly", feature(test))]
#[cfg(feature = "nightly")]
extern crate test;
#[macro_use] extern crate log;
extern crate conhash;
extern crate byteorder;
extern crate semver;
extern crate rand;
#[cfg(unix)]
extern crate unix_socket;
extern crate bufstream;
pub use client::Client;
pub mod proto;
pub mod client;
|
use serde::de::Deserialize;
#[derive(Deserialize, Debug)]
pub struct StoryNode {
pub id: String,
pub content: String,
pub answers: Vec<StoryAnswer>,
}
#[derive(Deserialize, Debug)]
pub struct StoryAnswer {
pub id: String,
pub content: String,
pub next: Option<String>,
}
|
use crate::commands::WholeStreamCommand;
use crate::errors::ShellError;
use crate::format::TableView;
use crate::prelude::*;
pub struct Table;
#[derive(Deserialize)]
pub struct TableArgs {}
impl WholeStreamCommand for Table {
fn name(&self) -> &str {
"table"
}
fn signature(&self) -> Signature {
Signature::build("table")
}
fn usage(&self) -> &str {
"View the contents of the pipeline as a table."
}
fn run(
&self,
args: CommandArgs,
registry: &CommandRegistry,
) -> Result<OutputStream, ShellError> {
args.process(registry, table)?.run()
}
}
pub fn table(_args: TableArgs, context: RunnableContext) -> Result<OutputStream, ShellError> {
let stream = async_stream! {
let input: Vec<Tagged<Value>> = context.input.into_vec().await;
if input.len() > 0 {
let mut host = context.host.lock().unwrap();
let view = TableView::from_list(&input);
if let Some(view) = view {
handle_unexpected(&mut *host, |host| crate::format::print_view(&view, host));
}
}
// Needed for async_stream to type check
if false {
yield ReturnSuccess::value(Value::nothing().tagged_unknown());
}
};
Ok(OutputStream::new(stream))
}
|
use common::TagClass;
use super::ASNTag;
use universal;
use structure;
use std::default;
use byteorder::{BigEndian, WriteBytesExt};
/// Integer value.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Integer {
pub id: u64,
pub class: TagClass,
pub inner: i64,
}
/// Integer with a different tag.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Enumerated {
pub id: u64,
pub class: TagClass,
pub inner: i64,
}
fn i_e_into_structure(id: u64, class: TagClass, inner: i64) -> structure::StructureTag {
let mut count = 0u8;
let mut rem: i64 = if inner >= 0 { inner } else { inner * -1 };
while {count += 1; rem >>= 8; rem > 0 }{}
let mut out: Vec<u8> = Vec::with_capacity(count as usize);
out.write_int::<BigEndian>(inner, count as usize).unwrap();
structure::StructureTag {
id: id,
class: class,
payload: structure::PL::P(out),
}
}
impl ASNTag for Integer {
fn into_structure(self) -> structure::StructureTag {
i_e_into_structure(self.id, self.class, self.inner)
}
}
impl ASNTag for Enumerated {
fn into_structure(self) -> structure::StructureTag {
i_e_into_structure(self.id, self.class, self.inner)
}
}
impl default::Default for Integer {
fn default() -> Integer {
Integer {
id: universal::Types::Integer as u64,
class: TagClass::Universal,
inner: 0i64,
}
}
}
impl default::Default for Enumerated {
fn default() -> Enumerated {
Enumerated {
id: universal::Types::Enumerated as u64,
class: TagClass::Universal,
inner: 0i64,
}
}
}
|
use bevy::prelude::*;
pub fn is_colliding_with_walls(window: &mut Window, transform: &mut Mut<Transform>) -> bool {
let pos_x_abs = transform.translation.x.abs();
let pos_y_bas = transform.translation.y.abs();
let max_x = window.width() / 2.;
let max_y = window.height() / 2.;
if pos_x_abs >= max_x {
if transform.translation.x > 0. {
transform.translation.x -= 1.;
} else {
transform.translation.x += 1.;
}
return true;
}
if pos_y_bas >= max_y {
if transform.translation.y > 0. {
transform.translation.y -= 1.;
} else {
transform.translation.y += 1.;
}
return true;
}
false
}
|
use actix_web::web;
use actix_web::Responder;
pub mod common;
pub mod configuration;
pub mod sessions;
pub mod translations;
pub mod users;
pub async fn index() -> impl Responder {
"Welcome to Metaphrase API!"
}
pub fn config(cfg: &mut web::ServiceConfig) {
cfg.route("/", web::get().to(index));
cfg.service(
web::resource("/configuration")
.name("configuration")
.route(web::get().to(configuration::index)),
);
cfg.service(
web::resource("/login")
.name("login")
.route(web::post().to(sessions::login)),
);
cfg.service(
web::resource("/logout")
.name("logout")
.route(web::post().to(sessions::logout)),
);
cfg.service(
web::resource("/translations")
.name("translations")
.route(web::get().to(translations::index))
.route(web::post().to(translations::create)),
);
cfg.service(
web::resource("/translations/{id}/validate")
.name("translations_validate")
.route(web::post().to(translations::validate)),
);
cfg.service(
web::resource("/translations/{key}")
.name("translations_by_key")
.route(web::get().to(translations::show))
.route(web::delete().to(translations::delete)),
);
cfg.service(
web::resource("/users")
.name("users_create")
.route(web::post().to(users::create)),
);
}
|
// move_semantics2.rs
// Make me compile without changing line 13!
// Execute `rustlings hint move_semantics2` for hints :)
fn main() {
// solution 1: Just clone vec0 before calling fill
/*
let vec0 = Vec::new();
let vec_cloned = vec0.clone();
let mut vec1 = fill_vec(vec_cloned);
println!("{} has length {} content `{:?}`", "vec0", vec0.len(), vec0);
vec1.push(88);
println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1);
*/
// Solution2: Change fill so that it borrows its argument instead of taking ownership of it
// --> fill_vec_borrow
/*
let vec0 = Vec::new();
let mut vec1 = fill_vec_borrow(&vec0);
println!("{} has length {} content `{:?}`", "vec0", vec0.len(), vec0);
vec1.push(88);
println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1);
*/
// Solution3: mutably borrow vec in fill_vec
let mut vec0 = Vec::new();
fill_vec_mutably_borrow(&mut vec0);
// Do not change the following line!
println!("{} has length {} content `{:?}`", "vec0", vec0.len(), vec0);
vec0.push(88);
println!("{} has length {} content `{:?}`", "vec1", vec0.len(), vec0);
}
fn fill_vec(vec: Vec<i32>) -> Vec<i32> {
let mut vec = vec;
vec.push(22);
vec.push(44);
vec.push(66);
vec
}
fn fill_vec_borrow(vec: &Vec<i32>) -> Vec<i32> {
let mut vec = vec.clone();
vec.push(22);
vec.push(44);
vec.push(66);
vec
}
fn fill_vec_mutably_borrow(vec: &mut Vec<i32>) {
vec.push(22);
vec.push(44);
vec.push(66);
} |
//! read & write TLB items
#![allow(deprecated)]
use crate::instructions;
use crate::registers::cp0;
/// refers to one TLB entry
pub struct TLBEntry {
pub entry_lo0: cp0::entry_lo::EntryLo,
pub entry_lo1: cp0::entry_lo::EntryLo,
pub entry_hi: cp0::entry_hi::EntryHi,
pub page_mask: cp0::page_mask::PageMask,
}
#[deprecated(since = "0.2.0", note = "please use implementations in `TLBEntry`")]
pub fn clear_all_tlb() {
let mmu_size = cp0::config::mmu_size();
if mmu_size != 0 {
clear_tlb(0, mmu_size);
} else {
clear_tlb(0, 63);
}
}
#[deprecated(since = "0.2.0", note = "please use implementations in `TLBEntry`")]
pub fn clear_tlb(start: u32, end: u32) {
cp0::entry_lo::write0_u32(0);
cp0::entry_lo::write1_u32(0);
cp0::entry_hi::write_u32(0);
cp0::page_mask::write_u32(0);
for i in start..end + 1 {
cp0::index::write_u32(i);
unsafe { instructions::tlbwi() };
}
}
#[deprecated(since = "0.2.0", note = "please use implementations in `TLBEntry`")]
pub fn read_tlb(index: u32) -> TLBEntry {
cp0::index::write_u32(index);
unsafe { instructions::tlbr() };
TLBEntry {
entry_lo0: cp0::entry_lo::read0(),
entry_lo1: cp0::entry_lo::read1(),
entry_hi: cp0::entry_hi::read(),
page_mask: cp0::page_mask::read(),
}
}
#[deprecated(since = "0.2.0", note = "please use implementations in `TLBEntry`")]
pub fn write_tlb(entry: TLBEntry, index: u32) {
cp0::entry_lo::write0(entry.entry_lo0);
cp0::entry_lo::write1(entry.entry_lo1);
cp0::entry_hi::write(entry.entry_hi);
cp0::page_mask::write(entry.page_mask);
cp0::index::write_u32(index);
unsafe { instructions::tlbwi() };
}
#[deprecated(since = "0.2.0", note = "please use implementations in `TLBEntry`")]
pub fn write_tlb_random(entry: TLBEntry) {
cp0::entry_lo::write0(entry.entry_lo0);
cp0::entry_lo::write1(entry.entry_lo1);
cp0::entry_hi::write(entry.entry_hi);
cp0::page_mask::write(entry.page_mask);
unsafe { instructions::tlbwr() };
}
impl TLBEntry {
pub fn clear(start: u32, end: u32) {
clear_tlb(start, end);
}
pub fn clear_all() {
clear_all_tlb();
}
pub fn read(index: u32) -> TLBEntry {
read_tlb(index)
}
pub fn write(self, index: u32) {
write_tlb(self, index);
}
pub fn write_random(self) {
write_tlb_random(self);
}
}
|
//! Tests auto-converted from "sass-spec/spec/non_conformant/errors/extend/placeholder"
#[allow(unused)]
use super::rsass;
// From "sass-spec/spec/non_conformant/errors/extend/placeholder/missing.hrx"
// Ignoring "missing", error tests are not supported yet.
// From "sass-spec/spec/non_conformant/errors/extend/placeholder/optional.hrx"
#[test]
#[ignore] // wrong result
fn optional() {
assert_eq!(
rsass(
".baz {\r\
\n @extend %foo !optional;\r\
\n color: green;\r\
\n}\r\
\n"
)
.unwrap(),
".baz {\
\n color: green;\
\n}\
\n"
);
}
// From "sass-spec/spec/non_conformant/errors/extend/placeholder/simple.hrx"
#[test]
#[ignore] // wrong result
fn simple() {
assert_eq!(
rsass(
"%foo {color: blue}\r\
\n%bar {color: red}\r\
\n.baz {\r\
\n @extend %foo;\r\
\n color: green;\r\
\n}\r\
\n"
)
.unwrap(),
".baz {\
\n color: blue;\
\n}\
\n.baz {\
\n color: green;\
\n}\
\n"
);
}
|
use std::fmt;
struct Point2 {
x: f64,
y: f64,
}
#[derive(Debug)]
struct Complex {
real: f64,
imag: f64
}
impl fmt::Display for Complex {
fn fmt(&self,f: &mut fmt::Formatter) -> fmt::Result {
write!(f,"{} + {}i",self.real,self.imag)
}
}
fn main(){
let complex = Complex {real: 3.3, imag: 7.2};
println!("Display: {}",complex);
println!("Debug: {:?}",complex);
}
|
use std::os::raw::{c_int, c_char, c_void, c_uint};
use std::ffi::{CString, CStr};
use std::collections::HashMap;
use raw::{aw, vp};
pub mod mapping;
pub enum AttribValue {
Int(c_int),
String(CString),
Float(f32),
Data(Vec<u8>)
}
pub struct AttribBuffer {
pub attribs: HashMap<aw::ATTRIBUTE, AttribValue>
}
impl AttribBuffer {
pub fn new() -> Self {
AttribBuffer {
attribs: HashMap::with_capacity(aw::ATTRIBUTE::MAX_ATTRIBUTE as usize)
}
}
pub fn set<T: Attrib>(&mut self, attribute: aw::ATTRIBUTE, value: T) {
self.attribs.insert(attribute, value.to_attrib());
}
pub fn get<T: Attrib>(&mut self, attribute: aw::ATTRIBUTE) -> Option<T> {
Attrib::from_attrib(self.attribs.entry(attribute).or_insert_with(|| T::default().to_attrib()))
}
}
pub trait Attrib: Sized {
fn to_attrib(self) -> AttribValue;
fn from_attrib(orig: &AttribValue) -> Option<Self>;
fn default() -> Self;
fn into_req<Other: Attrib>(self) -> Option<Other> {
Attrib::from_attrib(&self.to_attrib())
}
}
impl Attrib for c_int {
fn to_attrib(self) -> AttribValue {
AttribValue::Int(self)
}
fn from_attrib(orig: &AttribValue) -> Option<Self> {
match *orig {
AttribValue::Int(val) => Some(val),
_ => None
}
}
fn default() -> Self { 0 }
}
impl Attrib for CString {
fn to_attrib(self) -> AttribValue {
AttribValue::String(self)
}
fn from_attrib(orig: &AttribValue) -> Option<Self> {
match *orig {
AttribValue::String(ref val) => Some(val.clone()),
_ => None
}
}
fn default() -> Self { CString::new("").unwrap() }
}
impl Attrib for *mut c_char {
fn to_attrib(self) -> AttribValue {
unsafe {
AttribValue::String(CStr::from_ptr(self).to_owned())
}
}
fn from_attrib(orig: &AttribValue) -> Option<Self> {
match *orig {
AttribValue::String(ref val) => Some(val.as_ptr() as *mut _),
_ => None
}
}
fn default() -> Self {
CString::new("").expect("Really? It's the empty string!").into_raw()
}
}
impl Attrib for f32 {
fn to_attrib(self) -> AttribValue {
AttribValue::Float(self)
}
fn from_attrib(orig: &AttribValue) -> Option<Self> {
match *orig {
AttribValue::Float(val) => Some(val),
_ => None
}
}
fn default() -> Self { 0.0 }
}
impl Attrib for Vec<u8> {
fn to_attrib(self) -> AttribValue {
AttribValue::Data(self)
}
fn from_attrib(orig: &AttribValue) -> Option<Self> {
match *orig {
AttribValue::Data(ref val) => Some(val.clone()),
_ => None
}
}
fn default() -> Self { Vec::new() }
}
impl Attrib for (*mut c_void, c_uint) {
fn to_attrib(self) -> AttribValue {
if self.0.is_null() {
return AttribValue::Data(Vec::new());
}
let len = self.1 as usize;
let ptr = self.0 as *mut u8;
unsafe {
AttribValue::Data(unsafe {Vec::from_raw_parts(ptr, len, len)})
}
}
fn from_attrib(orig: &AttribValue) -> Option<Self> {
match *orig {
AttribValue::Data(ref val) => Some((val.as_ptr() as *mut _, val.len() as c_uint)),
_ => None
}
}
fn default() -> Self {
(0x1 as *mut c_void, 0)
}
}
|
extern crate turbine;
use turbine::*;
fn main() {
use std::mem::size_of;
let world = size_of::<World>();
// init, prev, current, next.
let physics = 4 * size_of::<[Vec3; world::ENTITY_COUNT]>();
let sum = world + physics;
println!("Memory requirements {} MiB", sum as f64 / 1024.0 / 1024.0);
}
|
use crate::context::Context;
use crate::data::DynSharable;
use comet::api::Collectable;
use comet::api::Finalize;
use comet::api::Trace;
use std::fmt::Debug;
use std::ptr::NonNull;
#[macro_export]
macro_rules! declare_functions {
($($id:ident),* $(,)?) => {
#[derive(Send, Sync, Unpin, Collectable, Finalize, NoTrace)]
pub struct Function<I: 'static, O: 'static> {
pub ptr: fn(I, Context) -> O,
pub tag: FunctionTag<I, O>,
}
#[derive(Debug, Copy, Send, Sync, Unpin, Serialize, Deserialize)]
pub struct FunctionTag<I, O>(pub Tag, pub std::marker::PhantomData<(I, O)>);
#[derive(Debug, Clone, Copy, Send, Serialize, Deserialize)]
#[allow(non_camel_case_types)]
pub enum Tag {
$($id,)*
}
impl<I, O> Clone for Function<I, O> {
fn clone(&self) -> Self {
Self { ptr: self.ptr.clone(), tag: self.tag.clone() }
}
}
impl<I, O> std::fmt::Debug for Function<I, O> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
Ok(())
}
}
impl<I, O> Clone for FunctionTag<I, O> {
fn clone(&self) -> Self {
Self(self.0, std::marker::PhantomData)
}
}
impl<I, O> DynSharable for Function<I, O> {
type T = FunctionTag<I, O>;
fn into_sendable(&self, ctx: Context) -> Self::T {
self.tag.clone()
}
}
impl<I: 'static, O: 'static> DynSendable for FunctionTag<I, O> {
type T = Function<I, O>;
fn into_sharable(&self, ctx: Context) -> Self::T {
unsafe {
match self.0 {
$(Tag::$id => Function {
ptr: std::mem::transmute($id as usize),
tag: self.clone()
}),*
}
}
}
}
impl<I, O> Serialize for Function<I, O> {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
self.tag.0.serialize(serializer)
}
}
impl<'i, I, O> Deserialize<'i> for Function<I, O> {
fn deserialize<D: Deserializer<'i>>(deserializer: D) -> Result<Self, D::Error> {
unsafe {
match Tag::deserialize(deserializer)? {
$(Tag::$id => Ok(Function {
ptr: std::mem::transmute($id as usize),
tag: FunctionTag(Tag::$id, std::marker::PhantomData)
}),)*
}
}
}
}
};
}
#[macro_export]
macro_rules! declare {
(functions:[$($id:ident),* $(,)?], tasks:[]) => {
declare_functions! {
$($id),*
}
};
}
#[macro_export]
macro_rules! function {
// Create a function value
($fun:ident) => {
Function {
ptr: $fun,
tag: FunctionTag(Tag::$fun, std::marker::PhantomData),
}
};
// Create a function type
(($($input:ty),* $(,)?) -> $output:ty) => {
Function<($($input,)*), $output>
};
}
|
use std::{fmt, cmp};
use std::cmp::{PartialOrd, Ord, Ordering};
use std::hash::{Hash, Hasher};
use std::convert::TryFrom;
use pct_str::PctStr;
use crate::parsing;
use super::Error;
#[derive(Clone, Copy)]
pub struct UserInfo<'a> {
/// The path slice.
pub(crate) data: &'a [u8]
}
impl<'a> UserInfo<'a> {
#[inline]
pub fn as_ref(&self) -> &[u8] {
self.data
}
/// Get the underlying userinfo slice as a string slice.
#[inline]
pub fn as_str(&self) -> &str {
unsafe {
std::str::from_utf8_unchecked(&self.data)
}
}
/// Get the underlying userinfo slice as a percent-encoded string slice.
#[inline]
pub fn as_pct_str(&self) -> &PctStr {
unsafe {
PctStr::new_unchecked(self.as_str())
}
}
/// Checks if the userinfo is empty.
#[inline]
pub fn is_empty(&self) -> bool {
self.data.is_empty()
}
}
impl<'a> TryFrom<&'a str> for UserInfo<'a> {
type Error = Error;
#[inline]
fn try_from(str: &'a str) -> Result<UserInfo<'a>, Error> {
let userinfo_len = parsing::parse_userinfo(str.as_ref(), 0)?;
if userinfo_len < str.len() {
Err(Error::InvalidUserInfo)
} else {
Ok(UserInfo {
data: str.as_ref()
})
}
}
}
impl<'a> fmt::Display for UserInfo<'a> {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.as_str().fmt(f)
}
}
impl<'a> fmt::Debug for UserInfo<'a> {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.as_str().fmt(f)
}
}
impl<'a> cmp::PartialEq for UserInfo<'a> {
#[inline]
fn eq(&self, other: &UserInfo) -> bool {
self.as_pct_str() == other.as_pct_str()
}
}
impl<'a> Eq for UserInfo<'a> { }
impl<'a> cmp::PartialEq<&'a str> for UserInfo<'a> {
#[inline]
fn eq(&self, other: &&'a str) -> bool {
self.as_str() == *other
}
}
impl<'a> PartialOrd for UserInfo<'a> {
#[inline]
fn partial_cmp(&self, other: &UserInfo<'a>) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl<'a> Ord for UserInfo<'a> {
#[inline]
fn cmp(&self, other: &UserInfo<'a>) -> Ordering {
self.as_pct_str().cmp(other.as_pct_str())
}
}
impl<'a> Hash for UserInfo<'a> {
#[inline]
fn hash<H: Hasher>(&self, hasher: &mut H) {
self.as_pct_str().hash(hasher)
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.