text stringlengths 8 4.13M |
|---|
use std::io;
use std::mem;
use std::borrow::{Cow, ToOwned};
use std::ops::Range;
use crate::endianness::Endianness;
use crate::writable::Writable;
use crate::writer::Writer;
use crate::context::Context;
use crate::utils::as_bytes;
macro_rules! impl_for_primitive {
($type:ty, $write_name:ident) => {
impl< C: Context > Writable< C > for $type {
#[inline(always)]
fn write_to< 'a, T: ?Sized + Writer< 'a, C > >( &'a self, writer: &mut T ) -> io::Result< () > {
writer.$write_name( *self )
}
#[inline]
fn bytes_needed( &self ) -> usize {
mem::size_of::< Self >()
}
#[doc(hidden)]
#[inline(always)]
fn speedy_is_primitive() -> bool {
true
}
#[doc(hidden)]
#[inline(always)]
unsafe fn speedy_slice_as_bytes( slice: &[Self] ) -> &[u8] where Self: Sized {
as_bytes( slice )
}
}
}
}
impl_for_primitive!( i8, write_i8 );
impl_for_primitive!( i16, write_i16 );
impl_for_primitive!( i32, write_i32 );
impl_for_primitive!( i64, write_i64 );
impl_for_primitive!( u8, write_u8 );
impl_for_primitive!( u16, write_u16 );
impl_for_primitive!( u32, write_u32 );
impl_for_primitive!( u64, write_u64 );
impl_for_primitive!( f32, write_f32 );
impl_for_primitive!( f64, write_f64 );
impl< C: Context > Writable< C > for bool {
#[inline]
fn write_to< 'a, T: ?Sized + Writer< 'a, C > >( &'a self, writer: &mut T ) -> io::Result< () > {
writer.write_u8( if *self { 1 } else { 0 } )
}
#[inline]
fn bytes_needed( &self ) -> usize {
1
}
}
impl< C: Context > Writable< C > for String {
#[inline]
fn write_to< 'a, T: ?Sized + Writer< 'a, C > >( &'a self, writer: &mut T ) -> io::Result< () > {
self.as_bytes().write_to( writer )
}
#[inline]
fn bytes_needed( &self ) -> usize {
Writable::< C >::bytes_needed( self.as_bytes() )
}
}
impl< C: Context > Writable< C > for str {
#[inline]
fn write_to< 'a, T: ?Sized + Writer< 'a, C > >( &'a self, writer: &mut T ) -> io::Result< () > {
self.as_bytes().write_to( writer )
}
#[inline]
fn bytes_needed( &self ) -> usize {
Writable::< C >::bytes_needed( self.as_bytes() )
}
}
impl< 'r, C: Context > Writable< C > for Cow< 'r, str > {
#[inline]
fn write_to< 'a, T: ?Sized + Writer< 'a, C > >( &'a self, writer: &mut T ) -> io::Result< () > {
self.as_bytes().write_to( writer )
}
#[inline]
fn bytes_needed( &self ) -> usize {
Writable::< C >::bytes_needed( self.as_bytes() )
}
}
impl< C: Context, T: Writable< C > > Writable< C > for [T] {
#[inline]
fn write_to< 'a, W: ?Sized + Writer< 'a, C > >( &'a self, writer: &mut W ) -> io::Result< () > {
writer.write_u32( self.len() as _ )?;
if T::speedy_is_primitive() && (mem::size_of::< T >() == 1 || !writer.endianness().conversion_necessary()) {
let bytes = unsafe { T::speedy_slice_as_bytes( self ) };
writer.write_bytes( bytes )
} else {
for value in self {
writer.write_value( value )?;
}
Ok(())
}
}
#[inline]
fn bytes_needed( &self ) -> usize {
if T::speedy_is_primitive() {
return 4 + self.len() * mem::size_of::< T >();
}
let mut sum = 4;
for element in self {
sum += element.bytes_needed();
}
sum
}
}
impl< 'r, C: Context, T: Writable< C > > Writable< C > for Cow< 'r, [T] > where [T]: ToOwned {
#[inline]
fn write_to< 'a, W: ?Sized + Writer< 'a, C > >( &'a self, writer: &mut W ) -> io::Result< () > {
self.as_ref().write_to( writer )
}
#[inline]
fn bytes_needed( &self ) -> usize {
Writable::< C >::bytes_needed( self.as_ref() )
}
}
impl< C: Context, T: Writable< C > > Writable< C > for Vec< T > {
#[inline]
fn write_to< 'a, W: ?Sized + Writer< 'a, C > >( &'a self, writer: &mut W ) -> io::Result< () > {
self.as_slice().write_to( writer )
}
#[inline]
fn bytes_needed( &self ) -> usize {
Writable::< C >::bytes_needed( self.as_slice() )
}
}
impl< C: Context, T: Writable< C > > Writable< C > for Range< T > {
#[inline]
fn write_to< 'a, W: ?Sized + Writer< 'a, C > >( &'a self, writer: &mut W ) -> io::Result< () > {
self.start.write_to( writer )?;
self.end.write_to( writer )
}
#[inline]
fn bytes_needed( &self ) -> usize {
Writable::< C >::bytes_needed( &self.start ) + Writable::< C >::bytes_needed( &self.end )
}
}
impl< C: Context, T: Writable< C > > Writable< C > for Option< T > {
#[inline]
fn write_to< 'a, W: ?Sized + Writer< 'a, C > >( &'a self, writer: &mut W ) -> io::Result< () > {
if let Some( ref value ) = *self {
writer.write_u8( 1 )?;
value.write_to( writer )
} else {
writer.write_u8( 0 )
}
}
#[inline]
fn bytes_needed( &self ) -> usize {
if let Some( ref value ) = *self {
1 + Writable::< C >::bytes_needed( value )
} else {
1
}
}
}
impl< C: Context > Writable< C > for () {
#[inline]
fn write_to< 'a, W: ?Sized + Writer< 'a, C > >( &'a self, _: &mut W ) -> io::Result< () > {
Ok(())
}
#[inline]
fn bytes_needed( &self ) -> usize {
0
}
}
macro_rules! impl_for_tuple {
($($name:ident),+) => {
impl< C: Context, $($name: Writable< C >),+ > Writable< C > for ($($name,)+) {
#[inline]
fn write_to< 'a, W: ?Sized + Writer< 'a, C > >( &'a self, writer: &mut W ) -> io::Result< () > {
#[allow(non_snake_case)]
let &($(ref $name,)+) = self;
$(
$name.write_to( writer )?;
)+
Ok(())
}
#[inline]
fn bytes_needed( &self ) -> usize {
#[allow(non_snake_case)]
let &($(ref $name,)+) = self;
let mut size = 0;
$(
size += Writable::< C >::bytes_needed( $name );
)+
size
}
}
}
}
impl_for_tuple!( A0 );
impl_for_tuple!( A0, A1 );
impl_for_tuple!( A0, A1, A2 );
impl_for_tuple!( A0, A1, A2, A3 );
impl_for_tuple!( A0, A1, A2, A3, A4 );
impl_for_tuple!( A0, A1, A2, A3, A4, A5 );
impl_for_tuple!( A0, A1, A2, A3, A4, A5, A6 );
impl_for_tuple!( A0, A1, A2, A3, A4, A5, A6, A7 );
impl_for_tuple!( A0, A1, A2, A3, A4, A5, A6, A7, A8 );
impl_for_tuple!( A0, A1, A2, A3, A4, A5, A6, A7, A8, A9 );
impl_for_tuple!( A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10 );
impl< C: Context > Writable< C > for Endianness {
#[inline]
fn write_to< 'a, T: ?Sized + Writer< 'a, C > >( &'a self, writer: &mut T ) -> io::Result< () > {
let value = match *self {
Endianness::LittleEndian => 0,
Endianness::BigEndian => 1
};
writer.write_u8( value )
}
#[inline]
fn bytes_needed( &self ) -> usize {
1
}
}
|
extern crate clap;
use git2::{Repository,Error,SubmoduleUpdateOptions};
use clap::{Arg, App};
use std;
use std::io;
fn get_path(submodule : &str ,path : Option<&str>) -> io::Result<std::path::PathBuf>{
match path{
None =>{
let mut path = std::env::current_dir().unwrap();
// create path:
let result = submodule.split("/").last().unwrap().replace(".git","");
path.push(result);
Ok(path)
},
path=>{
let mut submodule_path = std::path::PathBuf::new();
submodule_path.push(std::env::current_dir().unwrap());
submodule_path.push(path.unwrap());
Ok(submodule_path)
}
}
}
fn can_add_submodule(repo :&Repository,submodule : &str) -> bool{
let list_of = repo.submodules().unwrap();
match list_of.into_iter().find(|entry|{
if entry.url().is_some(){
entry.url().unwrap() == submodule
}else{
false
}
}){
Some(_) => false,
None => true
}
}
fn add(repo : &Repository,submodule_url : &str,path : Option<&str>){
if can_add_submodule(repo,submodule_url){
let submodule_path = get_path(submodule_url,path);
match repo.submodule(submodule_url,submodule_path.unwrap().as_path(),true){
Err(e)=> println!("Error: could not add submodule because {}",e.message()),
Ok(mut module) =>{
std::fs::remove_dir_all(module.path()).unwrap();
println!("Cloning submodule ...");
Repository::clone(& module.url().unwrap(), module.path()).unwrap();
module.add_to_index(true).unwrap();
module.add_finalize().unwrap();
println!("Added {} to repositry to location {}",submodule_url,module.path().display());
}
}
}else{
println!("Repositry: {} is already added as submodule",submodule_url);
}
}
fn init_submodules(repo : &Repository,submodule_name : &str){
let mut submodule_options = SubmoduleUpdateOptions::new();
let init = true;
let opts = Some(&mut submodule_options);
println!("Initlize {} submodules of repository {}",submodule_name,repo.path().display());
if submodule_name == "all"{
for mut submodule in repo.submodules().unwrap(){
println!("Begin Initilize: {} submodule...",submodule_name);
submodule.update(init, Some(&mut submodule_options)).unwrap();
let submdoule_repo = submodule.open().unwrap();
init_submodules(&submdoule_repo,"all");
println!("Done with initlizing {} submodule...",submodule_name);
}
}else{
if let Some(mut submodule) = repo.submodules().unwrap().into_iter().find(|entry| entry.name().unwrap() == submodule_name){
println!("Begin Initilize: {} submodule...",submodule_name);
submodule.update(init, opts).unwrap();
let submdoule_repo = submodule.open().unwrap();
init_submodules(&submdoule_repo,"all");
println!("Done with initlizing {} submodule...",submodule_name);
}
}
println!("Done with initlizing {} submodules of repository {}",submodule_name,repo.path().display());
}
fn update(repo : &Repository,submodule_name : &str){
let list_of = repo.submodules().unwrap();
if let Some(submodule) = list_of.into_iter().find(|entry| entry.name().unwrap() == submodule_name){
let url = submodule.url().unwrap();
remove(&repo,&submodule_name);
add(&repo,url,Some(&submodule_name));
println!("Submodule was updated!");
}else{
println!("Cannot update submodule because it does not exists!");
}
}
fn remove_from_config(file : &str,submodule_name : &str){
let mut config = git2::Config::open(std::path::Path::new(file)).unwrap();
let values: Vec<String> = config
.entries(None)
.unwrap()
.into_iter()
.map(|entry|entry.unwrap().name().unwrap().into())
.collect();
for entry in values{
let mut find_str = String::from("submodule.");
find_str += submodule_name;
if entry.contains(&find_str){
if config.remove(&entry).is_err(){
println!("Cannot find {} entry in {}",entry,file);
}
}
}
}
fn remove(repo : &Repository,submodule_name : &str){
let list_of = repo.submodules().unwrap();
match list_of.into_iter().find(|entry| entry.name().unwrap() == submodule_name){
Some(submodule) => {
{ // remove from .gitmodules
remove_from_config(".gitmodules",submodule.name().unwrap());
}
{ // remove from config
remove_from_config(".git/config",submodule.name().unwrap());
}
{ // remove from index
let mut index = repo.index().unwrap();
index.remove_dir(submodule.path(),0).unwrap();
index.write().unwrap();
index.write_tree().unwrap();
}
{ // remove from modules folder
let path = std::path::Path::new(".git/modules/").join(submodule.path());
if std::fs::remove_dir_all(&path).is_err(){
println!("Error: could not remove {:?}", path.display());
}
}
{// remove local files:
let current_dir = std::env::current_dir().unwrap();
let path = current_dir.join(submodule.path());
if std::fs::remove_dir_all(&path).is_err(){
println!("Error: could not remove {:?}", path.display());
}
}
println!("Submodule was removed!");
}
None => {}
}
}
fn list(repo : &Repository){
let list_of = repo.submodules().unwrap();
println!("We found {} submodules.",list_of.len());
let mut count = 0;
for module in &list_of {
count += 1;
if module.url().is_some() {
println!("#{}\nname: {}\nurl: {}\npath: {:?}\n",count,module.name().unwrap(),module.url().unwrap(),module.path().to_str());
}else{
println!("#{}\nname: {} is invalid",count,module.name().unwrap());
}
}
}
fn init() -> Result<Repository,Error>{
let path = std::env::current_dir().unwrap();
println!("{:?}",path);
Repository::discover(path.to_str().unwrap())
}
fn main() {
if let Ok(repo) = init() {
let matches = App::new("gsm")
.version("0.1")
.author("Simon Renger <simon.renger@gmail.com>")
.about("git submodules easily managed")
.arg(Arg::with_name("add")
.short('a')
.long("add")
.value_name("submdoule")
.help("Adds a submodule")
.takes_value(true))
.arg(Arg::with_name("name")
.short('n')
.long("name")
.help("names a submodule")
.requires("add")
.takes_value(true))
.arg(Arg::with_name("remove")
.short('r')
.long("remove")
.value_name("submdoule")
.help("removes a submodule")
.takes_value(true))
.arg(Arg::with_name("update")
.short('u')
.long("update")
.value_name("submdoule")
.help("updates submodule to latests")
.takes_value(true))
.arg(Arg::with_name("init")
.short('i')
.long("init")
.value_name("submdoule")
.help("init submodule or all if all is given")
.takes_value(true))
.arg(Arg::with_name("list")
.short('l')
.long("list")
.help("list submodule"))
.get_matches();
if matches.is_present("add"){
add(&repo,matches.value_of("add").unwrap(),matches.value_of("name"));
}else if matches.is_present("list"){
list(&repo);
}else if matches.is_present("remove"){
remove(&repo,matches.value_of("remove").unwrap());
}else if matches.is_present("update"){
update(&repo,matches.value_of("update").unwrap());
}else if matches.is_present("init"){
init_submodules(&repo,matches.value_of("init").unwrap());
}
}else{
println!("Could not find a git reposity");
}
} |
#[cfg(test)]
mod stream_test;
use crate::association::AssociationState;
use crate::chunk::chunk_payload_data::{ChunkPayloadData, PayloadProtocolIdentifier};
use crate::error::Error;
use crate::queue::reassembly_queue::ReassemblyQueue;
use crate::queue::pending_queue::PendingQueue;
use bytes::Bytes;
use std::fmt;
use std::sync::atomic::{AtomicBool, AtomicU16, AtomicU32, AtomicU8, AtomicUsize, Ordering};
use std::sync::Arc;
use tokio::sync::{mpsc, Mutex, Notify};
#[derive(Debug, Copy, Clone, PartialEq)]
#[repr(C)]
pub enum ReliabilityType {
/// ReliabilityTypeReliable is used for reliable transmission
Reliable = 0,
/// ReliabilityTypeRexmit is used for partial reliability by retransmission count
Rexmit = 1,
/// ReliabilityTypeTimed is used for partial reliability by retransmission duration
Timed = 2,
}
impl Default for ReliabilityType {
fn default() -> Self {
ReliabilityType::Reliable
}
}
impl fmt::Display for ReliabilityType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let s = match *self {
ReliabilityType::Reliable => "Reliable",
ReliabilityType::Rexmit => "Rexmit",
ReliabilityType::Timed => "Timed",
};
write!(f, "{}", s)
}
}
impl From<u8> for ReliabilityType {
fn from(v: u8) -> ReliabilityType {
match v {
1 => ReliabilityType::Rexmit,
2 => ReliabilityType::Timed,
_ => ReliabilityType::Reliable,
}
}
}
pub type OnBufferedAmountLowFn = Box<dyn Fn() + Send + Sync>;
// TODO: benchmark performance between multiple Atomic+Mutex vs one Mutex<StreamInternal>
/// Stream represents an SCTP stream
#[derive(Default)]
pub struct Stream {
pub(crate) max_payload_size: u32,
pub(crate) max_message_size: Arc<AtomicU32>, // clone from association
pub(crate) state: Arc<AtomicU8>, // clone from association
pub(crate) awake_write_loop_ch: Option<Arc<mpsc::Sender<()>>>,
pub(crate) pending_queue: Arc<PendingQueue>,
pub(crate) stream_identifier: u16,
pub(crate) default_payload_type: AtomicU32, //PayloadProtocolIdentifier,
pub(crate) reassembly_queue: Mutex<ReassemblyQueue>,
pub(crate) sequence_number: AtomicU16,
pub(crate) read_notifier: Notify,
pub(crate) closed: AtomicBool,
pub(crate) unordered: AtomicBool,
pub(crate) reliability_type: AtomicU8, //ReliabilityType,
pub(crate) reliability_value: AtomicU32,
pub(crate) buffered_amount: AtomicUsize,
pub(crate) buffered_amount_low: AtomicUsize,
pub(crate) on_buffered_amount_low: Mutex<Option<OnBufferedAmountLowFn>>,
pub(crate) name: String,
}
impl fmt::Debug for Stream {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Stream")
.field("max_payload_size", &self.max_payload_size)
.field("max_message_size", &self.max_message_size)
.field("state", &self.state)
.field("awake_write_loop_ch", &self.awake_write_loop_ch)
.field("stream_identifier", &self.stream_identifier)
.field("default_payload_type", &self.default_payload_type)
.field("reassembly_queue", &self.reassembly_queue)
.field("sequence_number", &self.sequence_number)
.field("closed", &self.closed)
.field("unordered", &self.unordered)
.field("reliability_type", &self.reliability_type)
.field("reliability_value", &self.reliability_value)
.field("buffered_amount", &self.buffered_amount)
.field("buffered_amount_low", &self.buffered_amount_low)
.field("name", &self.name)
.finish()
}
}
impl Stream {
pub(crate) fn new(
name: String,
stream_identifier: u16,
max_payload_size: u32,
max_message_size: Arc<AtomicU32>,
state: Arc<AtomicU8>,
awake_write_loop_ch: Option<Arc<mpsc::Sender<()>>>,
pending_queue: Arc<PendingQueue>,
) -> Self {
Stream {
max_payload_size,
max_message_size,
state,
awake_write_loop_ch,
pending_queue,
stream_identifier,
default_payload_type: AtomicU32::new(0), //PayloadProtocolIdentifier::Unknown,
reassembly_queue: Mutex::new(ReassemblyQueue::new(stream_identifier)),
sequence_number: AtomicU16::new(0),
read_notifier: Notify::new(),
closed: AtomicBool::new(false),
unordered: AtomicBool::new(false),
reliability_type: AtomicU8::new(0), //ReliabilityType::Reliable,
reliability_value: AtomicU32::new(0),
buffered_amount: AtomicUsize::new(0),
buffered_amount_low: AtomicUsize::new(0),
on_buffered_amount_low: Mutex::new(None),
name,
}
}
/// stream_identifier returns the Stream identifier associated to the stream.
pub fn stream_identifier(&self) -> u16 {
self.stream_identifier
}
/// set_default_payload_type sets the default payload type used by write.
pub fn set_default_payload_type(&self, default_payload_type: PayloadProtocolIdentifier) {
self.default_payload_type
.store(default_payload_type as u32, Ordering::SeqCst);
}
/// set_reliability_params sets reliability parameters for this stream.
pub fn set_reliability_params(&self, unordered: bool, rel_type: ReliabilityType, rel_val: u32) {
log::debug!(
"[{}] reliability params: ordered={} type={} value={}",
self.name,
!unordered,
rel_type,
rel_val
);
self.unordered.store(unordered, Ordering::SeqCst);
self.reliability_type
.store(rel_type as u8, Ordering::SeqCst);
self.reliability_value.store(rel_val, Ordering::SeqCst);
}
/// read reads a packet of len(p) bytes, dropping the Payload Protocol Identifier.
/// Returns EOF when the stream is reset or an error if the stream is closed
/// otherwise.
pub async fn read(&self, p: &mut [u8]) -> Result<usize, Error> {
let (n, _) = self.read_sctp(p).await?;
Ok(n)
}
/// read_sctp reads a packet of len(p) bytes and returns the associated Payload
/// Protocol Identifier.
/// Returns EOF when the stream is reset or an error if the stream is closed
/// otherwise.
pub async fn read_sctp(
&self,
p: &mut [u8],
) -> Result<(usize, PayloadProtocolIdentifier), Error> {
while !self.closed.load(Ordering::SeqCst) {
let result = {
let mut reassembly_queue = self.reassembly_queue.lock().await;
reassembly_queue.read(p)
};
if result.is_ok() {
return result;
} else if let Err(err) = result {
if err == Error::ErrShortBuffer {
return Err(err);
}
}
self.read_notifier.notified().await;
}
Err(Error::ErrStreamClosed)
}
pub(crate) async fn handle_data(&self, pd: ChunkPayloadData) {
let readable = {
let mut reassembly_queue = self.reassembly_queue.lock().await;
if reassembly_queue.push(pd) {
let readable = reassembly_queue.is_readable();
log::debug!("[{}] reassemblyQueue readable={}", self.name, readable);
readable
} else {
false
}
};
if readable {
log::debug!("[{}] readNotifier.signal()", self.name);
self.read_notifier.notify_one();
log::debug!("[{}] readNotifier.signal() done", self.name);
}
}
pub(crate) async fn handle_forward_tsn_for_ordered(&self, ssn: u16) {
if self.unordered.load(Ordering::SeqCst) {
return; // unordered chunks are handled by handleForwardUnordered method
}
// Remove all chunks older than or equal to the new TSN from
// the reassembly_queue.
let readable = {
let mut reassembly_queue = self.reassembly_queue.lock().await;
reassembly_queue.forward_tsn_for_ordered(ssn);
reassembly_queue.is_readable()
};
// Notify the reader asynchronously if there's a data chunk to read.
if readable {
self.read_notifier.notify_one();
}
}
pub(crate) async fn handle_forward_tsn_for_unordered(&self, new_cumulative_tsn: u32) {
if !self.unordered.load(Ordering::SeqCst) {
return; // ordered chunks are handled by handleForwardTSNOrdered method
}
// Remove all chunks older than or equal to the new TSN from
// the reassembly_queue.
let readable = {
let mut reassembly_queue = self.reassembly_queue.lock().await;
reassembly_queue.forward_tsn_for_unordered(new_cumulative_tsn);
reassembly_queue.is_readable()
};
// Notify the reader asynchronously if there's a data chunk to read.
if readable {
self.read_notifier.notify_one();
}
}
/// write writes len(p) bytes from p with the default Payload Protocol Identifier
pub async fn write(&self, p: &Bytes) -> Result<usize, Error> {
self.write_sctp(p, self.default_payload_type.load(Ordering::SeqCst).into())
.await
}
/// write_sctp writes len(p) bytes from p to the DTLS connection
pub async fn write_sctp(
&self,
p: &Bytes,
ppi: PayloadProtocolIdentifier,
) -> Result<usize, Error> {
if p.len() > self.max_message_size.load(Ordering::SeqCst) as usize {
return Err(Error::ErrOutboundPacketTooLarge);
}
let state: AssociationState = self.state.load(Ordering::SeqCst).into();
match state {
AssociationState::ShutdownSent
| AssociationState::ShutdownAckSent
| AssociationState::ShutdownPending
| AssociationState::ShutdownReceived => return Err(Error::ErrStreamClosed),
_ => {}
};
let chunks = self.packetize(p, ppi);
self.send_payload_data(chunks).await?;
Ok(p.len())
}
fn packetize(&self, raw: &Bytes, ppi: PayloadProtocolIdentifier) -> Vec<ChunkPayloadData> {
let mut i = 0;
let mut remaining = raw.len();
// From draft-ietf-rtcweb-data-protocol-09, section 6:
// All Data Channel Establishment Protocol messages MUST be sent using
// ordered delivery and reliable transmission.
let unordered =
ppi != PayloadProtocolIdentifier::Dcep && self.unordered.load(Ordering::SeqCst);
let mut chunks = vec![];
let head_abandoned = Arc::new(AtomicBool::new(false));
let head_all_inflight = Arc::new(AtomicBool::new(false));
while remaining != 0 {
let fragment_size = std::cmp::min(self.max_payload_size as usize, remaining); //self.association.max_payload_size
// Copy the userdata since we'll have to store it until acked
// and the caller may re-use the buffer in the mean time
let user_data = raw.slice(i..i + fragment_size);
let chunk = ChunkPayloadData {
stream_identifier: self.stream_identifier,
user_data,
unordered,
beginning_fragment: i == 0,
ending_fragment: remaining - fragment_size == 0,
immediate_sack: false,
payload_type: ppi,
stream_sequence_number: self.sequence_number.load(Ordering::SeqCst),
abandoned: head_abandoned.clone(), // all fragmented chunks use the same abandoned
all_inflight: head_all_inflight.clone(), // all fragmented chunks use the same all_inflight
..Default::default()
};
chunks.push(chunk);
remaining -= fragment_size;
i += fragment_size;
}
// RFC 4960 Sec 6.6
// Note: When transmitting ordered and unordered data, an endpoint does
// not increment its Stream Sequence Number when transmitting a DATA
// chunk with U flag set to 1.
if !unordered {
self.sequence_number.fetch_add(1, Ordering::SeqCst);
}
let old_value = self.buffered_amount.fetch_add(raw.len(), Ordering::SeqCst);
log::trace!("[{}] bufferedAmount = {}", self.name, old_value + raw.len());
chunks
}
/// Close closes the write-direction of the stream.
/// Future calls to write are not permitted after calling Close.
pub async fn close(&self) -> Result<(), Error> {
if !self.closed.load(Ordering::SeqCst) {
// Reset the outgoing stream
// https://tools.ietf.org/html/rfc6525
self.send_reset_request(self.stream_identifier).await?;
}
self.closed.store(true, Ordering::SeqCst);
self.read_notifier.notify_waiters(); // broadcast regardless
Ok(())
}
/// buffered_amount returns the number of bytes of data currently queued to be sent over this stream.
pub fn buffered_amount(&self) -> usize {
self.buffered_amount.load(Ordering::SeqCst)
}
/// buffered_amount_low_threshold returns the number of bytes of buffered outgoing data that is
/// considered "low." Defaults to 0.
pub fn buffered_amount_low_threshold(&self) -> usize {
self.buffered_amount_low.load(Ordering::SeqCst)
}
/// set_buffered_amount_low_threshold is used to update the threshold.
/// See buffered_amount_low_threshold().
pub fn set_buffered_amount_low_threshold(&self, th: usize) {
self.buffered_amount_low.store(th, Ordering::SeqCst);
}
/// on_buffered_amount_low sets the callback handler which would be called when the number of
/// bytes of outgoing data buffered is lower than the threshold.
pub async fn on_buffered_amount_low(&self, f: OnBufferedAmountLowFn) {
let mut on_buffered_amount_low = self.on_buffered_amount_low.lock().await;
*on_buffered_amount_low = Some(f);
}
/// This method is called by association's read_loop (go-)routine to notify this stream
/// of the specified amount of outgoing data has been delivered to the peer.
pub(crate) async fn on_buffer_released(&self, n_bytes_released: i64) {
if n_bytes_released <= 0 {
return;
}
let from_amount = self.buffered_amount.load(Ordering::SeqCst);
let new_amount = if from_amount < n_bytes_released as usize {
self.buffered_amount.store(0, Ordering::SeqCst);
log::error!(
"[{}] released buffer size {} should be <= {}",
self.name,
n_bytes_released,
0,
);
0
} else {
self.buffered_amount
.fetch_sub(n_bytes_released as usize, Ordering::SeqCst);
from_amount - n_bytes_released as usize
};
log::trace!("[{}] bufferedAmount = {}", self.name, new_amount);
let on_buffered_amount_low = self.on_buffered_amount_low.lock().await;
if let Some(f) = &*on_buffered_amount_low {
let buffered_amount_low = self.buffered_amount_low.load(Ordering::SeqCst);
if from_amount > buffered_amount_low && new_amount <= buffered_amount_low {
f();
}
}
}
pub(crate) async fn get_num_bytes_in_reassembly_queue(&self) -> usize {
// No lock is required as it reads the size with atomic load function.
let reassembly_queue = self.reassembly_queue.lock().await;
reassembly_queue.get_num_bytes()
}
/// get_state atomically returns the state of the Association.
fn get_state(&self) -> AssociationState {
self.state.load(Ordering::SeqCst).into()
}
fn awake_write_loop(&self) {
//log::debug!("[{}] awake_write_loop_ch.notify_one", self.name);
if let Some(awake_write_loop_ch) = &self.awake_write_loop_ch {
let _ = awake_write_loop_ch.try_send(());
}
}
async fn send_payload_data(&self, chunks: Vec<ChunkPayloadData>) -> Result<(), Error> {
let state = self.get_state();
if state != AssociationState::Established {
return Err(Error::ErrPayloadDataStateNotExist);
}
// Push the chunks into the pending queue first.
for c in chunks {
self.pending_queue.push(c).await;
}
self.awake_write_loop();
Ok(())
}
async fn send_reset_request(&self, stream_identifier: u16) -> Result<(), Error> {
let state = self.get_state();
if state != AssociationState::Established {
return Err(Error::ErrResetPacketInStateNotExist);
}
// Create DATA chunk which only contains valid stream identifier with
// nil userData and use it as a EOS from the stream.
let c = ChunkPayloadData {
stream_identifier,
beginning_fragment: true,
ending_fragment: true,
user_data: Bytes::new(),
..Default::default()
};
self.pending_queue.push(c).await;
self.awake_write_loop();
Ok(())
}
}
|
use std::iter::Iterator;
use std::ops::{Div, Sub};
/// An iterator that returns successive iterations of the Newton's method.
///
/// This iterator is generic over it's entry, and allows to freely use the Newton method on
/// arbitrary types.
///
/// # Example
///
/// ```
/// use generic_newton::Newton;
///
/// fn main() {
/// let mut n = Newton::<f64,_,_>::new(
/// 0.5, // Initial guess
/// |x| x.cos() - x.powi(3), // The actual function
/// |x| -(x.sin() + 3. * x.powi(2)), // Its derivative
/// );
///
/// assert!((n.nth(1000).unwrap() - 0.865474033102).abs() < 1E-11)
/// }
/// ```
pub struct Newton<T, F, DF>
where
T: Div<Output = T> + Sub<Output = T> + Copy,
F: Fn(T) -> T,
DF: Fn(T) -> T,
{
current: T,
func: F,
derivative: DF,
}
impl<T, F, DF> Newton<T, F, DF>
where
T: Div<Output = T> + Sub<Output = T> + Copy,
F: Fn(T) -> T,
DF: Fn(T) -> T,
{
/// Creates a new `Newton` iterator.
///
/// - `func` is the actual function to find the root of
/// - `derivative` is it's derivative.
pub fn new(initial_guess: T, func: F, derivative: DF) -> Self {
Newton {
current: initial_guess,
func,
derivative,
}
}
}
impl<T, F, DF> Iterator for Newton<T, F, DF>
where
T: Div<Output = T> + Sub<Output = T> + Copy,
F: Fn(T) -> T,
DF: Fn(T) -> T,
{
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
let func = &self.func;
let deriv = &self.derivative;
let next = self.current - (func(self.current) / deriv(self.current));
self.current = next;
Some(next)
}
}
#[cfg(test)]
mod tests {
use super::Newton;
#[test]
fn is_generic() {
let mut n = Newton::new(0, |x| x - 1, |_| 1);
assert_eq!(n.nth(5).unwrap(), 1);
let mut n = Newton::new(0., |x| x - 1., |_| 1.);
assert_eq!(n.nth(5).unwrap(), 1.);
let value = 1.0;
let mut n = Newton::new(0., |x| x - value, |_| 1.);
assert_eq!(n.nth(5).unwrap(), 1.);
}
}
|
use libc::c_void;
use util::ConstDefault;
use arch::{IrqHandler, __STACK_START};
pub type VectorTable<I> = arm::VectorTable<ExceptionVectors, I>;
extern fn cortex_m0_isr() {
unsafe {
asm!("
.thumb_func
.global __default_isr_handler
__default_isr_handler:
bkpt
b .
"::::"volatile");
}
}
#[repr(C)]
pub struct ExceptionVectors {
pub initial_sp: *const c_void,
pub reset: IrqHandler,
pub nmi: IrqHandler,
pub hard_fault: IrqHandler,
pub reserved_4: [IrqHandler; 7],
pub svcall: IrqHandler,
pub reserved_12: [IrqHandler; 2],
pub pendsv: IrqHandler,
pub systick: IrqHandler,
}
impl ConstDefault for ExceptionVectors {
const DEFAULT: ExceptionVectors = ExceptionVectors {
initial_sp: &__STACK_START,
reset: IrqHandler::DEFAULT,
nmi: IrqHandler::DEFAULT,
hard_fault: IrqHandler::DEFAULT,
reserved_4: [IrqHandler::DEFAULT; 7],
svcall: IrqHandler::DEFAULT,
reserved_12: [IrqHandler::DEFAULT; 2],
pendsv: IrqHandler::DEFAULT,
systick: IrqHandler::DEFAULT,
};
}
|
use crate::raw_key::RawKey;
use crate::signers::{Error, Signer};
use hmac::crypto_mac::Mac;
use hmac::Hmac as BaseHmac;
use sha3::Sha3_256;
use std::convert::TryInto;
type Conjuncted = BaseHmac<Sha3_256>;
pub struct Hmac {
pub hmac: Conjuncted,
}
impl Signer for Hmac {
fn make(key: &[u8]) -> Self {
Hmac {
hmac: Conjuncted::new_varkey(key).unwrap(),
}
}
fn sign(&self, buffer: &[u8]) -> [u8; 32] {
let mut hmac = self.hmac.clone();
hmac.input(buffer);
hmac.result().code().as_slice().try_into().unwrap()
}
fn verify(&self, buffer: &[u8], mac: &[u8]) -> Result<(), Error> {
let mut hmac = self.hmac.clone();
hmac.input(buffer);
Ok(hmac.verify(mac).map_err(|_| Error::InvalidSignature)?)
}
}
impl<'a> From<&'a RawKey> for Hmac {
fn from(raw_key: &'a RawKey) -> Self {
Hmac::make(&raw_key.key.mac)
}
}
#[cfg(test)]
mod tests {
use crate::hashers::sha3_512::Sha3_512;
use crate::hashers::Hasher;
use crate::iv::Iv;
use crate::raw_key::RawKey;
use crate::signers::hmac::Hmac;
use crate::signers::Signer;
use hex_literal::hex;
#[test]
fn is_signing_correctly() {
let iv = Iv {
iv: hex!("746f74616c6c7972616e646f6d766563"),
};
let key = Sha3_512::make("testkey");
let raw_key = RawKey::make(key, iv);
let msg = String::from("123");
let sign = Hmac::from(&raw_key);
let result = sign.sign(msg.as_bytes());
assert_eq!(
result,
hex!("4606943e0582b639e375a78628358d12783e45c74635a8fd3d26812633b34d14")
);
}
}
|
use nu_path::canonicalize_with;
use nu_protocol::{
ast::{
Argument, Block, Call, Expr, Expression, ImportPattern, ImportPatternHead,
ImportPatternMember, Pipeline,
},
engine::{StateWorkingSet, DEFAULT_OVERLAY_NAME},
span, BlockId, Exportable, Module, PositionalArg, Span, Spanned, SyntaxShape, Type,
};
use std::collections::HashSet;
use std::path::{Path, PathBuf};
static LIB_DIRS_ENV: &str = "NU_LIB_DIRS";
#[cfg(feature = "plugin")]
static PLUGIN_DIRS_ENV: &str = "NU_PLUGIN_DIRS";
use crate::{
known_external::KnownExternal,
lex, lite_parse,
lite_parse::LiteCommand,
parser::{
check_call, check_name, garbage, garbage_pipeline, parse, parse_block_expression,
parse_internal_call, parse_multispan_value, parse_signature, parse_string,
parse_var_with_opt_type, trim_quotes, ParsedInternalCall,
},
unescape_unquote_string, ParseError,
};
pub fn parse_def_predecl(
working_set: &mut StateWorkingSet,
spans: &[Span],
expand_aliases_denylist: &[usize],
) -> Option<ParseError> {
let name = working_set.get_span_contents(spans[0]);
// handle "export def" same as "def"
let (name, spans) = if name == b"export" && spans.len() >= 2 {
(working_set.get_span_contents(spans[1]), &spans[1..])
} else {
(name, spans)
};
if (name == b"def" || name == b"def-env") && spans.len() >= 4 {
let (name_expr, ..) = parse_string(working_set, spans[1], expand_aliases_denylist);
let name = name_expr.as_string();
working_set.enter_scope();
// FIXME: because parse_signature will update the scope with the variables it sees
// we end up parsing the signature twice per def. The first time is during the predecl
// so that we can see the types that are part of the signature, which we need for parsing.
// The second time is when we actually parse the body itworking_set.
// We can't reuse the first time because the variables that are created during parse_signature
// are lost when we exit the scope below.
let (sig, ..) = parse_signature(working_set, spans[2], expand_aliases_denylist);
let signature = sig.as_signature();
working_set.exit_scope();
if let (Some(name), Some(mut signature)) = (name, signature) {
signature.name = name;
let decl = signature.predeclare();
if working_set.add_predecl(decl).is_some() {
return Some(ParseError::DuplicateCommandDef(spans[1]));
}
}
} else if name == b"extern" && spans.len() == 3 {
let (name_expr, ..) = parse_string(working_set, spans[1], expand_aliases_denylist);
let name = name_expr.as_string();
working_set.enter_scope();
// FIXME: because parse_signature will update the scope with the variables it sees
// we end up parsing the signature twice per def. The first time is during the predecl
// so that we can see the types that are part of the signature, which we need for parsing.
// The second time is when we actually parse the body itworking_set.
// We can't reuse the first time because the variables that are created during parse_signature
// are lost when we exit the scope below.
let (sig, ..) = parse_signature(working_set, spans[2], expand_aliases_denylist);
let signature = sig.as_signature();
working_set.exit_scope();
if let (Some(name), Some(mut signature)) = (name, signature) {
signature.name = name.clone();
//let decl = signature.predeclare();
let decl = KnownExternal {
name,
usage: "run external command".into(),
signature,
};
if working_set.add_predecl(Box::new(decl)).is_some() {
return Some(ParseError::DuplicateCommandDef(spans[1]));
}
}
}
None
}
pub fn parse_for(
working_set: &mut StateWorkingSet,
spans: &[Span],
expand_aliases_denylist: &[usize],
) -> (Expression, Option<ParseError>) {
// Checking that the function is used with the correct name
// Maybe this is not necessary but it is a sanity check
if working_set.get_span_contents(spans[0]) != b"for" {
return (
garbage(spans[0]),
Some(ParseError::UnknownState(
"internal error: Wrong call name for 'for' function".into(),
span(spans),
)),
);
}
// Parsing the spans and checking that they match the register signature
// Using a parsed call makes more sense than checking for how many spans are in the call
// Also, by creating a call, it can be checked if it matches the declaration signature
let (call, call_span) = match working_set.find_decl(b"for", &Type::Any) {
None => {
return (
garbage(spans[0]),
Some(ParseError::UnknownState(
"internal error: for declaration not found".into(),
span(spans),
)),
)
}
Some(decl_id) => {
working_set.enter_scope();
let ParsedInternalCall {
call,
error: mut err,
output,
} = parse_internal_call(
working_set,
spans[0],
&spans[1..],
decl_id,
expand_aliases_denylist,
);
working_set.exit_scope();
let call_span = span(spans);
let decl = working_set.get_decl(decl_id);
let sig = decl.signature();
// Let's get our block and make sure it has the right signature
if let Some(arg) = call.positional_nth(2) {
match arg {
Expression {
expr: Expr::Block(block_id),
..
}
| Expression {
expr: Expr::RowCondition(block_id),
..
} => {
let block = working_set.get_block_mut(*block_id);
block.signature = Box::new(sig.clone());
}
_ => {}
}
}
err = check_call(call_span, &sig, &call).or(err);
if err.is_some() || call.has_flag("help") {
return (
Expression {
expr: Expr::Call(call),
span: call_span,
ty: output,
custom_completion: None,
},
err,
);
}
(call, call_span)
}
};
// All positional arguments must be in the call positional vector by this point
let var_decl = call.positional_nth(0).expect("for call already checked");
let block = call.positional_nth(2).expect("for call already checked");
let error = None;
if let (Some(var_id), Some(block_id)) = (&var_decl.as_var(), block.as_block()) {
let block = working_set.get_block_mut(block_id);
block.signature.required_positional.insert(
0,
PositionalArg {
name: String::new(),
desc: String::new(),
shape: SyntaxShape::Any,
var_id: Some(*var_id),
default_value: None,
},
);
}
(
Expression {
expr: Expr::Call(call),
span: call_span,
ty: Type::Any,
custom_completion: None,
},
error,
)
}
fn build_usage(working_set: &StateWorkingSet, spans: &[Span]) -> String {
let mut usage = String::new();
let mut num_spaces = 0;
let mut first = true;
// Use the comments to build the usage
for comment_part in spans {
let contents = working_set.get_span_contents(*comment_part);
let comment_line = if first {
// Count the number of spaces still at the front, skipping the '#'
let mut pos = 1;
while pos < contents.len() {
if let Some(b' ') = contents.get(pos) {
// continue
} else {
break;
}
pos += 1;
}
num_spaces = pos;
first = false;
String::from_utf8_lossy(&contents[pos..]).to_string()
} else {
let mut pos = 1;
while pos < contents.len() && pos < num_spaces {
if let Some(b' ') = contents.get(pos) {
// continue
} else {
break;
}
pos += 1;
}
String::from_utf8_lossy(&contents[pos..]).to_string()
};
if !usage.is_empty() {
usage.push('\n');
}
usage.push_str(&comment_line);
}
usage
}
pub fn parse_def(
working_set: &mut StateWorkingSet,
lite_command: &LiteCommand,
expand_aliases_denylist: &[usize],
) -> (Pipeline, Option<ParseError>) {
let spans = &lite_command.parts[..];
let usage = build_usage(working_set, &lite_command.comments);
// Checking that the function is used with the correct name
// Maybe this is not necessary but it is a sanity check
// Note: "export def" is treated the same as "def"
let (name_span, split_id) =
if spans.len() > 1 && working_set.get_span_contents(spans[0]) == b"export" {
(spans[1], 2)
} else {
(spans[0], 1)
};
let def_call = working_set.get_span_contents(name_span).to_vec();
if def_call != b"def" && def_call != b"def-env" {
return (
garbage_pipeline(spans),
Some(ParseError::UnknownState(
"internal error: Wrong call name for def function".into(),
span(spans),
)),
);
}
// Parsing the spans and checking that they match the register signature
// Using a parsed call makes more sense than checking for how many spans are in the call
// Also, by creating a call, it can be checked if it matches the declaration signature
let (call, call_span) = match working_set.find_decl(&def_call, &Type::Any) {
None => {
return (
garbage_pipeline(spans),
Some(ParseError::UnknownState(
"internal error: def declaration not found".into(),
span(spans),
)),
)
}
Some(decl_id) => {
working_set.enter_scope();
let (command_spans, rest_spans) = spans.split_at(split_id);
let ParsedInternalCall {
call,
error: mut err,
output,
} = parse_internal_call(
working_set,
span(command_spans),
rest_spans,
decl_id,
expand_aliases_denylist,
);
working_set.exit_scope();
let call_span = span(spans);
let decl = working_set.get_decl(decl_id);
let sig = decl.signature();
// Let's get our block and make sure it has the right signature
if let Some(arg) = call.positional_nth(2) {
match arg {
Expression {
expr: Expr::Block(block_id),
..
}
| Expression {
expr: Expr::RowCondition(block_id),
..
} => {
let block = working_set.get_block_mut(*block_id);
block.signature = Box::new(sig.clone());
}
_ => {}
}
}
err = check_call(call_span, &sig, &call).or(err);
if err.is_some() || call.has_flag("help") {
return (
Pipeline::from_vec(vec![Expression {
expr: Expr::Call(call),
span: call_span,
ty: output,
custom_completion: None,
}]),
err,
);
}
(call, call_span)
}
};
// All positional arguments must be in the call positional vector by this point
let name_expr = call.positional_nth(0).expect("def call already checked");
let sig = call.positional_nth(1).expect("def call already checked");
let block = call.positional_nth(2).expect("def call already checked");
let mut error = None;
if let (Some(name), Some(mut signature), Some(block_id)) =
(&name_expr.as_string(), sig.as_signature(), block.as_block())
{
if let Some(decl_id) = working_set.find_predecl(name.as_bytes()) {
let declaration = working_set.get_decl_mut(decl_id);
signature.name = name.clone();
*signature = signature.add_help();
signature.usage = usage;
*declaration = signature.clone().into_block_command(block_id);
let mut block = working_set.get_block_mut(block_id);
block.signature = signature;
block.redirect_env = def_call == b"def-env";
} else {
error = error.or_else(|| {
Some(ParseError::InternalError(
"Predeclaration failed to add declaration".into(),
name_expr.span,
))
});
};
}
if let Some(name) = name_expr.as_string() {
// It's OK if it returns None: The decl was already merged in previous parse pass.
working_set.merge_predecl(name.as_bytes());
} else {
error = error.or_else(|| {
Some(ParseError::UnknownState(
"Could not get string from string expression".into(),
name_expr.span,
))
});
}
(
Pipeline::from_vec(vec![Expression {
expr: Expr::Call(call),
span: call_span,
ty: Type::Any,
custom_completion: None,
}]),
error,
)
}
pub fn parse_extern(
working_set: &mut StateWorkingSet,
lite_command: &LiteCommand,
expand_aliases_denylist: &[usize],
) -> (Pipeline, Option<ParseError>) {
let spans = &lite_command.parts;
let mut error = None;
let usage = build_usage(working_set, &lite_command.comments);
// Checking that the function is used with the correct name
// Maybe this is not necessary but it is a sanity check
let (name_span, split_id) =
if spans.len() > 1 && working_set.get_span_contents(spans[0]) == b"export" {
(spans[1], 2)
} else {
(spans[0], 1)
};
let extern_call = working_set.get_span_contents(name_span).to_vec();
if extern_call != b"extern" {
return (
garbage_pipeline(spans),
Some(ParseError::UnknownState(
"internal error: Wrong call name for extern function".into(),
span(spans),
)),
);
}
// Parsing the spans and checking that they match the register signature
// Using a parsed call makes more sense than checking for how many spans are in the call
// Also, by creating a call, it can be checked if it matches the declaration signature
let (call, call_span) = match working_set.find_decl(&extern_call, &Type::Any) {
None => {
return (
garbage_pipeline(spans),
Some(ParseError::UnknownState(
"internal error: def declaration not found".into(),
span(spans),
)),
)
}
Some(decl_id) => {
working_set.enter_scope();
let (command_spans, rest_spans) = spans.split_at(split_id);
let ParsedInternalCall {
call, error: err, ..
} = parse_internal_call(
working_set,
span(command_spans),
rest_spans,
decl_id,
expand_aliases_denylist,
);
working_set.exit_scope();
error = error.or(err);
let call_span = span(spans);
//let decl = working_set.get_decl(decl_id);
//let sig = decl.signature();
(call, call_span)
}
};
let name_expr = call.positional_nth(0);
let sig = call.positional_nth(1);
if let (Some(name_expr), Some(sig)) = (name_expr, sig) {
if let (Some(name), Some(mut signature)) = (&name_expr.as_string(), sig.as_signature()) {
if let Some(decl_id) = working_set.find_predecl(name.as_bytes()) {
let declaration = working_set.get_decl_mut(decl_id);
signature.name = name.clone();
signature.usage = usage.clone();
let decl = KnownExternal {
name: name.to_string(),
usage,
signature,
};
*declaration = Box::new(decl);
} else {
error = error.or_else(|| {
Some(ParseError::InternalError(
"Predeclaration failed to add declaration".into(),
spans[split_id],
))
});
};
}
if let Some(name) = name_expr.as_string() {
// It's OK if it returns None: The decl was already merged in previous parse pass.
working_set.merge_predecl(name.as_bytes());
} else {
error = error.or_else(|| {
Some(ParseError::UnknownState(
"Could not get string from string expression".into(),
name_expr.span,
))
});
}
}
(
Pipeline::from_vec(vec![Expression {
expr: Expr::Call(call),
span: call_span,
ty: Type::Any,
custom_completion: None,
}]),
error,
)
}
pub fn parse_alias(
working_set: &mut StateWorkingSet,
spans: &[Span],
expand_aliases_denylist: &[usize],
) -> (Pipeline, Option<ParseError>) {
let (name_span, split_id) =
if spans.len() > 1 && working_set.get_span_contents(spans[0]) == b"export" {
(spans[1], 2)
} else {
(spans[0], 1)
};
let name = working_set.get_span_contents(name_span);
if name == b"alias" {
if let Some((span, err)) = check_name(working_set, spans) {
return (Pipeline::from_vec(vec![garbage(*span)]), Some(err));
}
if let Some(decl_id) = working_set.find_decl(b"alias", &Type::Any) {
let (command_spans, rest_spans) = spans.split_at(split_id);
let ParsedInternalCall { call, output, .. } = parse_internal_call(
working_set,
span(command_spans),
rest_spans,
decl_id,
expand_aliases_denylist,
);
if call.has_flag("help") {
return (
Pipeline::from_vec(vec![Expression {
expr: Expr::Call(call),
span: span(spans),
ty: output,
custom_completion: None,
}]),
None,
);
}
if spans.len() >= split_id + 3 {
let alias_name = working_set.get_span_contents(spans[split_id]);
let alias_name = if alias_name.starts_with(b"\"")
&& alias_name.ends_with(b"\"")
&& alias_name.len() > 1
{
alias_name[1..(alias_name.len() - 1)].to_vec()
} else {
alias_name.to_vec()
};
let _equals = working_set.get_span_contents(spans[split_id + 1]);
let replacement = spans[(split_id + 2)..].to_vec();
working_set.add_alias(alias_name, replacement);
}
let err = if spans.len() < 4 {
Some(ParseError::IncorrectValue(
"Incomplete alias".into(),
span(&spans[..split_id]),
"incomplete alias".into(),
))
} else {
None
};
return (
Pipeline::from_vec(vec![Expression {
expr: Expr::Call(call),
span: span(spans),
ty: Type::Any,
custom_completion: None,
}]),
err,
);
}
}
(
garbage_pipeline(spans),
Some(ParseError::InternalError(
"Alias statement unparseable".into(),
span(spans),
)),
)
}
// This one will trigger if `export` appears during eval, e.g., in a script
pub fn parse_export_in_block(
working_set: &mut StateWorkingSet,
lite_command: &LiteCommand,
expand_aliases_denylist: &[usize],
) -> (Pipeline, Option<ParseError>) {
let call_span = span(&lite_command.parts);
let full_name = if lite_command.parts.len() > 1 {
let sub = working_set.get_span_contents(lite_command.parts[1]);
match sub {
b"alias" | b"def" | b"def-env" | b"extern" | b"use" => [b"export ", sub].concat(),
_ => b"export".to_vec(),
}
} else {
b"export".to_vec()
};
if let Some(decl_id) = working_set.find_decl(&full_name, &Type::Any) {
let ParsedInternalCall {
call,
error: mut err,
output,
..
} = parse_internal_call(
working_set,
if full_name == b"export" {
lite_command.parts[0]
} else {
span(&lite_command.parts[0..2])
},
if full_name == b"export" {
&lite_command.parts[1..]
} else {
&lite_command.parts[2..]
},
decl_id,
expand_aliases_denylist,
);
let decl = working_set.get_decl(decl_id);
err = check_call(call_span, &decl.signature(), &call).or(err);
if err.is_some() || call.has_flag("help") {
return (
Pipeline::from_vec(vec![Expression {
expr: Expr::Call(call),
span: call_span,
ty: output,
custom_completion: None,
}]),
err,
);
}
} else {
return (
garbage_pipeline(&lite_command.parts),
Some(ParseError::UnknownState(
format!(
"internal error: '{}' declaration not found",
String::from_utf8_lossy(&full_name)
),
span(&lite_command.parts),
)),
);
};
if &full_name == b"export" {
// export by itself is meaningless
return (
garbage_pipeline(&lite_command.parts),
Some(ParseError::UnexpectedKeyword(
"export".into(),
lite_command.parts[0],
)),
);
}
match full_name.as_slice() {
b"export alias" => parse_alias(working_set, &lite_command.parts, expand_aliases_denylist),
b"export def" | b"export def-env" => {
parse_def(working_set, lite_command, expand_aliases_denylist)
}
b"export use" => {
let (pipeline, _, err) =
parse_use(working_set, &lite_command.parts, expand_aliases_denylist);
(pipeline, err)
}
b"export extern" => parse_extern(working_set, lite_command, expand_aliases_denylist),
_ => (
garbage_pipeline(&lite_command.parts),
Some(ParseError::UnexpectedKeyword(
String::from_utf8_lossy(&full_name).to_string(),
lite_command.parts[0],
)),
),
}
}
// This one will trigger only in a module
pub fn parse_export_in_module(
working_set: &mut StateWorkingSet,
lite_command: &LiteCommand,
expand_aliases_denylist: &[usize],
) -> (Pipeline, Vec<Exportable>, Option<ParseError>) {
let spans = &lite_command.parts[..];
let mut error = None;
let export_span = if let Some(sp) = spans.get(0) {
if working_set.get_span_contents(*sp) != b"export" {
return (
garbage_pipeline(spans),
vec![],
Some(ParseError::UnknownState(
"expected export statement".into(),
span(spans),
)),
);
}
*sp
} else {
return (
garbage_pipeline(spans),
vec![],
Some(ParseError::UnknownState(
"got empty input for parsing export statement".into(),
span(spans),
)),
);
};
let export_decl_id = if let Some(id) = working_set.find_decl(b"export", &Type::Any) {
id
} else {
return (
garbage_pipeline(spans),
vec![],
Some(ParseError::InternalError(
"missing export command".into(),
export_span,
)),
);
};
let mut call = Box::new(Call {
head: spans[0],
decl_id: export_decl_id,
arguments: vec![],
redirect_stdout: true,
redirect_stderr: false,
});
let exportables = if let Some(kw_span) = spans.get(1) {
let kw_name = working_set.get_span_contents(*kw_span);
match kw_name {
b"def" => {
let lite_command = LiteCommand {
comments: lite_command.comments.clone(),
parts: spans[1..].to_vec(),
};
let (pipeline, err) =
parse_def(working_set, &lite_command, expand_aliases_denylist);
error = error.or(err);
let export_def_decl_id =
if let Some(id) = working_set.find_decl(b"export def", &Type::Any) {
id
} else {
return (
garbage_pipeline(spans),
vec![],
Some(ParseError::InternalError(
"missing 'export def' command".into(),
export_span,
)),
);
};
// Trying to warp the 'def' call into the 'export def' in a very clumsy way
if let Some(Expression {
expr: Expr::Call(ref def_call),
..
}) = pipeline.expressions.get(0)
{
call = def_call.clone();
call.head = span(&spans[0..=1]);
call.decl_id = export_def_decl_id;
} else {
error = error.or_else(|| {
Some(ParseError::InternalError(
"unexpected output from parsing a definition".into(),
span(&spans[1..]),
))
});
};
let mut result = vec![];
if let Some(decl_name_span) = spans.get(2) {
let decl_name = working_set.get_span_contents(*decl_name_span);
let decl_name = trim_quotes(decl_name);
if let Some(decl_id) = working_set.find_decl(decl_name, &Type::Any) {
result.push(Exportable::Decl {
name: decl_name.to_vec(),
id: decl_id,
});
} else {
error = error.or_else(|| {
Some(ParseError::InternalError(
"failed to find added declaration".into(),
span(&spans[1..]),
))
});
}
}
result
}
b"def-env" => {
let lite_command = LiteCommand {
comments: lite_command.comments.clone(),
parts: spans[1..].to_vec(),
};
let (pipeline, err) =
parse_def(working_set, &lite_command, expand_aliases_denylist);
error = error.or(err);
let export_def_decl_id =
if let Some(id) = working_set.find_decl(b"export def-env", &Type::Any) {
id
} else {
return (
garbage_pipeline(spans),
vec![],
Some(ParseError::InternalError(
"missing 'export def-env' command".into(),
export_span,
)),
);
};
// Trying to warp the 'def' call into the 'export def' in a very clumsy way
if let Some(Expression {
expr: Expr::Call(ref def_call),
..
}) = pipeline.expressions.get(0)
{
call = def_call.clone();
call.head = span(&spans[0..=1]);
call.decl_id = export_def_decl_id;
} else {
error = error.or_else(|| {
Some(ParseError::InternalError(
"unexpected output from parsing a definition".into(),
span(&spans[1..]),
))
});
};
let mut result = vec![];
let decl_name = match spans.get(2) {
Some(span) => working_set.get_span_contents(*span),
None => &[],
};
let decl_name = trim_quotes(decl_name);
if let Some(decl_id) = working_set.find_decl(decl_name, &Type::Any) {
result.push(Exportable::Decl {
name: decl_name.to_vec(),
id: decl_id,
});
} else {
error = error.or_else(|| {
Some(ParseError::InternalError(
"failed to find added declaration".into(),
span(&spans[1..]),
))
});
}
result
}
b"extern" => {
let lite_command = LiteCommand {
comments: lite_command.comments.clone(),
parts: spans[1..].to_vec(),
};
let (pipeline, err) =
parse_extern(working_set, &lite_command, expand_aliases_denylist);
error = error.or(err);
let export_def_decl_id =
if let Some(id) = working_set.find_decl(b"export extern", &Type::Any) {
id
} else {
return (
garbage_pipeline(spans),
vec![],
Some(ParseError::InternalError(
"missing 'export extern' command".into(),
export_span,
)),
);
};
// Trying to warp the 'def' call into the 'export def' in a very clumsy way
if let Some(Expression {
expr: Expr::Call(ref def_call),
..
}) = pipeline.expressions.get(0)
{
call = def_call.clone();
call.head = span(&spans[0..=1]);
call.decl_id = export_def_decl_id;
} else {
error = error.or_else(|| {
Some(ParseError::InternalError(
"unexpected output from parsing a definition".into(),
span(&spans[1..]),
))
});
};
let mut result = vec![];
let decl_name = match spans.get(2) {
Some(span) => working_set.get_span_contents(*span),
None => &[],
};
let decl_name = trim_quotes(decl_name);
if let Some(decl_id) = working_set.find_decl(decl_name, &Type::Any) {
result.push(Exportable::Decl {
name: decl_name.to_vec(),
id: decl_id,
});
} else {
error = error.or_else(|| {
Some(ParseError::InternalError(
"failed to find added declaration".into(),
span(&spans[1..]),
))
});
}
result
}
b"alias" => {
let lite_command = LiteCommand {
comments: lite_command.comments.clone(),
parts: spans[1..].to_vec(),
};
let (pipeline, err) =
parse_alias(working_set, &lite_command.parts, expand_aliases_denylist);
error = error.or(err);
let export_alias_decl_id =
if let Some(id) = working_set.find_decl(b"export alias", &Type::Any) {
id
} else {
return (
garbage_pipeline(spans),
vec![],
Some(ParseError::InternalError(
"missing 'export alias' command".into(),
export_span,
)),
);
};
// Trying to warp the 'alias' call into the 'export alias' in a very clumsy way
if let Some(Expression {
expr: Expr::Call(ref alias_call),
..
}) = pipeline.expressions.get(0)
{
call = alias_call.clone();
call.head = span(&spans[0..=1]);
call.decl_id = export_alias_decl_id;
} else {
error = error.or_else(|| {
Some(ParseError::InternalError(
"unexpected output from parsing a definition".into(),
span(&spans[1..]),
))
});
};
let mut result = vec![];
let alias_name = match spans.get(2) {
Some(span) => working_set.get_span_contents(*span),
None => &[],
};
let alias_name = trim_quotes(alias_name);
if let Some(alias_id) = working_set.find_alias(alias_name) {
result.push(Exportable::Alias {
name: alias_name.to_vec(),
id: alias_id,
});
} else {
error = error.or_else(|| {
Some(ParseError::InternalError(
"failed to find added alias".into(),
span(&spans[1..]),
))
});
}
result
}
b"use" => {
let lite_command = LiteCommand {
comments: lite_command.comments.clone(),
parts: spans[1..].to_vec(),
};
let (pipeline, exportables, err) =
parse_use(working_set, &lite_command.parts, expand_aliases_denylist);
error = error.or(err);
let export_use_decl_id =
if let Some(id) = working_set.find_decl(b"export use", &Type::Any) {
id
} else {
return (
garbage_pipeline(spans),
vec![],
Some(ParseError::InternalError(
"missing 'export use' command".into(),
export_span,
)),
);
};
// Trying to warp the 'use' call into the 'export use' in a very clumsy way
if let Some(Expression {
expr: Expr::Call(ref use_call),
..
}) = pipeline.expressions.get(0)
{
call = use_call.clone();
call.head = span(&spans[0..=1]);
call.decl_id = export_use_decl_id;
} else {
error = error.or_else(|| {
Some(ParseError::InternalError(
"unexpected output from parsing a definition".into(),
span(&spans[1..]),
))
});
};
exportables
}
b"env" => {
if let Some(id) = working_set.find_decl(b"export env", &Type::Any) {
call.decl_id = id;
} else {
return (
garbage_pipeline(spans),
vec![],
Some(ParseError::InternalError(
"missing 'export env' command".into(),
export_span,
)),
);
}
let sig = working_set.get_decl(call.decl_id);
let call_signature = sig.signature().call_signature();
call.head = span(&spans[0..=1]);
let mut result = vec![];
if let Some(name_span) = spans.get(2) {
let (name_expr, err) =
parse_string(working_set, *name_span, expand_aliases_denylist);
error = error.or(err);
call.add_positional(name_expr);
let env_var_name = working_set.get_span_contents(*name_span).to_vec();
if let Some(block_span) = spans.get(3) {
let (block_expr, err) = parse_block_expression(
working_set,
&SyntaxShape::Block(None),
*block_span,
expand_aliases_denylist,
);
error = error.or(err);
if let Expression {
expr: Expr::Block(block_id),
..
} = block_expr
{
result.push(Exportable::EnvVar {
name: env_var_name,
id: block_id,
});
} else {
error = error.or_else(|| {
Some(ParseError::InternalError(
"block was not parsed as a block".into(),
*block_span,
))
});
}
call.add_positional(block_expr);
} else {
let err_span = Span {
start: name_span.end,
end: name_span.end,
};
error = error.or_else(|| {
Some(ParseError::MissingPositional(
"block".into(),
err_span,
call_signature,
))
});
}
} else {
let err_span = Span {
start: kw_span.end,
end: kw_span.end,
};
error = error.or_else(|| {
Some(ParseError::MissingPositional(
"environment variable name".into(),
err_span,
call_signature,
))
});
}
result
}
_ => {
error = error.or_else(|| {
Some(ParseError::Expected(
// TODO: Fill in more keywords as they come
"def, def-env, alias, use, or env keyword".into(),
spans[1],
))
});
vec![]
}
}
} else {
error = error.or_else(|| {
Some(ParseError::MissingPositional(
"def, def-env, alias, or env keyword".into(), // TODO: keep filling more keywords as they come
Span {
start: export_span.end,
end: export_span.end,
},
"'def', `def-env`, `alias`, or 'env' keyword.".to_string(),
))
});
vec![]
};
(
Pipeline::from_vec(vec![Expression {
expr: Expr::Call(call),
span: span(spans),
ty: Type::Any,
custom_completion: None,
}]),
exportables,
error,
)
}
pub fn parse_export_env(
working_set: &mut StateWorkingSet,
spans: &[Span],
expand_aliases_denylist: &[usize],
) -> (Pipeline, Option<BlockId>, Option<ParseError>) {
if !spans.is_empty() && working_set.get_span_contents(spans[0]) != b"export-env" {
return (
garbage_pipeline(spans),
None,
Some(ParseError::UnknownState(
"internal error: Wrong call name for 'export-env' command".into(),
span(spans),
)),
);
}
if spans.len() < 2 {
return (
garbage_pipeline(spans),
None,
Some(ParseError::MissingPositional(
"block".into(),
span(spans),
"export-env <block>".into(),
)),
);
}
let call = match working_set.find_decl(b"export-env", &Type::Any) {
Some(decl_id) => {
let ParsedInternalCall {
call,
error: mut err,
output,
} = parse_internal_call(
working_set,
spans[0],
&[spans[1]],
decl_id,
expand_aliases_denylist,
);
let decl = working_set.get_decl(decl_id);
let call_span = span(spans);
err = check_call(call_span, &decl.signature(), &call).or(err);
if err.is_some() || call.has_flag("help") {
return (
Pipeline::from_vec(vec![Expression {
expr: Expr::Call(call),
span: call_span,
ty: output,
custom_completion: None,
}]),
None,
err,
);
}
call
}
None => {
return (
garbage_pipeline(spans),
None,
Some(ParseError::UnknownState(
"internal error: 'export-env' declaration not found".into(),
span(spans),
)),
)
}
};
let block_id = if let Some(block) = call.positional_nth(0) {
if let Some(block_id) = block.as_block() {
block_id
} else {
return (
garbage_pipeline(spans),
None,
Some(ParseError::UnknownState(
"internal error: 'export-env' block is not a block".into(),
block.span,
)),
);
}
} else {
return (
garbage_pipeline(spans),
None,
Some(ParseError::UnknownState(
"internal error: 'export-env' block is missing".into(),
span(spans),
)),
);
};
let pipeline = Pipeline::from_vec(vec![Expression {
expr: Expr::Call(call),
span: span(spans),
ty: Type::Any,
custom_completion: None,
}]);
(pipeline, Some(block_id), None)
}
pub fn parse_module_block(
working_set: &mut StateWorkingSet,
span: Span,
expand_aliases_denylist: &[usize],
) -> (Block, Module, Option<ParseError>) {
let mut error = None;
working_set.enter_scope();
let source = working_set.get_span_contents(span);
let (output, err) = lex(source, span.start, &[], &[], false);
error = error.or(err);
let (output, err) = lite_parse(&output);
error = error.or(err);
for pipeline in &output.block {
// TODO: Should we add export env predecls as well?
if pipeline.commands.len() == 1 {
parse_def_predecl(
working_set,
&pipeline.commands[0].parts,
expand_aliases_denylist,
);
}
}
let mut module = Module::from_span(span);
let block: Block = output
.block
.iter()
.map(|pipeline| {
if pipeline.commands.len() == 1 {
let name = working_set.get_span_contents(pipeline.commands[0].parts[0]);
let (pipeline, err) = match name {
b"def" | b"def-env" => {
let (pipeline, err) =
parse_def(working_set, &pipeline.commands[0], expand_aliases_denylist);
(pipeline, err)
}
b"extern" => {
let (pipeline, err) = parse_extern(
working_set,
&pipeline.commands[0],
expand_aliases_denylist,
);
(pipeline, err)
}
b"alias" => {
let (pipeline, err) = parse_alias(
working_set,
&pipeline.commands[0].parts,
expand_aliases_denylist,
);
(pipeline, err)
}
b"use" => {
let (pipeline, _, err) = parse_use(
working_set,
&pipeline.commands[0].parts,
expand_aliases_denylist,
);
(pipeline, err)
}
b"export" => {
let (pipe, exportables, err) = parse_export_in_module(
working_set,
&pipeline.commands[0],
expand_aliases_denylist,
);
if err.is_none() {
for exportable in exportables {
match exportable {
Exportable::Decl { name, id } => {
module.add_decl(name, id);
}
Exportable::Alias { name, id } => {
module.add_alias(name, id);
}
Exportable::EnvVar { name, id } => {
module.add_env_var(name, id);
}
}
}
}
(pipe, err)
}
b"export-env" => {
let (pipe, maybe_env_block, err) = parse_export_env(
working_set,
&pipeline.commands[0].parts,
expand_aliases_denylist,
);
if let Some(block_id) = maybe_env_block {
module.add_env_block(block_id);
}
(pipe, err)
}
_ => (
garbage_pipeline(&pipeline.commands[0].parts),
Some(ParseError::ExpectedKeyword(
"def or export keyword".into(),
pipeline.commands[0].parts[0],
)),
),
};
if error.is_none() {
error = err;
}
pipeline
} else {
error = Some(ParseError::Expected("not a pipeline".into(), span));
garbage_pipeline(&[span])
}
})
.into();
working_set.exit_scope();
(block, module, error)
}
pub fn parse_module(
working_set: &mut StateWorkingSet,
spans: &[Span],
expand_aliases_denylist: &[usize],
) -> (Pipeline, Option<ParseError>) {
// TODO: Currently, module is closing over its parent scope (i.e., defs in the parent scope are
// visible and usable in this module's scope). We want to disable that for files.
let mut error = None;
let bytes = working_set.get_span_contents(spans[0]);
if bytes == b"module" && spans.len() >= 3 {
let (module_name_expr, err) = parse_string(working_set, spans[1], expand_aliases_denylist);
error = error.or(err);
let module_name = module_name_expr
.as_string()
.expect("internal error: module name is not a string");
let block_span = spans[2];
let block_bytes = working_set.get_span_contents(block_span);
let mut start = block_span.start;
let mut end = block_span.end;
if block_bytes.starts_with(b"{") {
start += 1;
} else {
return (
garbage_pipeline(spans),
Some(ParseError::Expected("block".into(), block_span)),
);
}
if block_bytes.ends_with(b"}") {
end -= 1;
} else {
error =
error.or_else(|| Some(ParseError::Unclosed("}".into(), Span { start: end, end })));
}
let block_span = Span { start, end };
let (block, module, err) =
parse_module_block(working_set, block_span, expand_aliases_denylist);
error = error.or(err);
let block_id = working_set.add_block(block);
let _ = working_set.add_module(&module_name, module);
let block_expr = Expression {
expr: Expr::Block(block_id),
span: block_span,
ty: Type::Block,
custom_completion: None,
};
let module_decl_id = working_set
.find_decl(b"module", &Type::Any)
.expect("internal error: missing module command");
let call = Box::new(Call {
head: spans[0],
decl_id: module_decl_id,
arguments: vec![
Argument::Positional(module_name_expr),
Argument::Positional(block_expr),
],
redirect_stdout: true,
redirect_stderr: false,
});
(
Pipeline::from_vec(vec![Expression {
expr: Expr::Call(call),
span: span(spans),
ty: Type::Any,
custom_completion: None,
}]),
error,
)
} else {
(
garbage_pipeline(spans),
Some(ParseError::UnknownState(
"Expected structure: module <name> {}".into(),
span(spans),
)),
)
}
}
pub fn parse_use(
working_set: &mut StateWorkingSet,
spans: &[Span],
expand_aliases_denylist: &[usize],
) -> (Pipeline, Vec<Exportable>, Option<ParseError>) {
let (name_span, split_id) =
if spans.len() > 1 && working_set.get_span_contents(spans[0]) == b"export" {
(spans[1], 2)
} else {
(spans[0], 1)
};
let use_call = working_set.get_span_contents(name_span).to_vec();
if use_call != b"use" {
return (
garbage_pipeline(spans),
vec![],
Some(ParseError::UnknownState(
"internal error: Wrong call name for 'use' command".into(),
span(spans),
)),
);
}
if working_set.get_span_contents(name_span) != b"use" {
return (
garbage_pipeline(spans),
vec![],
Some(ParseError::UnknownState(
"internal error: Wrong call name for 'use' command".into(),
span(spans),
)),
);
}
let (call, call_span, use_decl_id) = match working_set.find_decl(b"use", &Type::Any) {
Some(decl_id) => {
let (command_spans, rest_spans) = spans.split_at(split_id);
let ParsedInternalCall {
call,
error: mut err,
output,
} = parse_internal_call(
working_set,
span(command_spans),
rest_spans,
decl_id,
expand_aliases_denylist,
);
let decl = working_set.get_decl(decl_id);
let call_span = span(spans);
err = check_call(call_span, &decl.signature(), &call).or(err);
if err.is_some() || call.has_flag("help") {
return (
Pipeline::from_vec(vec![Expression {
expr: Expr::Call(call),
span: call_span,
ty: output,
custom_completion: None,
}]),
vec![],
err,
);
}
(call, call_span, decl_id)
}
None => {
return (
garbage_pipeline(spans),
vec![],
Some(ParseError::UnknownState(
"internal error: 'use' declaration not found".into(),
span(spans),
)),
)
}
};
let import_pattern = if let Some(expr) = call.positional_nth(0) {
if let Some(pattern) = expr.as_import_pattern() {
pattern
} else {
return (
garbage_pipeline(spans),
vec![],
Some(ParseError::UnknownState(
"internal error: Import pattern positional is not import pattern".into(),
expr.span,
)),
);
}
} else {
return (
garbage_pipeline(spans),
vec![],
Some(ParseError::UnknownState(
"internal error: Missing required positional after call parsing".into(),
call_span,
)),
);
};
let cwd = working_set.get_cwd();
let mut error = None;
// TODO: Add checking for importing too long import patterns, e.g.:
// > use spam foo non existent names here do not throw error
let (import_pattern, module) =
if let Some(module_id) = working_set.find_module(&import_pattern.head.name) {
(import_pattern, working_set.get_module(module_id).clone())
} else {
// It could be a file
// TODO: Do not close over when loading module from file?
let (module_filename, err) =
unescape_unquote_string(&import_pattern.head.name, import_pattern.head.span);
if err.is_none() {
if let Some(module_path) =
find_in_dirs(&module_filename, working_set, &cwd, LIB_DIRS_ENV)
{
if let Some(i) = working_set
.parsed_module_files
.iter()
.rposition(|p| p == &module_path)
{
let mut files: Vec<String> = working_set
.parsed_module_files
.split_off(i)
.iter()
.map(|p| p.to_string_lossy().to_string())
.collect();
files.push(module_path.to_string_lossy().to_string());
let msg = files.join("\nuses ");
return (
Pipeline::from_vec(vec![Expression {
expr: Expr::Call(call),
span: call_span,
ty: Type::Any,
custom_completion: None,
}]),
vec![],
Some(ParseError::CyclicalModuleImport(
msg,
import_pattern.head.span,
)),
);
}
let module_name = if let Some(stem) = module_path.file_stem() {
stem.to_string_lossy().to_string()
} else {
return (
Pipeline::from_vec(vec![Expression {
expr: Expr::Call(call),
span: call_span,
ty: Type::Any,
custom_completion: None,
}]),
vec![],
Some(ParseError::ModuleNotFound(import_pattern.head.span)),
);
};
if let Ok(contents) = std::fs::read(&module_path) {
let span_start = working_set.next_span_start();
working_set.add_file(module_filename, &contents);
let span_end = working_set.next_span_start();
// Change the currently parsed directory
let prev_currently_parsed_cwd = if let Some(parent) = module_path.parent() {
let prev = working_set.currently_parsed_cwd.clone();
working_set.currently_parsed_cwd = Some(parent.into());
prev
} else {
working_set.currently_parsed_cwd.clone()
};
// Add the file to the stack of parsed module files
working_set.parsed_module_files.push(module_path);
// Parse the module
let (block, module, err) = parse_module_block(
working_set,
Span::new(span_start, span_end),
expand_aliases_denylist,
);
error = error.or(err);
// Remove the file from the stack of parsed module files
working_set.parsed_module_files.pop();
// Restore the currently parsed directory back
working_set.currently_parsed_cwd = prev_currently_parsed_cwd;
let _ = working_set.add_block(block);
let module_id = working_set.add_module(&module_name, module.clone());
(
ImportPattern {
head: ImportPatternHead {
name: module_name.into(),
id: Some(module_id),
span: import_pattern.head.span,
},
members: import_pattern.members,
hidden: HashSet::new(),
},
module,
)
} else {
return (
Pipeline::from_vec(vec![Expression {
expr: Expr::Call(call),
span: call_span,
ty: Type::Any,
custom_completion: None,
}]),
vec![],
Some(ParseError::ModuleNotFound(import_pattern.head.span)),
);
}
} else {
error = error.or(Some(ParseError::ModuleNotFound(import_pattern.head.span)));
let old_span = import_pattern.head.span;
let mut import_pattern = ImportPattern::new();
import_pattern.head.span = old_span;
(import_pattern, Module::new())
}
} else {
return (
garbage_pipeline(spans),
vec![],
Some(ParseError::NonUtf8(import_pattern.head.span)),
);
}
};
let (decls_to_use, aliases_to_use) = if import_pattern.members.is_empty() {
(
module.decls_with_head(&import_pattern.head.name),
module.aliases_with_head(&import_pattern.head.name),
)
} else {
match &import_pattern.members[0] {
ImportPatternMember::Glob { .. } => (module.decls(), module.aliases()),
ImportPatternMember::Name { name, span } => {
let mut decl_output = vec![];
let mut alias_output = vec![];
if let Some(id) = module.get_decl_id(name) {
decl_output.push((name.clone(), id));
} else if let Some(id) = module.get_alias_id(name) {
alias_output.push((name.clone(), id));
} else if !module.has_env_var(name) {
error = error.or(Some(ParseError::ExportNotFound(*span)))
}
(decl_output, alias_output)
}
ImportPatternMember::List { names } => {
let mut decl_output = vec![];
let mut alias_output = vec![];
for (name, span) in names {
if let Some(id) = module.get_decl_id(name) {
decl_output.push((name.clone(), id));
} else if let Some(id) = module.get_alias_id(name) {
alias_output.push((name.clone(), id));
} else if !module.has_env_var(name) {
error = error.or(Some(ParseError::ExportNotFound(*span)));
break;
}
}
(decl_output, alias_output)
}
}
};
let exportables = decls_to_use
.iter()
.map(|(name, decl_id)| Exportable::Decl {
name: name.clone(),
id: *decl_id,
})
.chain(
aliases_to_use
.iter()
.map(|(name, alias_id)| Exportable::Alias {
name: name.clone(),
id: *alias_id,
}),
)
.collect();
// Extend the current scope with the module's exportables
working_set.use_decls(decls_to_use);
working_set.use_aliases(aliases_to_use);
// Create a new Use command call to pass the new import pattern
let import_pattern_expr = Expression {
expr: Expr::ImportPattern(import_pattern),
span: span(&spans[1..]),
ty: Type::List(Box::new(Type::String)),
custom_completion: None,
};
let call = Box::new(Call {
head: span(spans.split_at(split_id).0),
decl_id: use_decl_id,
arguments: vec![Argument::Positional(import_pattern_expr)],
redirect_stdout: true,
redirect_stderr: false,
});
(
Pipeline::from_vec(vec![Expression {
expr: Expr::Call(call),
span: span(spans),
ty: Type::Any,
custom_completion: None,
}]),
exportables,
error,
)
}
pub fn parse_hide(
working_set: &mut StateWorkingSet,
spans: &[Span],
expand_aliases_denylist: &[usize],
) -> (Pipeline, Option<ParseError>) {
if working_set.get_span_contents(spans[0]) != b"hide" {
return (
garbage_pipeline(spans),
Some(ParseError::UnknownState(
"internal error: Wrong call name for 'hide' command".into(),
span(spans),
)),
);
}
let (call, call_span, hide_decl_id) = match working_set.find_decl(b"hide", &Type::Any) {
Some(decl_id) => {
let ParsedInternalCall {
call,
error: mut err,
output,
} = parse_internal_call(
working_set,
spans[0],
&spans[1..],
decl_id,
expand_aliases_denylist,
);
let decl = working_set.get_decl(decl_id);
let call_span = span(spans);
err = check_call(call_span, &decl.signature(), &call).or(err);
if err.is_some() || call.has_flag("help") {
return (
Pipeline::from_vec(vec![Expression {
expr: Expr::Call(call),
span: call_span,
ty: output,
custom_completion: None,
}]),
err,
);
}
(call, call_span, decl_id)
}
None => {
return (
garbage_pipeline(spans),
Some(ParseError::UnknownState(
"internal error: 'hide' declaration not found".into(),
span(spans),
)),
)
}
};
let import_pattern = if let Some(expr) = call.positional_nth(0) {
if let Some(pattern) = expr.as_import_pattern() {
pattern
} else {
return (
garbage_pipeline(spans),
Some(ParseError::UnknownState(
"internal error: Import pattern positional is not import pattern".into(),
call_span,
)),
);
}
} else {
return (
garbage_pipeline(spans),
Some(ParseError::UnknownState(
"internal error: Missing required positional after call parsing".into(),
call_span,
)),
);
};
let mut error = None;
let bytes = working_set.get_span_contents(spans[0]);
if bytes == b"hide" && spans.len() >= 2 {
for span in spans[1..].iter() {
let (_, err) = parse_string(working_set, *span, expand_aliases_denylist);
error = error.or(err);
}
let (is_module, module) = if let Some(module_id) =
working_set.find_module(&import_pattern.head.name)
{
(true, working_set.get_module(module_id).clone())
} else if import_pattern.members.is_empty() {
// The pattern head can be:
if let Some(id) = working_set.find_alias(&import_pattern.head.name) {
// an alias,
let mut module = Module::new();
module.add_alias(import_pattern.head.name.clone(), id);
(false, module)
} else if let Some(id) = working_set.find_decl(&import_pattern.head.name, &Type::Any) {
// a custom command,
let mut module = Module::new();
module.add_decl(import_pattern.head.name.clone(), id);
(false, module)
} else {
// , or it could be an env var (handled by the engine)
(false, Module::new())
}
} else {
return (
garbage_pipeline(spans),
Some(ParseError::ModuleNotFound(spans[1])),
);
};
// This kind of inverts the import pattern matching found in parse_use()
let (aliases_to_hide, decls_to_hide) = if import_pattern.members.is_empty() {
if is_module {
(
module.alias_names_with_head(&import_pattern.head.name),
module.decl_names_with_head(&import_pattern.head.name),
)
} else {
(module.alias_names(), module.decl_names())
}
} else {
match &import_pattern.members[0] {
ImportPatternMember::Glob { .. } => (module.alias_names(), module.decl_names()),
ImportPatternMember::Name { name, span } => {
let mut aliases = vec![];
let mut decls = vec![];
if let Some(item) = module.alias_name_with_head(name, &import_pattern.head.name)
{
aliases.push(item);
} else if let Some(item) =
module.decl_name_with_head(name, &import_pattern.head.name)
{
decls.push(item);
} else if !module.has_env_var(name) {
error = error.or(Some(ParseError::ExportNotFound(*span)));
}
(aliases, decls)
}
ImportPatternMember::List { names } => {
let mut aliases = vec![];
let mut decls = vec![];
for (name, span) in names {
if let Some(item) =
module.alias_name_with_head(name, &import_pattern.head.name)
{
aliases.push(item);
} else if let Some(item) =
module.decl_name_with_head(name, &import_pattern.head.name)
{
decls.push(item);
} else if !module.has_env_var(name) {
error = error.or(Some(ParseError::ExportNotFound(*span)));
break;
}
}
(aliases, decls)
}
}
};
let import_pattern = {
let aliases: HashSet<Vec<u8>> = aliases_to_hide.iter().cloned().collect();
let decls: HashSet<Vec<u8>> = decls_to_hide.iter().cloned().collect();
import_pattern.with_hidden(decls.union(&aliases).cloned().collect())
};
// TODO: `use spam; use spam foo; hide foo` will hide both `foo` and `spam foo` since
// they point to the same DeclId. Do we want to keep it that way?
working_set.hide_decls(&decls_to_hide);
working_set.hide_aliases(&aliases_to_hide);
// Create a new Use command call to pass the new import pattern
let import_pattern_expr = Expression {
expr: Expr::ImportPattern(import_pattern),
span: span(&spans[1..]),
ty: Type::List(Box::new(Type::String)),
custom_completion: None,
};
let call = Box::new(Call {
head: spans[0],
decl_id: hide_decl_id,
arguments: vec![Argument::Positional(import_pattern_expr)],
redirect_stdout: true,
redirect_stderr: false,
});
(
Pipeline::from_vec(vec![Expression {
expr: Expr::Call(call),
span: span(spans),
ty: Type::Any,
custom_completion: None,
}]),
error,
)
} else {
(
garbage_pipeline(spans),
Some(ParseError::UnknownState(
"Expected structure: hide <name>".into(),
span(spans),
)),
)
}
}
pub fn parse_overlay(
working_set: &mut StateWorkingSet,
spans: &[Span],
expand_aliases_denylist: &[usize],
) -> (Pipeline, Option<ParseError>) {
if working_set.get_span_contents(spans[0]) != b"overlay" {
return (
garbage_pipeline(spans),
Some(ParseError::UnknownState(
"internal error: Wrong call name for 'overlay' command".into(),
span(spans),
)),
);
}
if spans.len() > 1 {
let subcommand = working_set.get_span_contents(spans[1]);
match subcommand {
b"use" => {
return parse_overlay_use(working_set, spans, expand_aliases_denylist);
}
b"list" => {
// TODO: Abstract this code blob, it's repeated all over the place:
let call = match working_set.find_decl(b"overlay list", &Type::Any) {
Some(decl_id) => {
let ParsedInternalCall {
call,
error: mut err,
output,
} = parse_internal_call(
working_set,
span(&spans[..2]),
if spans.len() > 2 { &spans[2..] } else { &[] },
decl_id,
expand_aliases_denylist,
);
let decl = working_set.get_decl(decl_id);
let call_span = span(spans);
err = check_call(call_span, &decl.signature(), &call).or(err);
if err.is_some() || call.has_flag("help") {
return (
Pipeline::from_vec(vec![Expression {
expr: Expr::Call(call),
span: call_span,
ty: output,
custom_completion: None,
}]),
err,
);
}
call
}
None => {
return (
garbage_pipeline(spans),
Some(ParseError::UnknownState(
"internal error: 'overlay' declaration not found".into(),
span(spans),
)),
)
}
};
return (
Pipeline::from_vec(vec![Expression {
expr: Expr::Call(call),
span: span(spans),
ty: Type::Any,
custom_completion: None,
}]),
None,
);
}
b"new" => {
return parse_overlay_new(working_set, spans, expand_aliases_denylist);
}
b"hide" => {
return parse_overlay_hide(working_set, spans, expand_aliases_denylist);
}
_ => { /* continue parsing overlay */ }
}
}
let call = match working_set.find_decl(b"overlay", &Type::Any) {
Some(decl_id) => {
let ParsedInternalCall {
call,
error: mut err,
output,
} = parse_internal_call(
working_set,
spans[0],
&spans[1..],
decl_id,
expand_aliases_denylist,
);
let decl = working_set.get_decl(decl_id);
let call_span = span(spans);
err = check_call(call_span, &decl.signature(), &call).or(err);
if err.is_some() || call.has_flag("help") {
return (
Pipeline::from_vec(vec![Expression {
expr: Expr::Call(call),
span: call_span,
ty: output,
custom_completion: None,
}]),
err,
);
}
call
}
None => {
return (
garbage_pipeline(spans),
Some(ParseError::UnknownState(
"internal error: 'overlay' declaration not found".into(),
span(spans),
)),
)
}
};
(
Pipeline::from_vec(vec![Expression {
expr: Expr::Call(call),
span: span(spans),
ty: Type::Any,
custom_completion: None,
}]),
None,
)
}
pub fn parse_overlay_new(
working_set: &mut StateWorkingSet,
spans: &[Span],
expand_aliases_denylist: &[usize],
) -> (Pipeline, Option<ParseError>) {
if spans.len() > 1 && working_set.get_span_contents(span(&spans[0..2])) != b"overlay new" {
return (
garbage_pipeline(spans),
Some(ParseError::UnknownState(
"internal error: Wrong call name for 'overlay new' command".into(),
span(spans),
)),
);
}
let (call, call_span) = match working_set.find_decl(b"overlay new", &Type::Any) {
Some(decl_id) => {
let ParsedInternalCall {
call,
error: mut err,
output,
} = parse_internal_call(
working_set,
span(&spans[0..2]),
&spans[2..],
decl_id,
expand_aliases_denylist,
);
let decl = working_set.get_decl(decl_id);
let call_span = span(spans);
err = check_call(call_span, &decl.signature(), &call).or(err);
if err.is_some() || call.has_flag("help") {
return (
Pipeline::from_vec(vec![Expression {
expr: Expr::Call(call),
span: call_span,
ty: output,
custom_completion: None,
}]),
err,
);
}
(call, call_span)
}
None => {
return (
garbage_pipeline(spans),
Some(ParseError::UnknownState(
"internal error: 'overlay new' declaration not found".into(),
span(spans),
)),
)
}
};
let (overlay_name, _) = if let Some(expr) = call.positional_nth(0) {
if let Some(s) = expr.as_string() {
(s, expr.span)
} else {
return (
garbage_pipeline(spans),
Some(ParseError::UnknownState(
"internal error: Module name not a string".into(),
expr.span,
)),
);
}
} else {
return (
garbage_pipeline(spans),
Some(ParseError::UnknownState(
"internal error: Missing required positional after call parsing".into(),
call_span,
)),
);
};
let pipeline = Pipeline::from_vec(vec![Expression {
expr: Expr::Call(call),
span: span(spans),
ty: Type::Any,
custom_completion: None,
}]);
let module_id = working_set.add_module(&overlay_name, Module::new());
working_set.add_overlay(
overlay_name.as_bytes().to_vec(),
module_id,
vec![],
vec![],
false,
);
(pipeline, None)
}
pub fn parse_overlay_use(
working_set: &mut StateWorkingSet,
spans: &[Span],
expand_aliases_denylist: &[usize],
) -> (Pipeline, Option<ParseError>) {
if spans.len() > 1 && working_set.get_span_contents(span(&spans[0..2])) != b"overlay use" {
return (
garbage_pipeline(spans),
Some(ParseError::UnknownState(
"internal error: Wrong call name for 'overlay use' command".into(),
span(spans),
)),
);
}
// TODO: Allow full import pattern as argument (requires custom naming of module/overlay)
let (call, call_span) = match working_set.find_decl(b"overlay use", &Type::Any) {
Some(decl_id) => {
let ParsedInternalCall {
call,
error: mut err,
output,
} = parse_internal_call(
working_set,
span(&spans[0..2]),
&spans[2..],
decl_id,
expand_aliases_denylist,
);
let decl = working_set.get_decl(decl_id);
let call_span = span(spans);
err = check_call(call_span, &decl.signature(), &call).or(err);
if err.is_some() || call.has_flag("help") {
return (
Pipeline::from_vec(vec![Expression {
expr: Expr::Call(call),
span: call_span,
ty: output,
custom_completion: None,
}]),
err,
);
}
(call, call_span)
}
None => {
return (
garbage_pipeline(spans),
Some(ParseError::UnknownState(
"internal error: 'overlay use' declaration not found".into(),
span(spans),
)),
)
}
};
let (overlay_name, overlay_name_span) = if let Some(expr) = call.positional_nth(0) {
if let Some(s) = expr.as_string() {
(s, expr.span)
} else {
return (
garbage_pipeline(spans),
Some(ParseError::UnknownState(
"internal error: Module name not a string".into(),
expr.span,
)),
);
}
} else {
return (
garbage_pipeline(spans),
Some(ParseError::UnknownState(
"internal error: Missing required positional after call parsing".into(),
call_span,
)),
);
};
let new_name = if let Some(kw_expression) = call.positional_nth(1) {
if let Some(new_name_expression) = kw_expression.as_keyword() {
if let Some(new_name) = new_name_expression.as_string() {
Some(Spanned {
item: new_name,
span: new_name_expression.span,
})
} else {
return (
garbage_pipeline(spans),
Some(ParseError::TypeMismatch(
Type::String,
new_name_expression.ty.clone(),
new_name_expression.span,
)),
);
}
} else {
return (
garbage_pipeline(spans),
Some(ParseError::ExpectedKeyword(
"as keyword".to_string(),
kw_expression.span,
)),
);
}
} else {
None
};
let has_prefix = call.has_flag("prefix");
let pipeline = Pipeline::from_vec(vec![Expression {
expr: Expr::Call(call.clone()),
span: span(spans),
ty: Type::Any,
custom_completion: None,
}]);
let cwd = working_set.get_cwd();
let mut error = None;
let (final_overlay_name, origin_module, origin_module_id, is_module_updated) = if let Some(
overlay_frame,
) =
working_set.find_overlay(overlay_name.as_bytes())
{
// Activate existing overlay
// First, check for errors
if has_prefix && !overlay_frame.prefixed {
return (
pipeline,
Some(ParseError::OverlayPrefixMismatch(
overlay_name,
"without".to_string(),
overlay_name_span,
)),
);
}
if !has_prefix && overlay_frame.prefixed {
return (
pipeline,
Some(ParseError::OverlayPrefixMismatch(
overlay_name,
"with".to_string(),
overlay_name_span,
)),
);
}
if let Some(new_name) = new_name {
if new_name.item != overlay_name {
return (
pipeline,
Some(ParseError::CantAddOverlayHelp(
format!("Cannot add overlay as '{}' because it already exsits under the name '{}'", new_name.item, overlay_name),
new_name.span,
)),
);
}
}
let module_id = overlay_frame.origin;
if let Some(new_module_id) = working_set.find_module(overlay_name.as_bytes()) {
if module_id == new_module_id {
(overlay_name, Module::new(), module_id, false)
} else {
// The origin module of an overlay changed => update it
(
overlay_name,
working_set.get_module(new_module_id).clone(),
new_module_id,
true,
)
}
} else {
(overlay_name, Module::new(), module_id, true)
}
} else {
// Create a new overlay from a module
if let Some(module_id) =
// the name is a module
working_set.find_module(overlay_name.as_bytes())
{
(
new_name.map(|spanned| spanned.item).unwrap_or(overlay_name),
working_set.get_module(module_id).clone(),
module_id,
true,
)
} else {
// try if the name is a file
if let Ok(module_filename) =
String::from_utf8(trim_quotes(overlay_name.as_bytes()).to_vec())
{
if let Some(module_path) =
find_in_dirs(&module_filename, working_set, &cwd, LIB_DIRS_ENV)
{
let overlay_name = if let Some(stem) = module_path.file_stem() {
stem.to_string_lossy().to_string()
} else {
return (
pipeline,
Some(ParseError::ModuleOrOverlayNotFound(spans[1])),
);
};
if let Ok(contents) = std::fs::read(&module_path) {
let span_start = working_set.next_span_start();
working_set.add_file(module_filename, &contents);
let span_end = working_set.next_span_start();
// Change currently parsed directory
let prev_currently_parsed_cwd = if let Some(parent) = module_path.parent() {
let prev = working_set.currently_parsed_cwd.clone();
working_set.currently_parsed_cwd = Some(parent.into());
prev
} else {
working_set.currently_parsed_cwd.clone()
};
let (block, module, err) = parse_module_block(
working_set,
Span::new(span_start, span_end),
expand_aliases_denylist,
);
error = error.or(err);
// Restore the currently parsed directory back
working_set.currently_parsed_cwd = prev_currently_parsed_cwd;
let _ = working_set.add_block(block);
let module_id = working_set.add_module(&overlay_name, module.clone());
(
new_name.map(|spanned| spanned.item).unwrap_or(overlay_name),
module,
module_id,
true,
)
} else {
return (
pipeline,
Some(ParseError::ModuleOrOverlayNotFound(spans[1])),
);
}
} else {
return (
pipeline,
Some(ParseError::ModuleOrOverlayNotFound(overlay_name_span)),
);
}
} else {
return (garbage_pipeline(spans), Some(ParseError::NonUtf8(spans[1])));
}
}
};
let (decls_to_lay, aliases_to_lay) = if has_prefix {
(
origin_module.decls_with_head(final_overlay_name.as_bytes()),
origin_module.aliases_with_head(final_overlay_name.as_bytes()),
)
} else {
(origin_module.decls(), origin_module.aliases())
};
working_set.add_overlay(
final_overlay_name.as_bytes().to_vec(),
origin_module_id,
decls_to_lay,
aliases_to_lay,
has_prefix,
);
// Change the call argument to include the Overlay expression with the module ID
let mut call = call;
if let Some(overlay_expr) = call.positional_nth_mut(0) {
overlay_expr.expr = Expr::Overlay(if is_module_updated {
Some(origin_module_id)
} else {
None
});
} // no need to check for else since it was already checked
let pipeline = Pipeline::from_vec(vec![Expression {
expr: Expr::Call(call),
span: span(spans),
ty: Type::Any,
custom_completion: None,
}]);
(pipeline, error)
}
pub fn parse_overlay_hide(
working_set: &mut StateWorkingSet,
spans: &[Span],
expand_aliases_denylist: &[usize],
) -> (Pipeline, Option<ParseError>) {
if spans.len() > 1 && working_set.get_span_contents(span(&spans[0..2])) != b"overlay hide" {
return (
garbage_pipeline(spans),
Some(ParseError::UnknownState(
"internal error: Wrong call name for 'overlay hide' command".into(),
span(spans),
)),
);
}
let call = match working_set.find_decl(b"overlay hide", &Type::Any) {
Some(decl_id) => {
let ParsedInternalCall {
call,
error: mut err,
output,
} = parse_internal_call(
working_set,
span(&spans[0..2]),
&spans[2..],
decl_id,
expand_aliases_denylist,
);
let decl = working_set.get_decl(decl_id);
let call_span = span(spans);
err = check_call(call_span, &decl.signature(), &call).or(err);
if err.is_some() || call.has_flag("help") {
return (
Pipeline::from_vec(vec![Expression {
expr: Expr::Call(call),
span: call_span,
ty: output,
custom_completion: None,
}]),
err,
);
}
call
}
None => {
return (
garbage_pipeline(spans),
Some(ParseError::UnknownState(
"internal error: 'overlay hide' declaration not found".into(),
span(spans),
)),
)
}
};
let (overlay_name, overlay_name_span) = if let Some(expr) = call.positional_nth(0) {
if let Some(s) = expr.as_string() {
(s, expr.span)
} else {
return (
garbage_pipeline(spans),
Some(ParseError::UnknownState(
"internal error: Module name not a string".into(),
expr.span,
)),
);
}
} else {
(
String::from_utf8_lossy(working_set.last_overlay_name()).to_string(),
call.head,
)
};
let keep_custom = call.has_flag("keep-custom");
let pipeline = Pipeline::from_vec(vec![Expression {
expr: Expr::Call(call),
span: span(spans),
ty: Type::Any,
custom_completion: None,
}]);
if overlay_name == DEFAULT_OVERLAY_NAME {
return (
pipeline,
Some(ParseError::CantHideDefaultOverlay(
overlay_name,
overlay_name_span,
)),
);
}
if !working_set
.unique_overlay_names()
.contains(&overlay_name.as_bytes().to_vec())
{
return (
pipeline,
Some(ParseError::ActiveOverlayNotFound(overlay_name_span)),
);
}
if working_set.num_overlays() < 2 {
return (
pipeline,
Some(ParseError::CantRemoveLastOverlay(overlay_name_span)),
);
}
working_set.remove_overlay(overlay_name.as_bytes(), keep_custom);
(pipeline, None)
}
pub fn parse_let(
working_set: &mut StateWorkingSet,
spans: &[Span],
expand_aliases_denylist: &[usize],
) -> (Pipeline, Option<ParseError>) {
let name = working_set.get_span_contents(spans[0]);
if name == b"let" {
if let Some((span, err)) = check_name(working_set, spans) {
return (Pipeline::from_vec(vec![garbage(*span)]), Some(err));
}
if let Some(decl_id) = working_set.find_decl(b"let", &Type::Any) {
let cmd = working_set.get_decl(decl_id);
let call_signature = cmd.signature().call_signature();
if spans.len() >= 4 {
// This is a bit of by-hand parsing to get around the issue where we want to parse in the reverse order
// so that the var-id created by the variable isn't visible in the expression that init it
for span in spans.iter().enumerate() {
let item = working_set.get_span_contents(*span.1);
if item == b"=" && spans.len() > (span.0 + 1) {
let mut error = None;
let mut idx = span.0;
let (rvalue, err) = parse_multispan_value(
working_set,
spans,
&mut idx,
&SyntaxShape::Keyword(b"=".to_vec(), Box::new(SyntaxShape::Expression)),
expand_aliases_denylist,
);
error = error.or(err);
if idx < (spans.len() - 1) {
error = error.or(Some(ParseError::ExtraPositional(
call_signature,
spans[idx + 1],
)));
}
let mut idx = 0;
let (lvalue, err) =
parse_var_with_opt_type(working_set, &spans[1..(span.0)], &mut idx);
error = error.or(err);
let var_name =
String::from_utf8_lossy(working_set.get_span_contents(lvalue.span))
.to_string();
if ["in", "nu", "env", "nothing"].contains(&var_name.as_str()) {
error =
error.or(Some(ParseError::LetBuiltinVar(var_name, lvalue.span)));
}
let var_id = lvalue.as_var();
let rhs_type = rvalue.ty.clone();
if let Some(var_id) = var_id {
working_set.set_variable_type(var_id, rhs_type);
}
let call = Box::new(Call {
decl_id,
head: spans[0],
arguments: vec![
Argument::Positional(lvalue),
Argument::Positional(rvalue),
],
redirect_stdout: true,
redirect_stderr: false,
});
return (
Pipeline::from_vec(vec![Expression {
expr: Expr::Call(call),
span: nu_protocol::span(spans),
ty: Type::Any,
custom_completion: None,
}]),
error,
);
}
}
}
let ParsedInternalCall {
call,
error: err,
output,
} = parse_internal_call(
working_set,
spans[0],
&spans[1..],
decl_id,
expand_aliases_denylist,
);
return (
Pipeline {
expressions: vec![Expression {
expr: Expr::Call(call),
span: nu_protocol::span(spans),
ty: output,
custom_completion: None,
}],
},
err,
);
}
}
(
garbage_pipeline(spans),
Some(ParseError::UnknownState(
"internal error: let statement unparseable".into(),
span(spans),
)),
)
}
pub fn parse_source(
working_set: &mut StateWorkingSet,
spans: &[Span],
expand_aliases_denylist: &[usize],
) -> (Pipeline, Option<ParseError>) {
let mut error = None;
let name = working_set.get_span_contents(spans[0]);
if name == b"source" || name == b"source-env" {
let scoped = name == b"source-env";
if let Some(decl_id) = working_set.find_decl(name, &Type::Any) {
let cwd = working_set.get_cwd();
// Is this the right call to be using here?
// Some of the others (`parse_let`) use it, some of them (`parse_hide`) don't.
let ParsedInternalCall {
call,
error: err,
output,
} = parse_internal_call(
working_set,
spans[0],
&spans[1..],
decl_id,
expand_aliases_denylist,
);
error = error.or(err);
if error.is_some() || call.has_flag("help") {
return (
Pipeline::from_vec(vec![Expression {
expr: Expr::Call(call),
span: span(spans),
ty: output,
custom_completion: None,
}]),
error,
);
}
// Command and one file name
if spans.len() >= 2 {
let name_expr = working_set.get_span_contents(spans[1]);
let (filename, err) = unescape_unquote_string(name_expr, spans[1]);
if err.is_none() {
if let Some(path) = find_in_dirs(&filename, working_set, &cwd, LIB_DIRS_ENV) {
if let Ok(contents) = std::fs::read(&path) {
// Change currently parsed directory
let prev_currently_parsed_cwd = if let Some(parent) = path.parent() {
let prev = working_set.currently_parsed_cwd.clone();
working_set.currently_parsed_cwd = Some(parent.into());
prev
} else {
working_set.currently_parsed_cwd.clone()
};
// This will load the defs from the file into the
// working set, if it was a successful parse.
let (block, err) = parse(
working_set,
path.file_name().and_then(|x| x.to_str()),
&contents,
scoped,
expand_aliases_denylist,
);
// Restore the currently parsed directory back
working_set.currently_parsed_cwd = prev_currently_parsed_cwd;
if err.is_some() {
// Unsuccessful parse of file
return (
Pipeline::from_vec(vec![Expression {
expr: Expr::Call(call),
span: span(&spans[1..]),
ty: Type::Any,
custom_completion: None,
}]),
// Return the file parse error
err,
);
} else {
// Save the block into the working set
let block_id = working_set.add_block(block);
let mut call_with_block = call;
// FIXME: Adding this expression to the positional creates a syntax highlighting error
// after writing `source example.nu`
call_with_block.add_positional(Expression {
expr: Expr::Int(block_id as i64),
span: spans[1],
ty: Type::Any,
custom_completion: None,
});
return (
Pipeline::from_vec(vec![Expression {
expr: Expr::Call(call_with_block),
span: span(spans),
ty: Type::Any,
custom_completion: None,
}]),
None,
);
}
}
} else {
error = error.or(Some(ParseError::SourcedFileNotFound(filename, spans[1])));
}
} else {
return (garbage_pipeline(spans), Some(ParseError::NonUtf8(spans[1])));
}
}
return (
Pipeline::from_vec(vec![Expression {
expr: Expr::Call(call),
span: span(spans),
ty: Type::Any,
custom_completion: None,
}]),
error,
);
}
}
(
garbage_pipeline(spans),
Some(ParseError::UnknownState(
"internal error: source statement unparseable".into(),
span(spans),
)),
)
}
#[cfg(feature = "plugin")]
pub fn parse_register(
working_set: &mut StateWorkingSet,
spans: &[Span],
expand_aliases_denylist: &[usize],
) -> (Pipeline, Option<ParseError>) {
use nu_plugin::{get_signature, PluginDeclaration};
use nu_protocol::{engine::Stack, Signature};
let cwd = working_set.get_cwd();
// Checking that the function is used with the correct name
// Maybe this is not necessary but it is a sanity check
if working_set.get_span_contents(spans[0]) != b"register" {
return (
garbage_pipeline(spans),
Some(ParseError::UnknownState(
"internal error: Wrong call name for parse plugin function".into(),
span(spans),
)),
);
}
// Parsing the spans and checking that they match the register signature
// Using a parsed call makes more sense than checking for how many spans are in the call
// Also, by creating a call, it can be checked if it matches the declaration signature
let (call, call_span) = match working_set.find_decl(b"register", &Type::Any) {
None => {
return (
garbage_pipeline(spans),
Some(ParseError::UnknownState(
"internal error: Register declaration not found".into(),
span(spans),
)),
)
}
Some(decl_id) => {
let ParsedInternalCall {
call,
error: mut err,
output,
} = parse_internal_call(
working_set,
spans[0],
&spans[1..],
decl_id,
expand_aliases_denylist,
);
let decl = working_set.get_decl(decl_id);
let call_span = span(spans);
err = check_call(call_span, &decl.signature(), &call).or(err);
if err.is_some() || call.has_flag("help") {
return (
Pipeline::from_vec(vec![Expression {
expr: Expr::Call(call),
span: call_span,
ty: output,
custom_completion: None,
}]),
err,
);
}
(call, call_span)
}
};
// Extracting the required arguments from the call and keeping them together in a tuple
// The ? operator is not used because the error has to be kept to be printed in the shell
// For that reason the values are kept in a result that will be passed at the end of this call
let arguments = call
.positional_nth(0)
.map(|expr| {
let name_expr = working_set.get_span_contents(expr.span);
let (name, err) = unescape_unquote_string(name_expr, expr.span);
if let Some(err) = err {
Err(err)
} else {
let path = if let Some(p) = find_in_dirs(&name, working_set, &cwd, PLUGIN_DIRS_ENV)
{
p
} else {
return Err(ParseError::RegisteredFileNotFound(name, expr.span));
};
if path.exists() & path.is_file() {
Ok(path)
} else {
Err(ParseError::RegisteredFileNotFound(
format!("{:?}", path),
expr.span,
))
}
}
})
.expect("required positional has being checked");
// Signature is an optional value from the call and will be used to decide if
// the plugin is called to get the signatures or to use the given signature
let signature = call.positional_nth(1).map(|expr| {
let signature = working_set.get_span_contents(expr.span);
serde_json::from_slice::<Signature>(signature).map_err(|e| {
ParseError::LabeledError(
"Signature deserialization error".into(),
format!("unable to deserialize signature: {}", e),
spans[0],
)
})
});
// Shell is another optional value used as base to call shell to plugins
let shell = call.get_flag_expr("shell").map(|expr| {
let shell_expr = working_set.get_span_contents(expr.span);
String::from_utf8(shell_expr.to_vec())
.map_err(|_| ParseError::NonUtf8(expr.span))
.and_then(|name| {
canonicalize_with(&name, cwd)
.map_err(|_| ParseError::RegisteredFileNotFound(name, expr.span))
})
.and_then(|path| {
if path.exists() & path.is_file() {
Ok(path)
} else {
Err(ParseError::RegisteredFileNotFound(
format!("{:?}", path),
expr.span,
))
}
})
});
let shell = match shell {
None => None,
Some(path) => match path {
Ok(path) => Some(path),
Err(err) => {
return (
Pipeline::from_vec(vec![Expression {
expr: Expr::Call(call),
span: call_span,
ty: Type::Any,
custom_completion: None,
}]),
Some(err),
);
}
},
};
// We need the current environment variables for `python` based plugins
// Or we'll likely have a problem when a plugin is implemented in a virtual Python environment.
let stack = Stack::new();
let current_envs =
nu_engine::env::env_to_strings(working_set.permanent_state, &stack).unwrap_or_default();
let error = match signature {
Some(signature) => arguments.and_then(|path| {
// restrict plugin file name starts with `nu_plugin_`
let f_name = path
.file_name()
.map(|s| s.to_string_lossy().starts_with("nu_plugin_"));
if let Some(true) = f_name {
signature.map(|signature| {
let plugin_decl = PluginDeclaration::new(path, signature, shell);
working_set.add_decl(Box::new(plugin_decl));
working_set.mark_plugins_file_dirty();
})
} else {
Ok(())
}
}),
None => arguments.and_then(|path| {
// restrict plugin file name starts with `nu_plugin_`
let f_name = path
.file_name()
.map(|s| s.to_string_lossy().starts_with("nu_plugin_"));
if let Some(true) = f_name {
get_signature(path.as_path(), &shell, ¤t_envs)
.map_err(|err| {
ParseError::LabeledError(
"Error getting signatures".into(),
err.to_string(),
spans[0],
)
})
.map(|signatures| {
for signature in signatures {
// create plugin command declaration (need struct impl Command)
// store declaration in working set
let plugin_decl =
PluginDeclaration::new(path.clone(), signature, shell.clone());
working_set.add_decl(Box::new(plugin_decl));
}
working_set.mark_plugins_file_dirty();
})
} else {
Ok(())
}
}),
}
.err();
(
Pipeline::from_vec(vec![Expression {
expr: Expr::Call(call),
span: call_span,
ty: Type::Nothing,
custom_completion: None,
}]),
error,
)
}
/// This helper function is used to find files during parsing
///
/// First, the actual current working directory is selected as
/// a) the directory of a file currently being parsed
/// b) current working directory (PWD)
///
/// Then, if the file is not found in the actual cwd, NU_LIB_DIRS is checked.
/// If there is a relative path in NU_LIB_DIRS, it is assumed to be relative to the actual cwd
/// determined in the first step.
///
/// Always returns an absolute path
pub fn find_in_dirs(
filename: &str,
working_set: &StateWorkingSet,
cwd: &str,
dirs_env: &str,
) -> Option<PathBuf> {
// Choose whether to use file-relative or PWD-relative path
let actual_cwd = if let Some(currently_parsed_cwd) = &working_set.currently_parsed_cwd {
currently_parsed_cwd.as_path()
} else {
Path::new(cwd)
};
if let Ok(p) = canonicalize_with(filename, actual_cwd) {
Some(p)
} else {
let path = Path::new(filename);
if path.is_relative() {
if let Some(lib_dirs) = working_set.get_env_var(dirs_env) {
if let Ok(dirs) = lib_dirs.as_list() {
for lib_dir in dirs {
if let Ok(dir) = lib_dir.as_path() {
// make sure the dir is absolute path
if let Ok(dir_abs) = canonicalize_with(&dir, actual_cwd) {
if let Ok(path) = canonicalize_with(filename, dir_abs) {
return Some(path);
}
}
}
}
None
} else {
None
}
} else {
None
}
} else {
None
}
}
}
|
extern crate gl;
use gl::types::*;
use gl_buffer::*;
use gl_err::*;
use std::ptr;
pub struct GlVertexArray {
pub gl_handle : GLuint,
pub vertex_count : i32,
_vbs : Vec<GlBufferRaw>
}
pub struct GlVertexArrayTmp<'a> {
pub gl_handle : GLuint,
pub vertex_count : i32,
_vbs : Vec<&'a GlBufferRaw>
}
pub trait HasGlVertexArrayHandle {
fn gl_vao_handle(&self) -> GLuint;
}
impl GlVertexArray {
pub fn new(vbs : Vec<GlBufferRaw>) -> Result<GlVertexArray> {
let gl_handle = {
let vbs_ref: Vec<_> = vbs.iter().map(|a| a).collect();
gen_va(&vbs_ref[..])?
};
Ok(GlVertexArray {
gl_handle: gl_handle,
vertex_count: vbs[0].el_count as i32,
_vbs: vbs
})
}
}
impl<'a> GlVertexArrayTmp<'a> {
pub fn new(vbs : Vec<&'a GlBufferRaw>) -> Result<GlVertexArrayTmp<'a>> {
let gl_handle = gen_va(&vbs[..])?;
Ok(GlVertexArrayTmp {
gl_handle: gl_handle,
vertex_count: vbs[0].el_count as i32,
_vbs: vbs
})
}
}
impl HasGlVertexArrayHandle for GlVertexArray {
fn gl_vao_handle(&self) -> GLuint {
self.gl_handle
}
}
impl<'a> HasGlVertexArrayHandle for GlVertexArrayTmp<'a> {
fn gl_vao_handle(&self) -> GLuint {
self.gl_handle
}
}
impl Drop for GlVertexArray {
fn drop (&mut self) {
unsafe {
gl::DeleteVertexArrays(1, &self.gl_handle);
}
validate_gl().unwrap();
self.gl_handle = 0;
}
}
impl<'a> Drop for GlVertexArrayTmp<'a> {
fn drop (&mut self) {
unsafe {
gl::DeleteVertexArrays(1, &self.gl_handle);
}
validate_gl().unwrap();
self.gl_handle = 0;
}
}
fn gen_va(vbs : &[&GlBufferRaw]) -> Result<GLuint> {
unsafe {
let mut gl_handle : GLuint = 0;
gl::GenVertexArrays(1, &mut gl_handle);
gl::BindVertexArray(gl_handle);
for (i,vb) in vbs.iter().enumerate() {
gl::EnableVertexAttribArray(i as u32);
gl::BindBuffer(gl::ARRAY_BUFFER, vb.buffer_id);
gl::VertexAttribPointer(i as u32, vb.component_count as i32,
vb.gl_type_enum, gl::FALSE, 0, ptr::null());
}
match validate_gl() {
Err(s) => Err(s),
_ => Ok(gl_handle)
}
}
}
|
fn cholesky(mat: Vec<f64>, n: usize) -> Vec<f64> {
let mut res = vec![0.0; mat.len()];
for i in 0..n {
for j in 0..(i+1){
let mut s = 0.0;
for k in 0..j {
s += res[i * n + k] * res[j * n + k];
}
res[i * n + j] = if i == j { (mat[i * n + i] - s).sqrt() } else { (1.0 / res[j * n + j] * (mat[i * n + j] - s)) };
}
}
res
}
fn show_matrix(matrix: Vec<f64>, n: usize){
for i in 0..n {
for j in 0..n {
print!("{:.4}\t", matrix[i * n + j]);
}
println!("");
}
println!("");
}
fn main(){
let dimension = 3 as usize;
let m1 = vec![25.0, 15.0, -5.0,
15.0, 18.0, 0.0,
-5.0, 0.0, 11.0];
let res1 = cholesky(m1, dimension);
show_matrix(res1, dimension);
let dimension = 4 as usize;
let m2 = vec![18.0, 22.0, 54.0, 42.0,
22.0, 70.0, 86.0, 62.0,
54.0, 86.0, 174.0, 134.0,
42.0, 62.0, 134.0, 106.0];
let res2 = cholesky(m2, dimension);
show_matrix(res2, dimension);
} |
#![feature(plugin)]
#![plugin(rocket_codegen)]
#[macro_use]
extern crate serde_derive;
extern crate rocket;
extern crate serde_json;
mod lib;
use lib::direction::Direction;
use lib::point::Point;
use lib::robot::Robot;
static mut ROBOT: Robot = Robot {
facing: Direction::North,
position: Point { x: 0, y: 0 },
};
#[get("/")]
fn index() -> String {
unsafe { serde_json::to_string(&ROBOT).unwrap() }
}
#[get("/move")]
fn move_forward() -> String {
unsafe {
ROBOT.move_forward();
serde_json::to_string(&ROBOT).unwrap()
}
}
#[get("/right")]
fn right() -> String {
unsafe { serde_json::to_string(&ROBOT.turn_right()).unwrap() }
}
#[get("/left")]
fn left() -> String {
unsafe { serde_json::to_string(&ROBOT.turn_left()).unwrap() }
}
fn main() {
rocket::ignite()
.mount("/", routes![index, move_forward, right, left])
.launch();
}
|
use std::collections::HashMap;
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
}
fn serve_order() {}
mod front_of_house {
pub mod hosting {
pub fn add_to_waitlist() {}
fn seat_at_table() {}
}
mod serving {
fn take_order() {}
fn server_order() {}
fn take_payment() {}
}
}
mod back_of_house {
pub enum Appetizer {
Soup,
Salad,
}
pub struct Breakfast {
pub toast: String,
seasonal_fruit: String,
}
impl Breakfast {
pub fn summer(toast: &str) -> Breakfast {
Breakfast {
toast: String::from(toast),
seasonal_fruit: String::from("peach"),
}
}
}
fn fix_incorrect_order() {
cook_order();
super::serve_order();
}
fn cook_order() {}
}
pub fn eat_at_restaurant() {
// Absolute path
crate::front_of_house::hosting::add_to_waitlist();
// Relative path
front_of_house::hosting::add_to_waitlist();
let a = back_of_house::Appetizer::Soup;
let mut map = HashMap::new();
map.insert(1, String::from("asd"));
} |
use ::{ ActoxError, ActoxResult };
use ::std::{
ptr, collections::HashMap, any::Any,
sync::{ mpsc::Sender, Mutex, atomic::{ AtomicPtr, Ordering } }
};
/// A global `ActorPool` to register input-channels under a name
pub struct ActorPool;
impl ActorPool {
/// Registers a new `actor_input` under `name`
///
/// Parameters:
/// - `actor_input`: The input-channel to register
/// - `name`: The name under which the input-channel should be registered
///
/// Returns either _nothing_ or an `ActoxError::ExistsAlready` if an actor with the same `name`
/// is registered
pub fn register<T: Send + 'static>(actor_input: Sender<T>, name: impl ToString) -> ActoxResult<()> {
// Get pool instance
let mut pool = Self::pool().lock().unwrap();
// Insert sender
let name = name.to_string();
if !pool.contains_key(&name) { pool.insert(name, Box::new(actor_input)); }
else { throw_err!(ActoxError::ExistsAlready) }
Ok(())
}
/// Unregisters an input-channel
///
/// Parameter `name`: The name under which the input-channel to unregister was registered
///
/// Returns either _nothing_ or an `ActoxError::NotFound` if no input-channel with `name` was
/// registered
pub fn unregister(name: impl ToString) -> ActoxResult<()> {
// Get pool instance
let mut pool = Self::pool().lock().unwrap();
// Get and cast actor
some_or!(pool.remove(&name.to_string()), throw_err!(ActoxError::NotFound));
Ok(())
}
/// The currently registered actors
pub fn registered() -> Vec<String> {
// Get pool instance and clone keys
let pool = Self::pool().lock().unwrap();
pool.keys().map(|key| key.clone()).collect()
}
/// Sends a `message` to an input-channel registered under `name`
///
/// Parameters:
/// - `name`: The name under which the input-channel was registered
/// - `message`: The message to send to the input-channel
///
/// Returns either _nothing_ or a corresponding `ActoxError`
pub fn send<T: Send + 'static>(name: impl ToString, message: T) -> ActoxResult<()> {
// Get pool instance
let pool = Self::pool().lock().unwrap();
// Get and cast actor
let actor: &Box<Any> = some_or!(pool.get(&name.to_string()), throw_err!(ActoxError::NotFound));
let actor: &Sender<T> = some_or!(actor.as_ref().downcast_ref(), throw_err!(ActoxError::TypeMismatch));
// Send message
Ok(ok_or!(actor.send(message), throw_err!(ActoxError::EndpointNotConnected)))
}
/// The global event pool
fn pool() -> &'static Mutex<HashMap<String, Box<Any>>> {
static POOL: AtomicPtr<Mutex<HashMap<String, Box<Any>>>> =
AtomicPtr::new(ptr::null_mut());
POOL.compare_and_swap(
ptr::null_mut(),
Box::into_raw(Box::new(Mutex::new(HashMap::new()))),
Ordering::SeqCst
);
unsafe{ POOL.load(Ordering::SeqCst).as_ref().unwrap() }
}
} |
#![doc = "generated by AutoRust 0.1.0"]
#![allow(non_camel_case_types)]
#![allow(unused_imports)]
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ResourceIdentity {
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<resource_identity::Type>,
#[serde(rename = "principalId", default, skip_serializing_if = "Option::is_none")]
pub principal_id: Option<String>,
#[serde(rename = "tenantId", default, skip_serializing_if = "Option::is_none")]
pub tenant_id: Option<String>,
}
pub mod resource_identity {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Type {
None,
SystemAssigned,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AzureMonitorWorkspaceProperties {
#[serde(rename = "workspaceId", default, skip_serializing_if = "Option::is_none")]
pub workspace_id: Option<String>,
#[serde(rename = "workspaceResourceId", default, skip_serializing_if = "Option::is_none")]
pub workspace_resource_id: Option<String>,
#[serde(rename = "includeChangeDetails", default, skip_serializing_if = "Option::is_none")]
pub include_change_details: Option<ChangeDetailsMode>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ChangeDetailsMode {
None,
Include,
Exclude,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum NotificationsState {
None,
Enabled,
Disabled,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct NotificationSettings {
#[serde(rename = "azureMonitorWorkspaceProperties", default, skip_serializing_if = "Option::is_none")]
pub azure_monitor_workspace_properties: Option<AzureMonitorWorkspaceProperties>,
#[serde(rename = "activationState", default, skip_serializing_if = "Option::is_none")]
pub activation_state: Option<NotificationsState>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ConfigurationProfileResourceProperties {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub notifications: Option<NotificationSettings>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SystemData {
#[serde(rename = "createdBy", default, skip_serializing_if = "Option::is_none")]
pub created_by: Option<String>,
#[serde(rename = "createdByType", default, skip_serializing_if = "Option::is_none")]
pub created_by_type: Option<String>,
#[serde(rename = "createdAt", default, skip_serializing_if = "Option::is_none")]
pub created_at: Option<String>,
#[serde(rename = "lastModifiedBy", default, skip_serializing_if = "Option::is_none")]
pub last_modified_by: Option<String>,
#[serde(rename = "lastModifiedByType", default, skip_serializing_if = "Option::is_none")]
pub last_modified_by_type: Option<String>,
#[serde(rename = "lastModifiedAt", default, skip_serializing_if = "Option::is_none")]
pub last_modified_at: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ConfigurationProfileResource {
#[serde(flatten)]
pub extended_proxy_resource: ExtendedProxyResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub identity: Option<ResourceIdentity>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<ConfigurationProfileResourceProperties>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub location: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ExtendedProxyResource {
#[serde(flatten)]
pub proxy_resource: ProxyResource,
#[serde(rename = "systemData", default, skip_serializing_if = "Option::is_none")]
pub system_data: Option<SystemData>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ResourceProviderOperationDisplay {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub provider: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub resource: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub operation: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ResourceProviderOperationDefinition {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub display: Option<ResourceProviderOperationDisplay>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ResourceProviderOperationList {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<ResourceProviderOperationDefinition>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ErrorResponse {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error: Option<ErrorDetail>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ErrorDetail {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub code: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub target: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub details: Vec<ErrorDetail>,
#[serde(rename = "additionalInfo", default, skip_serializing_if = "Vec::is_empty")]
pub additional_info: Vec<ErrorAdditionalInfo>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ErrorAdditionalInfo {
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub info: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ProxyResource {
#[serde(flatten)]
pub resource: Resource,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Resource {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
}
|
use std::slice;
use std::io::{self, Write};
use byteorder::{
ByteOrder,
LittleEndian,
BigEndian,
WriteBytesExt
};
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
pub enum Endianness {
LittleEndian,
BigEndian
}
impl Endianness {
#[cfg( target_endian = "little" )]
pub const NATIVE: Endianness = Endianness::LittleEndian;
#[cfg( target_endian = "big" )]
pub const NATIVE: Endianness = Endianness::BigEndian;
}
impl Endianness {
#[inline(always)]
pub fn conversion_necessary( self ) -> bool {
self != Endianness::NATIVE
}
#[inline(always)]
pub fn swap_slice_u8( self, _: &mut [u8] ) {}
#[inline(always)]
pub fn swap_slice_i8( self, _: &mut [i8] ) {}
}
macro_rules! emit_wrapper {
($type:ty, $reader:ident, $stream_writer:ident, $swapper:ident, $slice_swapper:ident, $from_slice:ident, $write:ident) => {
impl Endianness {
#[inline]
pub fn $reader( self, slice: &[u8] ) -> $type {
match self {
Endianness::LittleEndian => LittleEndian::$reader( slice ),
Endianness::BigEndian => BigEndian::$reader( slice )
}
}
#[inline]
pub fn $stream_writer< S: Write + ?Sized >( self, stream: &mut S, value: $type ) -> io::Result< () > {
match self {
Endianness::LittleEndian => stream.$write::< LittleEndian >( value ),
Endianness::BigEndian => stream.$write::< BigEndian >( value )
}
}
#[inline]
pub fn $swapper( self, value: &mut $type ) {
let slice = unsafe { slice::from_raw_parts_mut( value as *mut $type, 1 ) };
self.$slice_swapper( slice );
}
#[inline]
pub fn $slice_swapper( self, slice: &mut [$type] ) {
match self {
Endianness::LittleEndian => LittleEndian::$from_slice( slice ),
Endianness::BigEndian => BigEndian::$from_slice( slice )
}
}
}
}
}
emit_wrapper!( u16, read_u16, write_to_stream_u16, swap_u16, swap_slice_u16, from_slice_u16, write_u16 );
emit_wrapper!( u32, read_u32, write_to_stream_u32, swap_u32, swap_slice_u32, from_slice_u32, write_u32 );
emit_wrapper!( u64, read_u64, write_to_stream_u64, swap_u64, swap_slice_u64, from_slice_u64, write_u64 );
emit_wrapper!( i16, read_i16, write_to_stream_i16, swap_i16, swap_slice_i16, from_slice_i16, write_i16 );
emit_wrapper!( i32, read_i32, write_to_stream_i32, swap_i32, swap_slice_i32, from_slice_i32, write_i32 );
emit_wrapper!( i64, read_i64, write_to_stream_i64, swap_i64, swap_slice_i64, from_slice_i64, write_i64 );
emit_wrapper!( f32, read_f32, write_to_stream_f32, swap_f32, swap_slice_f32, from_slice_f32, write_f32 );
emit_wrapper!( f64, read_f64, write_to_stream_f64, swap_f64, swap_slice_f64, from_slice_f64, write_f64 );
|
use anyhow::Result;
use log::{debug, error, info};
use osmpbfreader::objects::{Node, Way};
use osmpbfreader::{OsmObj, OsmPbfReader};
use rusqlite::{params, Connection, Statement};
use std::f64::consts::PI;
use std::fs::File;
use std::hash::{Hash, Hasher};
#[derive(Debug)]
pub struct Database {
conn: Connection,
filename: String,
}
#[derive(Debug, Clone)]
pub struct RouteNode {
id: i64,
pub lat: f64,
pub lon: f64,
}
impl Hash for RouteNode {
fn hash<H: Hasher>(&self, state: &mut H) {
self.id.hash(state);
}
}
impl PartialEq for RouteNode {
fn eq(&self, other: &Self) -> bool {
self.id == other.id
}
}
impl Eq for RouteNode {}
impl RouteNode {
pub fn distance_to(&self, other: &Self) -> i32 {
distance_between(self, other)
}
}
impl Database {
pub fn new(filename: &str) -> Result<Database> {
let db = Database {
conn: Connection::open(filename)?,
filename: filename.into(),
};
db.init()?;
db.fixup_quadkeys()?;
return Ok(db);
}
fn init(&self) -> Result<()> {
debug!("Initializing database");
self.conn.execute(
"CREATE TABLE IF NOT EXISTS nodes ( \
id INTEGER PRIMARY KEY, \
lat DOUBLE, \
lon DOUBLE, \
quadkey CHARACTER(10) \
)",
params![],
)?;
self.conn.execute(
"CREATE TABLE IF NOT EXISTS links ( \
id INTEGER PRIMARY KEY AUTOINCREMENT, \
source INTEGER, \
destination INTEGER, \
FOREIGN KEY(source) REFERENCES nodes(id), \
FOREIGN KEY(destination) REFERENCES nodes(id) \
)",
params![],
)?;
self.conn.execute(
"CREATE INDEX IF NOT EXISTS links_source ON links(source)",
params![],
)?;
self.conn.execute(
"CREATE INDEX IF NOT EXISTS links_destination ON links(destination)",
params![],
)?;
Ok(())
}
fn fixup_quadkeys(&self) -> Result<()> {
info!("Fixing quadkeys...");
let mut stmt = self
.conn
.prepare("SELECT id, lat, lon FROM nodes WHERE quadkey IS NULL")?;
let nodes_iter = stmt.query_map(params![], |row| {
let id: i64 = row.get(0)?;
let lat: f64 = row.get(1)?;
let lon: f64 = row.get(2)?;
let quadkey = super::quadkey::Quadkey::new(lat, lon, 13);
Ok((id, quadkey))
});
let mut stmt2 = self
.conn
.prepare("UPDATE nodes SET quadkey = ? WHERE id = ?")?;
let mut count = 0;
for res in nodes_iter? {
if let Ok((id, quadkey)) = res {
//debug!("Fix node {:?} with quadkey {:?}", id, quadkey.to_string());
count += 1;
stmt2.execute(params![quadkey.to_string(), id])?;
} else {
error!("Cannot fix quadkey: {:?}", res);
}
}
info!("Fixed {:?} quadkeys", count);
Ok(())
}
pub fn node_count(&self) -> Result<i64> {
let count: i64 = self
.conn
.query_row("SELECT count(*) FROM nodes", params![], |row| row.get(0))?;
Ok(count)
}
pub fn link_count(&self) -> Result<i64> {
let count: i64 = self
.conn
.query_row("SELECT count(*) FROM links", params![], |row| row.get(0))?;
Ok(count)
}
pub fn import(&self, filename: &str) -> Result<()> {
info!("Parsing OSM pbf {:?}...", filename);
let file = File::open(filename)?;
self.load_osm_pbf(file)?;
Ok(())
}
fn filter_object(&self, obj: &OsmObj) -> bool {
obj.is_way()
&& obj.tags().contains_key("waterway")
&& obj
.tags()
.values()
.any(|v| v == "river" || v == "stream" || v == "canal")
}
fn load_osm_pbf<T>(&self, input: T) -> Result<()>
where
T: std::io::Read + std::io::Seek,
{
let mut pbf = OsmPbfReader::new(input);
let objs = pbf.get_objs_and_deps(|x| self.filter_object(x))?;
info!("Updating database with {:?} objects...", objs.len());
self.conn.execute("BEGIN TRANSACTION", params![])?;
let mut node_stmt = self
.conn
.prepare("INSERT OR REPLACE INTO nodes (id, lat, lon, quadkey) VALUES (?, ?, ?, ?)")?;
let mut way_stmt = self
.conn
.prepare("INSERT OR REPLACE INTO links (source, destination) VALUES (?, ?)")?;
let mut count = 0;
for (_, obj) in &objs {
match obj {
OsmObj::Node(node) => {
let quadkey = super::quadkey::Quadkey::new(node.lat(), node.lon(), 13);
node_stmt.execute(params![
node.id.0,
node.lat(),
node.lon(),
quadkey.to_string()
])?;
}
OsmObj::Way(way) => {
for node_pair in way.nodes.windows(2) {
way_stmt.execute(params![node_pair[0].0, node_pair[1].0])?;
}
}
_ => (),
}
count += 1;
if count % 10000 == 0 {
info!("Updated {:?} objects so far", count);
self.conn.execute("COMMIT TRANSACTION", params![])?;
self.conn.execute("BEGIN TRANSACTION", params![])?;
}
}
self.conn.execute("COMMIT TRANSACTION", params![])?;
Ok(())
}
pub fn find_near(&self, lat: f64, lon: f64) -> Option<RouteNode> {
match self.find_near_err(lat, lon) {
Ok(node) => Some(node),
Err(_) => None,
}
}
fn find_near_err(&self, lat: f64, lon: f64) -> Result<RouteNode> {
// compute quadkey, find all nodes near, sort by distance, pick first
debug!("Looking for node near {:?} {:?}", lat, lon);
let quadkey = super::quadkey::Quadkey::new(lat, lon, 12);
debug!("Quadkey: {:?}", quadkey);
let mut stmt = self
.conn
//.prepare("SELECT id, lat, lon FROM nodes WHERE substr(quadkey, 1, ?) = ?")?;
.prepare("SELECT id, lat, lon FROM nodes WHERE lat >= ? AND lat <= ? AND lon >= ? AND lon <= ?")?;
let nodes_iter = stmt
//.query_map(params![12, quadkey.to_string()], |row| {
.query_map(
params![lat - 0.01, lat + 0.01, lon - 0.01, lon + 0.01],
|row| {
Ok(RouteNode {
id: row.get(0)?,
lat: row.get(1)?,
lon: row.get(2)?,
})
},
)?
.map(|n| n.unwrap());
let goal = RouteNode {
id: 0,
lat: lat,
lon: lon,
};
let min_node = nodes_iter.min_by(|a, b| {
let dist_a = distance_between(a, &goal);
let dist_b = distance_between(b, &goal);
dist_a.cmp(&dist_b)
});
debug!("min node: {:?}", min_node);
if min_node.is_some() {
let m = min_node.unwrap();
debug!("distance: {:?}", distance_between(&m, &goal));
return Ok(m);
} else {
return Err(anyhow!("No node near {:?} {:?}", lat, lon));
}
//return min_node.ok_or(anyhow!("No node near {:?} {:?}", lat, lon));
}
pub fn neighbours(&self, node: &RouteNode) -> Vec<(RouteNode, i32)> {
self.neighbours_res(node).unwrap_or(Vec::new())
}
fn neighbours_res(&self, node: &RouteNode) -> Result<Vec<(RouteNode, i32)>> {
let mut stmt_src = self.conn.prepare(
"SELECT n.id, n.lat, n.lon FROM links l
left join nodes n on l.destination = n.id
where l.source = ?",
)?;
let mut stmt_dst = self.conn.prepare(
"SELECT n.id, n.lat, n.lon FROM links l
left join nodes n on l.source = n.id
where l.destination = ?",
)?;
let nodes_iter = stmt_src
.query_map(params![node.id], |row| {
Ok(RouteNode {
id: row.get(0)?,
lat: row.get(1)?,
lon: row.get(2)?,
})
})?
.chain(stmt_dst.query_map(params![node.id], |row| {
Ok(RouteNode {
id: row.get(0)?,
lat: row.get(1)?,
lon: row.get(2)?,
})
})?)
.filter(|n| n.is_ok())
.map(|n| n.unwrap())
.map(|n| (n.clone(), distance_between(&node, &n)))
.collect();
return Ok(nodes_iter);
}
}
fn distance_between(a: &RouteNode, b: &RouteNode) -> i32 {
let r = 6371e3; // metres
let phi1 = (a.lat * PI) / 180.0; // φ, λ in radians
let phi2 = (b.lat * PI) / 180.0;
let delta_phi = ((b.lat - a.lat) * PI) / 180.0;
let delta_lambda = ((b.lon - a.lon) * PI) / 180.0;
let a = (delta_phi / 2.0).sin() * (delta_phi / 2.0).sin()
+ phi1.cos() * phi2.cos() * (delta_lambda / 2.0).sin() * (delta_lambda / 2.0).sin();
let c = 2.0 * (a.sqrt().atan2((1.0 - a).sqrt()));
let d = r * c; // in metres
return d.round() as i32;
}
|
use std::{
cell::{Ref, RefCell},
rc::Rc,
};
#[derive(Clone)]
pub struct Atom<T> {
value: Rc<RefCell<T>>,
subscribers: Rc<RefCell<Vec<Subscriber>>>,
}
impl<T> Atom<T> {
pub fn new(initial: T) -> Self {
Self {
value: Rc::new(RefCell::new(initial)),
subscribers: Rc::new(RefCell::new(Vec::new())),
}
}
pub fn get(&self) -> Ref<'_, T> {
CURRENT_REACTION.with(|current_reaction| {
if let Some(current_reaction) = &mut *current_reaction.borrow_mut() {
current_reaction.sources.push(self.subscribers.clone());
}
});
self.value.borrow()
}
pub fn set(&self, value: T) {
*self.value.borrow_mut() = value;
for subscriber in &*self.subscribers.borrow() {
subscriber.borrow()();
}
}
}
type Subscriber = Rc<RefCell<dyn Fn()>>;
pub fn react(f: impl Fn() + 'static) {
CURRENT_REACTION.with(|current_reaction| {
let mut current_reaction = current_reaction.borrow_mut();
assert!(current_reaction.is_none());
*current_reaction = Some(Reaction::new());
});
f();
let sources = CURRENT_REACTION.with(|current_reaction| {
let mut current_reaction = current_reaction.borrow_mut();
let reaction = current_reaction.take().unwrap();
reaction.sources
});
let f = Rc::new(RefCell::new(f));
for source in sources {
source.borrow_mut().push(f.clone());
}
}
struct Reaction {
sources: Vec<Rc<RefCell<Vec<Subscriber>>>>,
}
impl Reaction {
pub fn new() -> Self {
Reaction {
sources: Vec::new(),
}
}
}
thread_local! {
static CURRENT_REACTION: RefCell<Option<Reaction>> = RefCell::new(None);
}
|
pub const GRID_SIZE: (i16, i16) = (30, 20);
pub const GRID_CELL_SIZE: (i16, i16) = (40, 40);
pub const SCREEN_SIZE: (f32, f32) = (
GRID_SIZE.0 as f32 * GRID_CELL_SIZE.0 as f32,
GRID_SIZE.1 as f32 * GRID_CELL_SIZE.1 as f32,
);
pub const UPDATES_PER_SECOND: f32 = 10.0;
pub const MILLIS_PER_UPDATE: u64 = (1.0 / UPDATES_PER_SECOND * 1000.0) as u64;
|
use std::collections::HashMap;
use std::collections::hash_map::Entry::{Vacant, Occupied};
use std::hash;
pub fn create_or_increment<A: Eq + hash::Hash>(hash: &mut HashMap<A, i64>, key: A) {
match hash.entry(key) {
Vacant(e) => { e.insert(1); },
Occupied(mut e) => { *e.get_mut() += 1 },
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_vacant() {
let mut map = HashMap::<String, i64>::new();
create_or_increment(&mut map, "test".into());
assert_eq!(*map.get("test").unwrap(), 1);
}
#[test]
fn test_occupied() {
let mut map = HashMap::<String, i64>::new();
map.insert("test".into(), 100);
create_or_increment(&mut map, "test".into());
assert_eq!(*map.get("test").unwrap(), 101);
}
}
|
mod cli;
mod parser;
use cli::Cli;
use structopt::StructOpt;
use chrono::prelude::*;
use chrono::{Duration, Utc};
use std::collections::VecDeque;
const EARTH_RADIUS_IN_METERS: f32 = 6_371_000.0;
fn main() {
let args = Cli::from_args();
let coordinates = parser::process(&args.input);
let mut distances = Vec::with_capacity(coordinates.len() - 1);
for (index, element) in coordinates.iter().enumerate() {
if index + 1 >= coordinates.len() { break; }
let distance = distance_in_meters(element, &coordinates[index + 1]);
distances.push(distance);
}
let speed_in_mps = (0.277778 * args.speed).round() as u32;
let mut time_stamps = generate_timestamps(distances, speed_in_mps);
parser::write(&mut time_stamps, &args.input, args.output);
}
fn distance_in_meters(point1: &(f32, f32), point2: &(f32, f32)) -> u32 {
let lat1_rad = point1.0.to_radians();
let lat2_rad = point2.0.to_radians();
let lat_diff_rad = (point2.0 - point1.0).to_radians();
let long_diff_rad = (point2.1 - point1.1).to_radians();
let a = f32::sin(lat_diff_rad/2.0).powi(2) + f32::cos(lat1_rad) * f32::cos(lat2_rad) * f32::sin(long_diff_rad/2.0).powi(2);
let distance = f32::atan2(f32::sqrt(a), f32::sqrt(1.0-a)) * 2.0;
return (distance * EARTH_RADIUS_IN_METERS) as u32;
}
fn generate_timestamps(distances: Vec<u32>, speed: u32) -> VecDeque<DateTime<Utc>> {
let mut time_stamps = VecDeque::with_capacity(distances.len() + 1);
time_stamps.push_back(Utc::now());
for (index, distance) in distances.iter().enumerate() {
let time = distance / speed;
let new_time = time_stamps[index] + Duration::seconds(time as i64);
time_stamps.push_back(new_time);
}
return time_stamps
}
|
fn main() {
let _s1 = gives_ownership();
let s2 = String::from("Hello");
let _s3 = takes_and_gives_back(s2);
} // here, drop will only be called on _s1 and _s3 as s2 ownership was moved
fn gives_ownership() -> String {
let s = String::from("Hello");
s
}
fn takes_and_gives_back(s: String) -> String {
s
}
|
fn main() {
println!("Sort numbers in descending order");
let mut numbers = [4, 65, 2, -31, 0, 99, 2, 83, 782, 1];
println!("Before: {:?}", numbers);
quick_sort(&mut numbers, &|x,y| x > y);
println!("After: {:?}\n", numbers);
println!("Sort strings alphabetically");
let mut strings = ["beach", "hotel", "airplane", "car", "house", "art"];
println!("Before: {:?}", strings);
quick_sort(&mut strings, &|x,y| x < y);
println!("After: {:?}\n", strings);
println!("Sort strings by length");
println!("Before: {:?}", strings);
quick_sort(&mut strings, &|x,y| x.len() < y.len());
println!("After: {:?}", strings);
}
fn quick_sort<T,F>(v: &mut [T], f: &F)
where F: Fn(&T,&T) -> bool
{
let len = v.len();
if len >= 2 {
let pivot_index = partition(v, f);
quick_sort(&mut v[0..pivot_index], f);
quick_sort(&mut v[pivot_index + 1..len], f);
}
}
fn partition<T,F>(v: &mut [T], f: &F) -> usize
where F: Fn(&T,&T) -> bool
{
let len = v.len();
let pivot_index = len / 2;
let last_index = len - 1;
v.swap(pivot_index, last_index);
let mut store_index = 0;
for i in 0..last_index {
if f(&v[i], &v[last_index]) {
v.swap(i, store_index);
store_index += 1;
}
}
v.swap(store_index, len - 1);
store_index
} |
#[derive(PartialEq, Eq, Debug)]
pub enum MessageMethod {
Binding,
Custom(u16),
}
impl MessageMethod {
pub fn from(value: u16) -> MessageMethod {
// make sure the value is at most 12 bits length
if value & 0xFFF != value {
panic!(format!("invalid method value: {}", value))
}
match value {
1 => MessageMethod::Binding,
v => MessageMethod::Custom(v),
}
}
pub fn value(&self) -> u16 {
match self {
MessageMethod::Binding => 0x0001,
MessageMethod::Custom(v) => *v,
}
}
}
mod test {
#[test]
fn can_deserialize_binding_method() {
use super::*;
assert_eq!(MessageMethod::from(1), MessageMethod::Binding);
}
}
|
use std::io::Write;
use serde::de::value::Error;
use serde::ser::{self, Impossible};
use serde::Serialize;
use internal::gob::{Message, Writer};
use internal::types::TypeId;
use internal::utils::Bow;
use schema::Schema;
mod serialize_struct;
pub(crate) use self::serialize_struct::SerializeStructValue;
mod serialize_seq;
pub(crate) use self::serialize_seq::SerializeSeqValue;
mod serialize_tuple;
pub(crate) use self::serialize_tuple::SerializeTupleValue;
mod serialize_map;
pub(crate) use self::serialize_map::SerializeMapValue;
mod serialize_variant;
pub(crate) use self::serialize_variant::{SerializeStructVariantValue, SerializeVariantValue};
mod serialize_wire_types;
pub(crate) use self::serialize_wire_types::SerializeWireTypes;
pub(crate) struct SerializationOk<'t> {
pub ctx: SerializationCtx<'t>,
pub is_empty: bool,
}
pub(crate) struct SerializationCtx<'t> {
pub schema: Bow<'t, Schema>,
pub value: Message<Vec<u8>>,
}
impl<'t> SerializationCtx<'t> {
pub(crate) fn new() -> Self {
SerializationCtx::with_schema(Bow::Owned(Schema::new()))
}
pub(crate) fn with_schema(schema: Bow<'t, Schema>) -> Self {
SerializationCtx {
schema,
value: Message::new(Vec::new()),
}
}
pub(crate) fn flush<W: Write>(
&mut self,
type_id: TypeId,
mut writer: Writer<W>,
) -> Result<(), Error> {
self.schema.write_pending(writer.borrow_mut())?;
writer.write_section(type_id.0, self.value.get_ref())?;
Ok(())
}
}
pub(crate) struct FieldValueSerializer<'t> {
pub ctx: SerializationCtx<'t>,
pub type_id: TypeId,
}
impl<'t> FieldValueSerializer<'t> {
fn check_type(&self, got: TypeId) -> Result<(), Error> {
if self.type_id != got {
Err(ser::Error::custom(format!(
"type id mismatch: got {}, expected {}",
got.0, self.type_id.0
)))
} else {
Ok(())
}
}
}
impl<'t> ser::Serializer for FieldValueSerializer<'t> {
type Ok = SerializationOk<'t>;
type Error = Error;
type SerializeSeq = SerializeSeqValue<'t>;
type SerializeTuple = SerializeTupleValue<'t>;
type SerializeTupleStruct = Impossible<Self::Ok, Self::Error>;
type SerializeTupleVariant = Impossible<Self::Ok, Self::Error>;
type SerializeMap = SerializeMapValue<'t>;
type SerializeStruct = SerializeStructValue<'t>;
type SerializeStructVariant = SerializeStructVariantValue<'t>;
#[inline]
fn serialize_bool(mut self, v: bool) -> Result<Self::Ok, Self::Error> {
self.check_type(TypeId::BOOL)?;
self.ctx.value.write_bool(v)?;
Ok(SerializationOk {
ctx: self.ctx,
is_empty: v == true,
})
}
fn serialize_i8(self, v: i8) -> Result<Self::Ok, Self::Error> {
self.serialize_i64(v as i64)
}
fn serialize_i16(self, v: i16) -> Result<Self::Ok, Self::Error> {
self.serialize_i64(v as i64)
}
fn serialize_i32(self, v: i32) -> Result<Self::Ok, Self::Error> {
self.serialize_i64(v as i64)
}
fn serialize_i64(mut self, v: i64) -> Result<Self::Ok, Self::Error> {
self.check_type(TypeId::INT)?;
self.ctx.value.write_int(v)?;
Ok(SerializationOk {
ctx: self.ctx,
is_empty: v == 0,
})
}
fn serialize_u8(self, v: u8) -> Result<Self::Ok, Self::Error> {
self.serialize_u64(v as u64)
}
fn serialize_u16(self, v: u16) -> Result<Self::Ok, Self::Error> {
self.serialize_u64(v as u64)
}
fn serialize_u32(self, v: u32) -> Result<Self::Ok, Self::Error> {
self.serialize_u64(v as u64)
}
fn serialize_u64(mut self, v: u64) -> Result<Self::Ok, Self::Error> {
self.check_type(TypeId::UINT)?;
self.ctx.value.write_uint(v)?;
Ok(SerializationOk {
ctx: self.ctx,
is_empty: v == 0,
})
}
fn serialize_f32(self, v: f32) -> Result<Self::Ok, Self::Error> {
self.serialize_f64(v as f64)
}
fn serialize_f64(mut self, v: f64) -> Result<Self::Ok, Self::Error> {
self.check_type(TypeId::FLOAT)?;
self.ctx.value.write_float(v)?;
Ok(SerializationOk {
ctx: self.ctx,
is_empty: false,
})
}
fn serialize_char(self, v: char) -> Result<Self::Ok, Self::Error> {
self.serialize_i64(v as i64)
}
fn serialize_str(mut self, v: &str) -> Result<Self::Ok, Self::Error> {
self.check_type(TypeId::STRING)?;
self.ctx.value.write_bytes(v.as_bytes())?;
Ok(SerializationOk {
ctx: self.ctx,
is_empty: v.len() == 0,
})
}
fn serialize_bytes(mut self, v: &[u8]) -> Result<Self::Ok, Self::Error> {
self.check_type(TypeId::BYTES)?;
self.ctx.value.write_bytes(v)?;
Ok(SerializationOk {
ctx: self.ctx,
is_empty: v.len() == 0,
})
}
fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
Err(ser::Error::custom("not implemented yet"))
}
fn serialize_some<T: ?Sized>(self, _value: &T) -> Result<Self::Ok, Self::Error>
where
T: Serialize,
{
Err(ser::Error::custom("not implemented yet"))
}
fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
Err(ser::Error::custom("not implemented yet"))
}
fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok, Self::Error> {
Err(ser::Error::custom("not implemented yet"))
}
fn serialize_unit_variant(
self,
_name: &'static str,
_variant_index: u32,
_variant: &'static str,
) -> Result<Self::Ok, Self::Error> {
Err(ser::Error::custom("not implemented yet"))
}
fn serialize_newtype_struct<T: ?Sized>(
self,
_name: &'static str,
_value: &T,
) -> Result<Self::Ok, Self::Error>
where
T: Serialize,
{
Err(ser::Error::custom("not implemented yet"))
}
fn serialize_newtype_variant<T: ?Sized>(
self,
_name: &'static str,
variant_index: u32,
_variant: &'static str,
value: &T,
) -> Result<Self::Ok, Self::Error>
where
T: Serialize,
{
let ser = SerializeVariantValue::new(self.ctx, self.type_id, variant_index)?;
ser.serialize_newtype(value)
}
fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
SerializeSeqValue::new(self.ctx, len, self.type_id)
}
fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple, Self::Error> {
SerializeTupleValue::homogeneous(self.ctx, self.type_id)
}
fn serialize_tuple_struct(
self,
_name: &'static str,
_len: usize,
) -> Result<Self::SerializeTupleStruct, Self::Error> {
Err(ser::Error::custom("not implemented yet"))
}
fn serialize_tuple_variant(
self,
_name: &'static str,
_variant_index: u32,
_variant: &'static str,
_len: usize,
) -> Result<Self::SerializeTupleVariant, Self::Error> {
Err(ser::Error::custom("tuple variants not implemented yet"))
}
fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
SerializeMapValue::new(self.ctx, len, self.type_id)
}
fn serialize_struct(
self,
_name: &'static str,
_len: usize,
) -> Result<Self::SerializeStruct, Self::Error> {
SerializeStructValue::new(self.ctx, self.type_id)
}
fn serialize_struct_variant(
self,
_name: &'static str,
variant_index: u32,
_variant: &'static str,
_len: usize,
) -> Result<Self::SerializeStructVariant, Self::Error> {
let ser = SerializeVariantValue::new(self.ctx, self.type_id, variant_index)?;
ser.serialize_struct()
}
}
|
use {
Clipboard,
errors::{ClipboardError, WinError},
clipboard_metadata::{WinContentType, ClipboardContentType}
};
use clipboard_win::{
Clipboard as SystemClipboard,
raw::is_format_avail,
};
pub struct WindowsClipboard { }
impl Clipboard for WindowsClipboard {
type Output = Self;
fn new() -> Result<Self::Output, ClipboardError> {
Ok(WindowsClipboard { })
}
fn get_contents(&self)
-> Result<(Vec<u8>, ClipboardContentType), ClipboardError>
{
let clipboard = SystemClipboard::new()?;
let mut format = WinContentType::Bitmap;
loop {
if is_format_avail(format.into()) {
let format_size = match clipboard.size(format.into()) {
Some(s) => s,
None => return Err(WinError::FormatNoSize.into()),
};
let mut vec = vec![0; format_size];
clipboard.get(format.into(), &mut vec)?;
return Ok((vec, ClipboardContentType::WinContentType(format)));
} else {
match format.next() {
Some(f) => format = f,
None => return Err(WinError::EmptyClipboard.into()),
}
}
}
}
fn get_string_contents(&self)
-> Result<String, ClipboardError>
{
SystemClipboard::new()?.get_string().map_err(|e| e.into())
}
fn set_contents(&self, contents: Vec<u8>, format: ClipboardContentType)
-> Result<(), ClipboardError>
{
let win_content_type = match format {
ClipboardContentType::WinContentType(w) => w,
};
SystemClipboard::new()?.set(win_content_type.into(), &contents).map_err(|e| e.into())
}
fn set_string_contents(&self, contents: String)
-> Result<(), ClipboardError>
{
SystemClipboard::new()?.set_string(&contents).map_err(|e| e.into())
}
} |
fn main() {
proconio::input! {
n: i32,
r: i32,
}
if n >= 10 {
println!("{}", r);
}else{
println!("{}", r + 100 * (10 - n));
}
} |
use crate::{
diagnostics::Diagnostics,
dirgraphsvg::edges::{EdgeType, SingleEdge},
};
use serde::Deserialize;
use std::collections::{BTreeMap, BTreeSet, HashMap};
pub mod check;
pub mod validation;
///
/// The main struct of this program
/// It describes a GSN element
///
#[derive(Debug, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GsnNode {
pub(crate) text: String,
pub(crate) in_context_of: Option<Vec<String>>,
pub(crate) supported_by: Option<Vec<String>>,
pub(crate) undeveloped: Option<bool>,
pub(crate) classes: Option<Vec<String>>,
pub(crate) url: Option<String>,
pub(crate) level: Option<String>,
#[serde(flatten)]
pub(crate) additional: BTreeMap<String, String>,
#[serde(skip_deserializing)]
pub(crate) module: String,
}
impl GsnNode {
pub fn get_edges(&self) -> Vec<(String, EdgeType)> {
let mut edges = Vec::new();
if let Some(c_nodes) = &self.in_context_of {
let mut es: Vec<(String, EdgeType)> = c_nodes
.iter()
.map(|target| (target.to_owned(), EdgeType::OneWay(SingleEdge::InContextOf)))
.collect();
edges.append(&mut es);
}
if let Some(s_nodes) = &self.supported_by {
let mut es: Vec<(String, EdgeType)> = s_nodes
.iter()
.map(|target| (target.to_owned(), EdgeType::OneWay(SingleEdge::SupportedBy)))
.collect();
edges.append(&mut es);
}
edges
}
}
#[derive(Debug, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ModuleInformation {
pub(crate) name: String,
pub(crate) brief: Option<String>,
pub(crate) extends: Option<Vec<ExtendsModule>>,
#[serde(flatten)]
pub(crate) additional: BTreeMap<String, String>,
}
#[derive(Debug, Deserialize)]
#[serde(untagged)]
pub enum GsnDocumentNode {
GsnNode(GsnNode),
ModuleInformation(ModuleInformation),
}
#[derive(Default)]
pub struct Module {
pub relative_module_path: String,
pub meta: ModuleInformation,
}
#[derive(Debug, Deserialize)]
pub struct ExtendsModule {
pub module: String,
pub develops: BTreeMap<String, Vec<String>>,
}
///
///
///
///
pub fn extend_modules(
diags: &mut Diagnostics,
nodes: &mut BTreeMap<String, GsnNode>,
modules: &HashMap<String, Module>,
) {
for (module_name, module_info) in modules {
if let Some(extensions) = &module_info.meta.extends {
for ext in extensions {
if !modules.contains_key(&ext.module) {
diags.add_error(
Some(module_name),
format!("C09: Module {} is not found, but is supposed to be extended by module {}.", ext.module, module_name),
);
}
for (foreign_id, local_ids) in &ext.develops {
if let Some(foreign_node) = nodes.get_mut(foreign_id) {
if foreign_node.module != ext.module {
diags.add_error(
Some(module_name),
format!("C10: Element {} does not exist in module {}, but is supposed to be extended by {}.", foreign_id, ext.module, local_ids.join(",")),
);
} else if foreign_node.undeveloped != Some(true) {
diags.add_error(
Some(module_name),
format!("C10: Element {} is not undeveloped, but is supposed to be extended by {}.", foreign_id, local_ids.join(",")),
);
} else {
foreign_node.supported_by = Some(local_ids.to_vec());
foreign_node.undeveloped = Some(false);
}
} else {
diags.add_error(
Some(module_name),
format!("C10: Element {} does not exist, but is supposed to be extended by {}.", foreign_id, local_ids.join(",")),
);
}
}
}
}
}
}
///
/// Get root nodes
/// These are the unreferenced nodes.
///
fn get_root_nodes(nodes: &BTreeMap<String, GsnNode>) -> Vec<String> {
// Usage of BTreeSet, since root nodes might be used in output and that should be deterministic
let mut root_nodes: BTreeSet<String> = nodes.keys().cloned().collect();
for node in nodes.values() {
// Remove all keys if they are referenced; used to see if there is more than one top level node
if let Some(context) = node.in_context_of.as_ref() {
for cnode in context {
root_nodes.remove(cnode);
}
}
if let Some(support) = node.supported_by.as_ref() {
for snode in support {
root_nodes.remove(snode);
}
}
}
Vec::from_iter(root_nodes)
}
///
/// Gathers all different 'level' attributes from all nodes.
///
pub fn get_levels(nodes: &BTreeMap<String, GsnNode>) -> BTreeMap<&str, Vec<&str>> {
let mut levels = BTreeMap::<&str, Vec<&str>>::new();
for (id, node) in nodes.iter() {
if let Some(l) = &node.level {
levels.entry(l.trim()).or_default().push(id);
}
}
levels
}
///
/// Calculate module dependencies
/// Check if a dependency in one direction is already known, then only modify the existing one.
///
///
pub fn calculate_module_dependencies(
nodes: &BTreeMap<String, GsnNode>,
) -> BTreeMap<String, BTreeMap<String, EdgeType>> {
let mut res = BTreeMap::<String, BTreeMap<String, EdgeType>>::new();
for v in nodes.values() {
if let Some(sups) = &v.supported_by {
add_dependencies(sups, nodes, v, &mut res, SingleEdge::SupportedBy);
}
if let Some(ctxs) = &v.in_context_of {
add_dependencies(ctxs, nodes, v, &mut res, SingleEdge::InContextOf);
}
}
// Create empty dummies for other modules.
for n in nodes.values() {
if let std::collections::btree_map::Entry::Vacant(e) = res.entry(n.module.to_owned()) {
e.insert(BTreeMap::new());
}
}
res
}
///
///
///
fn add_dependencies(
children: &Vec<String>,
nodes: &BTreeMap<String, GsnNode>,
cur_node: &GsnNode,
dependencies: &mut BTreeMap<String, BTreeMap<String, EdgeType>>,
dep_type: SingleEdge,
) {
for child in children {
// Unwrap is ok, since node names in `nodes` always exist
let other_module = &nodes.get(child).unwrap().module;
if &cur_node.module != other_module {
let oneway = dependencies
.get(&cur_node.module)
.map(|es| es.contains_key(other_module))
.unwrap_or(false);
let otherway = dependencies
.get(other_module)
.map(|es| es.contains_key(&cur_node.module))
.unwrap_or(false);
let mut oneway_module = &cur_node.module;
let mut otherway_module = other_module;
let mut normal_dir = true;
if oneway && !otherway {
// Default assignment
} else if otherway && !oneway {
oneway_module = other_module;
otherway_module = &cur_node.module;
normal_dir = false;
} else {
// What about both true? Cannot happen, since we covered this in the match statement below.
// Here, both are false
let e = dependencies.entry(cur_node.module.to_owned()).or_default();
e.entry(other_module.to_owned())
.or_insert(EdgeType::OneWay(dep_type));
}
// unwrap is ok, since oneway_module is either newly inserted (else-case above),
// or found in `dependencies` before the if-else if-else.
let e = dependencies.get_mut(oneway_module).unwrap();
e.entry(otherway_module.to_owned())
.and_modify(|x| {
*x = match &x {
EdgeType::OneWay(et) if normal_dir => EdgeType::OneWay(*et | dep_type),
EdgeType::OneWay(et) if !normal_dir => EdgeType::TwoWay((dep_type, *et)),
EdgeType::TwoWay((te, et)) if normal_dir => {
EdgeType::TwoWay((*te, *et | dep_type))
}
EdgeType::TwoWay((te, et)) if !normal_dir => {
EdgeType::TwoWay((*te | dep_type, *et))
}
_ => *x,
}
})
.or_insert(EdgeType::OneWay(dep_type));
}
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn no_level_exists() {
let mut nodes = BTreeMap::<String, GsnNode>::new();
nodes.insert("Sn1".to_owned(), Default::default());
let output = get_levels(&nodes);
assert!(output.is_empty());
}
#[test]
fn two_levels_exist() {
let mut nodes = BTreeMap::<String, GsnNode>::new();
nodes.insert(
"Sn1".to_owned(),
GsnNode {
level: Some("x1".to_owned()),
..Default::default()
},
);
nodes.insert(
"G1".to_owned(),
GsnNode {
level: Some("x2".to_owned()),
..Default::default()
},
);
let output = get_levels(&nodes);
assert_eq!(output.len(), 2);
assert!(output.contains_key(&"x1"));
assert!(output.contains_key(&"x2"));
}
}
|
const HELP: &str = r#"
ntbk is a terminal notebook manager.
Usage: ntbk [ACTION]
ntbk find <pattern> - Find notes by path
ntbk grep <pattern> - Search through notes content
ntbk help - Print this usage information
ntbk list - List all notes
ntbk new <name> - Create a new note with <name>
ntbk open <name> - Open a note
ntbk remove <name> - Remove a note
ntbk show <name> - Show a note's content
Arguments <name> and <pattern> are optional.
if none are provided, ntbk will prompt for a choice / input.
"#;
pub fn run() {
println!("{}", HELP);
}
|
//! Callbacks for the `screen` object in the Lua libraries
use ::luaA;
use ::lua::Lua;
use libc::c_int;
#[repr(C)]
pub struct ScreenState {
// TODO IMPLEMENT
}
#[allow(non_snake_case)]
pub trait Screen {
// Class Methods
fn screen_add_signal(&self, lua: &Lua) -> c_int;
fn screen_connect_signal(&self, lua: &Lua) -> c_int;
fn screen_disconnect_signal(&self, lua: &Lua) -> c_int;
fn screen_emit_signal(&self, lua: &Lua) -> c_int;
fn screen_instances(&self, lua: &Lua) -> c_int;
fn screen_set_index_miss_handler(&self, lua: &Lua) -> c_int;
fn screen_set_newindex_miss_handler(&self, lua: &Lua) -> c_int;
// Methods
fn screen_count(&self, lua: &Lua) -> c_int;
fn screen___index(&self, lua: &Lua) -> c_int;
fn screen___newindex(&self, lua: &Lua) -> c_int;
fn screen___call(&self, lua: &Lua) -> c_int;
fn screen_fake_add(&self, lua: &Lua) -> c_int;
// Object meta methods
fn screen___tostring_meta(&self, lua: &Lua) -> c_int {
unsafe {
luaA::object_tostring(lua.0)
}
}
fn screen_connect_signal_meta(&self, lua: &Lua) -> c_int {
unsafe {
luaA::object_connect_signal_simple(lua.0)
}
}
fn screen_disconnect_signal_meta(&self, lua: &Lua) -> c_int {
unsafe {
luaA::object_disconnect_signal_simple(lua.0)
}
}
// Class meta methods
fn screen___index_meta(&self, lua: &Lua) -> c_int {
unsafe {
luaA::class_index(lua.0)
}
}
fn screen___newindex_meta(&self, lua: &Lua) -> c_int {
unsafe {
luaA::class_newindex(lua.0)
}
}
// Meta methods
fn screen_fake_remove(&self, lua: &Lua) -> c_int;
fn screen_fake_resize(&self, lua: &Lua) -> c_int;
fn screen_swap(&self, lua: &Lua) -> c_int;
/* Properties */
properties!([
screen_geometry,
screen_index,
screen_outputs,
screen_workarea
]);
}
|
extern crate duktape;
use duktape::error::Result;
use duktape::prelude::*;
fn main() -> Result<()> {
let mut ctx = Context::new()?;
let mut builder = class::build();
let global: Object = ctx.push_global_object().getp()?;
builder.method(
"greet",
(1, |ctx: &Context, this: &mut class::Instance| {
let name = ctx.get::<String>(0)?;
ctx.push(format!("Hello {}", name))?;
Ok(1)
}),
);
global.set("Greeter", builder);
let greeting: String = ctx
.eval(
r#"
var greeter = new Greeter();
var greeting = greeter.greet('me');
greeting + '!';
"#,
)?
.get(-1)?;
assert_eq!(greeting, "Hello me!");
println!("{}", greeting);
let greeter: Object = ctx.get_global_string("Greeter").construct(0)?.getp();
println!("{}", greeter.call::<String>("greet", "eevee")?);
Ok(())
}
|
extern crate ispc;
use std::env;
use std::path::PathBuf;
fn main() {
let mut embree_include;
if let Ok(e) = env::var("EMBREE_DIR") {
embree_include = PathBuf::from(e);
embree_include.push("include");
} else {
println!("cargo:error=Please set EMBREE_DIR=<path to embree3 root>");
panic!("Failed to find embree");
}
println!("cargo:rerun-if-env-changed=EMBREE_DIR");
let mut cfg = ispc::Config::new();
let ispc_files = vec!["src/crescent.ispc"];
for s in &ispc_files[..] {
cfg.file(*s);
}
cfg.include_path(embree_include)
.optimization_opt(ispc::OptimizationOpt::FastMath)
.opt_level(2)
.compile("crescent");
}
|
use console::style;
use std::error::Error;
use std::path::{Path, PathBuf};
use std::{env, fs, io, process};
use itertools::Itertools;
use std::hash::{Hash, Hasher};
#[cfg(unix)]
use std::os::unix::fs::MetadataExt;
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;
fn find_in_path<F>(dir: &Path, predicate: &F) -> io::Result<PathBuf>
where
F: Fn(&fs::DirEntry) -> bool,
{
dir.read_dir()?
.filter_map(io::Result::ok)
.find(predicate)
.ok_or_else(|| {
io::Error::new(
io::ErrorKind::NotFound,
format!("Item not found in directory: {}", dir.display()),
)
}).map(|entry| entry.path())
}
#[cfg(unix)]
fn check_file(entry: &fs::DirEntry) -> io::Result<bool> {
let metadata = entry.metadata()?;
let file_name = entry.file_name();
let file_name = file_name.to_string_lossy();
if !metadata.is_dir() && file_name.starts_with("uvm-") {
let metadata = entry.path().metadata().unwrap();
let process = env::current_exe().unwrap();
let p_metadata = process.metadata().unwrap();
let p_uid = p_metadata.uid();
let p_gid = p_metadata.gid();
let is_user = metadata.uid() == p_uid;
let is_group = metadata.gid() == p_gid;
let permissions = metadata.permissions();
let mode = permissions.mode();
return Ok((mode & 0o0001) != 0
|| ((mode & 0o0010) != 0 && is_group)
|| ((mode & 0o0100) != 0 && is_user));
}
Ok(false)
}
#[cfg(windows)]
fn check_file(entry: &fs::DirEntry) -> io::Result<bool> {
let metadata = entry.metadata()?;
let file_name = entry.file_name();
let file_name = file_name.to_string_lossy();
trace!("file_name {}", file_name);
Ok(!metadata.is_dir() && file_name.starts_with("uvm-") && file_name.ends_with(".exe"))
}
pub fn find_commands_in_path(dir: &Path) -> io::Result<Box<dyn Iterator<Item = PathBuf>>> {
let result = dir
.read_dir()?
.filter_map(io::Result::ok)
.filter(|entry| check_file(entry).unwrap_or(false))
.map(|entry| entry.path())
.flat_map(|path| path.canonicalize());
Ok(Box::new(result))
}
pub fn sub_command_path(command_name: &str) -> io::Result<PathBuf> {
let p = env::current_exe()?;
let base_search_dir = p.parent().unwrap();
#[cfg(windows)]
let command_name = format!("uvm-{}.exe", command_name);
#[cfg(unix)]
let command_name = format!("uvm-{}", command_name);
debug!("fetch path to subcommand: {}", &command_name);
//first check exe directory
let comparator = |entry: &fs::DirEntry| {
!entry.file_type().unwrap().is_dir() && entry.file_name() == command_name[..]
};
let command_path = find_in_path(base_search_dir, &comparator);
if command_path.is_ok() {
return command_path;
}
//check PATH
if let Ok(path) = env::var("PATH") {
let split_char = if cfg!(windows) { ";" } else { ":" };
let paths = path.split(split_char).map(|s| Path::new(s));
for path in paths {
let command_path = find_in_path(path, &comparator);
if command_path.is_ok() {
return command_path;
}
}
}
Err(io::Error::new(
io::ErrorKind::NotFound,
format!("command not found: {}", command_name),
))
}
pub struct UvmSubCommands(Box<dyn Iterator<Item = UvmSubCommand>>);
impl UvmSubCommands {
fn new() -> io::Result<UvmSubCommands> {
let p = env::current_exe()?;
let base_search_dir = p.parent().unwrap();
let mut iter = find_commands_in_path(base_search_dir).ok();
if let Ok(path) = env::var("PATH") {
let paths = path.split(':').map(|s| Path::new(s));
for path in paths {
if let Ok(sub_commands) = find_commands_in_path(path) {
iter = match iter {
Some(i) => Some(Box::new(i.chain(sub_commands))),
None => Some(sub_commands),
};
}
}
}
if let Some(i) = iter {
let m = i.unique().map(UvmSubCommand).unique();
Ok(UvmSubCommands(Box::new(m)))
} else {
Err(io::Error::new(io::ErrorKind::NotFound, "not Found"))
}
}
}
impl Iterator for UvmSubCommands {
type Item = UvmSubCommand;
fn next(&mut self) -> Option<Self::Item> {
self.0.next()
}
}
#[derive(Debug, Clone)]
pub struct UvmSubCommand(PathBuf);
impl UvmSubCommand {
pub fn path(&self) -> PathBuf {
self.0.clone()
}
pub fn command_name(&self) -> String {
String::from(
self.0
.file_name()
.unwrap()
.to_string_lossy()
.split("uvm-")
.last()
.unwrap(),
)
}
pub fn description(&self) -> String {
String::from("")
}
}
impl PartialEq for UvmSubCommand {
fn eq(&self, other: &Self) -> bool {
self.command_name() == other.command_name()
}
}
impl Eq for UvmSubCommand {}
impl Hash for UvmSubCommand {
fn hash<H: Hasher>(&self, state: &mut H) {
self.command_name().hash(state);
}
}
pub fn find_sub_commands() -> io::Result<UvmSubCommands> {
UvmSubCommands::new()
}
pub fn print_error_and_exit<E, T>(err: E) -> T
where
E: Error,
{
eprintln!("{}", style(err).red());
process::exit(1);
}
|
mod project;
pub mod projects;
mod task;
|
#![doc = "Peripheral access API for STM32L552 microcontrollers (generated using svd2rust v0.30.0 (8dd361f 2023-08-19))\n\nYou can find an overview of the generated API [here].\n\nAPI features to be included in the [next]
svd2rust release can be generated by cloning the svd2rust [repository], checking out the above commit, and running `cargo doc --open`.\n\n[here]: https://docs.rs/svd2rust/0.30.0/svd2rust/#peripheral-api\n[next]: https://github.com/rust-embedded/svd2rust/blob/master/CHANGELOG.md#unreleased\n[repository]: https://github.com/rust-embedded/svd2rust"]
use core::marker::PhantomData;
use core::ops::Deref;
#[doc = r"Number available in the NVIC for configuring priority"]
pub const NVIC_PRIO_BITS: u8 = 3;
#[cfg(feature = "rt")]
pub use self::Interrupt as interrupt;
pub use cortex_m::peripheral::Peripherals as CorePeripherals;
pub use cortex_m::peripheral::{CBP, CPUID, DCB, DWT, FPB, FPU, ITM, MPU, NVIC, SCB, SYST, TPIU};
#[cfg(feature = "rt")]
pub use cortex_m_rt::interrupt;
#[cfg(feature = "rt")]
extern "C" {
fn WWDG();
fn PVD_PVM();
fn RTC();
fn RTC_S();
fn TAMP();
fn TAMP_S();
fn FLASH();
fn FLASH_S();
fn GTZC();
fn RCC();
fn RCC_S();
fn EXTI0();
fn EXTI1();
fn EXTI2();
fn EXTI3();
fn EXTI4();
fn EXTI5();
fn EXTI6();
fn EXTI7();
fn EXTI8();
fn EXTI9();
fn EXTI10();
fn EXTI11();
fn EXTI12();
fn EXTI13();
fn EXTI14();
fn EXTI15();
fn DMAMUX1_OVR();
fn DMAMUX1_OVR_S();
fn DMA1_CH1();
fn DMA1_CH2();
fn DMA1_CH3();
fn DMA1_CH4();
fn DMA1_CH5();
fn DMA1_CH6();
fn DMA1_CH7();
fn DMA1_CHANNEL8();
fn ADC1_2();
fn DAC();
fn FDCAN1_IT0();
fn FDCAN1_IT1();
fn TIM1_BRK();
fn TIM1_UP();
fn TIM1_TRG_COM();
fn TIM1_CC();
fn TIM2();
fn TIM3();
fn TIM4();
fn TIM5();
fn TIM6();
fn TIM7();
fn TIM8_BRK();
fn TIM8_UP();
fn TIM8_TRG_COM();
fn TIM8_CC();
fn I2C1_EV();
fn I2C1_ER();
fn I2C2_EV();
fn I2C2_ER();
fn SPI1();
fn SPI2();
fn USART1();
fn USART2();
fn USART3();
fn UART4();
fn UART5();
fn LPUART1();
fn LPTIM1();
fn LPTIM2();
fn TIM15();
fn TIM16();
fn TIM17();
fn COMP();
fn USB_FS();
fn CRS();
fn FMC();
fn OCTOSPI1();
fn SDMMC1();
fn DMA2_CH1();
fn DMA2_CH2();
fn DMA2_CH3();
fn DMA2_CH4();
fn DMA2_CH5();
fn DMA2_CH6();
fn DMA2_CH7();
fn DMA2_CH8();
fn I2C3_EV();
fn I2C3_ER();
fn SAI1();
fn SAI2();
fn TSC();
fn RNG();
fn HASH();
fn LPTIM3();
fn SPI3();
fn I2C4_ER();
fn I2C4_EV();
fn DFSDM1_FLT0();
fn DFSDM1_FLT1();
fn DFSDM1_FLT2();
fn DFSDM1_FLT3();
fn UCPD1();
fn ICACHE();
}
#[doc(hidden)]
pub union Vector {
_handler: unsafe extern "C" fn(),
_reserved: u32,
}
#[cfg(feature = "rt")]
#[doc(hidden)]
#[link_section = ".vector_table.interrupts"]
#[no_mangle]
pub static __INTERRUPTS: [Vector; 108] = [
Vector { _handler: WWDG },
Vector { _handler: PVD_PVM },
Vector { _handler: RTC },
Vector { _handler: RTC_S },
Vector { _handler: TAMP },
Vector { _handler: TAMP_S },
Vector { _handler: FLASH },
Vector { _handler: FLASH_S },
Vector { _handler: GTZC },
Vector { _handler: RCC },
Vector { _handler: RCC_S },
Vector { _handler: EXTI0 },
Vector { _handler: EXTI1 },
Vector { _handler: EXTI2 },
Vector { _handler: EXTI3 },
Vector { _handler: EXTI4 },
Vector { _handler: EXTI5 },
Vector { _handler: EXTI6 },
Vector { _handler: EXTI7 },
Vector { _handler: EXTI8 },
Vector { _handler: EXTI9 },
Vector { _handler: EXTI10 },
Vector { _handler: EXTI11 },
Vector { _handler: EXTI12 },
Vector { _handler: EXTI13 },
Vector { _handler: EXTI14 },
Vector { _handler: EXTI15 },
Vector {
_handler: DMAMUX1_OVR,
},
Vector {
_handler: DMAMUX1_OVR_S,
},
Vector { _handler: DMA1_CH1 },
Vector { _handler: DMA1_CH2 },
Vector { _handler: DMA1_CH3 },
Vector { _handler: DMA1_CH4 },
Vector { _handler: DMA1_CH5 },
Vector { _handler: DMA1_CH6 },
Vector { _handler: DMA1_CH7 },
Vector {
_handler: DMA1_CHANNEL8,
},
Vector { _handler: ADC1_2 },
Vector { _handler: DAC },
Vector {
_handler: FDCAN1_IT0,
},
Vector {
_handler: FDCAN1_IT1,
},
Vector { _handler: TIM1_BRK },
Vector { _handler: TIM1_UP },
Vector {
_handler: TIM1_TRG_COM,
},
Vector { _handler: TIM1_CC },
Vector { _handler: TIM2 },
Vector { _handler: TIM3 },
Vector { _handler: TIM4 },
Vector { _handler: TIM5 },
Vector { _handler: TIM6 },
Vector { _handler: TIM7 },
Vector { _handler: TIM8_BRK },
Vector { _handler: TIM8_UP },
Vector {
_handler: TIM8_TRG_COM,
},
Vector { _handler: TIM8_CC },
Vector { _handler: I2C1_EV },
Vector { _handler: I2C1_ER },
Vector { _handler: I2C2_EV },
Vector { _handler: I2C2_ER },
Vector { _handler: SPI1 },
Vector { _handler: SPI2 },
Vector { _handler: USART1 },
Vector { _handler: USART2 },
Vector { _handler: USART3 },
Vector { _handler: UART4 },
Vector { _handler: UART5 },
Vector { _handler: LPUART1 },
Vector { _handler: LPTIM1 },
Vector { _handler: LPTIM2 },
Vector { _handler: TIM15 },
Vector { _handler: TIM16 },
Vector { _handler: TIM17 },
Vector { _handler: COMP },
Vector { _handler: USB_FS },
Vector { _handler: CRS },
Vector { _handler: FMC },
Vector { _handler: OCTOSPI1 },
Vector { _reserved: 0 },
Vector { _handler: SDMMC1 },
Vector { _reserved: 0 },
Vector { _handler: DMA2_CH1 },
Vector { _handler: DMA2_CH2 },
Vector { _handler: DMA2_CH3 },
Vector { _handler: DMA2_CH4 },
Vector { _handler: DMA2_CH5 },
Vector { _handler: DMA2_CH6 },
Vector { _handler: DMA2_CH7 },
Vector { _handler: DMA2_CH8 },
Vector { _handler: I2C3_EV },
Vector { _handler: I2C3_ER },
Vector { _handler: SAI1 },
Vector { _handler: SAI2 },
Vector { _handler: TSC },
Vector { _reserved: 0 },
Vector { _handler: RNG },
Vector { _reserved: 0 },
Vector { _handler: HASH },
Vector { _reserved: 0 },
Vector { _handler: LPTIM3 },
Vector { _handler: SPI3 },
Vector { _handler: I2C4_ER },
Vector { _handler: I2C4_EV },
Vector {
_handler: DFSDM1_FLT0,
},
Vector {
_handler: DFSDM1_FLT1,
},
Vector {
_handler: DFSDM1_FLT2,
},
Vector {
_handler: DFSDM1_FLT3,
},
Vector { _handler: UCPD1 },
Vector { _handler: ICACHE },
];
#[doc = r"Enumeration of all the interrupts."]
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
#[repr(u16)]
pub enum Interrupt {
#[doc = "0 - Window Watchdog interrupt"]
WWDG = 0,
#[doc = "1 - PVD/PVM1/PVM2/PVM3/PVM4 through EXTI"]
PVD_PVM = 1,
#[doc = "2 - RTC global interrupts (EXTI line 17)"]
RTC = 2,
#[doc = "3 - RTC secure global interrupts (EXTI line 18)"]
RTC_S = 3,
#[doc = "4 - TAMPTamper global interrupt (EXTI line 19)"]
TAMP = 4,
#[doc = "5 - Tamper secure global interrupt (EXTI line 20)"]
TAMP_S = 5,
#[doc = "6 - Flash global interrupt"]
FLASH = 6,
#[doc = "7 - Flash memory secure global interrupt"]
FLASH_S = 7,
#[doc = "8 - TZIC secure global interrupt"]
GTZC = 8,
#[doc = "9 - RCC global interrupt"]
RCC = 9,
#[doc = "10 - RCC SECURE GLOBAL INTERRUPT"]
RCC_S = 10,
#[doc = "11 - EXTI line0 interrupt"]
EXTI0 = 11,
#[doc = "12 - EXTI line1 interrupt"]
EXTI1 = 12,
#[doc = "13 - EXTI line2 interrupt"]
EXTI2 = 13,
#[doc = "14 - EXTI line3 interrupt"]
EXTI3 = 14,
#[doc = "15 - EXTI line4 interrupt"]
EXTI4 = 15,
#[doc = "16 - EXTI line5 interrupt"]
EXTI5 = 16,
#[doc = "17 - EXTI line6 interrupt"]
EXTI6 = 17,
#[doc = "18 - EXTI line7 interrupt"]
EXTI7 = 18,
#[doc = "19 - EXTI line8 interrupt"]
EXTI8 = 19,
#[doc = "20 - EXTI line9 interrupt"]
EXTI9 = 20,
#[doc = "21 - EXTI line10 interrupt"]
EXTI10 = 21,
#[doc = "22 - EXTI line11 interrupt"]
EXTI11 = 22,
#[doc = "23 - EXTI line12 interrupt"]
EXTI12 = 23,
#[doc = "24 - EXTI line13 interrupt"]
EXTI13 = 24,
#[doc = "25 - EXTI line14 interrupt"]
EXTI14 = 25,
#[doc = "26 - EXTI line15 interrupt"]
EXTI15 = 26,
#[doc = "27 - DMAMUX overrun interrupt"]
DMAMUX1_OVR = 27,
#[doc = "28 - DMAMUX1 secure overRun interrupt"]
DMAMUX1_OVR_S = 28,
#[doc = "29 - DMA1 Channel1 global interrupt"]
DMA1_CH1 = 29,
#[doc = "30 - DMA1 Channel2 global interrupt"]
DMA1_CH2 = 30,
#[doc = "31 - DMA1 Channel3 interrupt"]
DMA1_CH3 = 31,
#[doc = "32 - DMA1 Channel4 interrupt"]
DMA1_CH4 = 32,
#[doc = "33 - DMA1 Channel5 interrupt"]
DMA1_CH5 = 33,
#[doc = "34 - DMA1 Channel6 interrupt"]
DMA1_CH6 = 34,
#[doc = "35 - DMA1 Channel 7 interrupt"]
DMA1_CH7 = 35,
#[doc = "36 - DMA1_Channel8"]
DMA1_CHANNEL8 = 36,
#[doc = "37 - ADC1_2 global interrupt"]
ADC1_2 = 37,
#[doc = "38 - DAC global interrupt"]
DAC = 38,
#[doc = "39 - FDCAN1 Interrupt 0"]
FDCAN1_IT0 = 39,
#[doc = "40 - FDCAN1 Interrupt 1"]
FDCAN1_IT1 = 40,
#[doc = "41 - TIM1 Break"]
TIM1_BRK = 41,
#[doc = "42 - TIM1 Update"]
TIM1_UP = 42,
#[doc = "43 - TIM1 Trigger and Commutation"]
TIM1_TRG_COM = 43,
#[doc = "44 - TIM1 Capture Compare interrupt"]
TIM1_CC = 44,
#[doc = "45 - TIM2 global interrupt"]
TIM2 = 45,
#[doc = "46 - TIM3 global interrupt"]
TIM3 = 46,
#[doc = "47 - TIM4 global interrupt"]
TIM4 = 47,
#[doc = "48 - TIM5 global interrupt"]
TIM5 = 48,
#[doc = "49 - TIM6 global interrupt"]
TIM6 = 49,
#[doc = "50 - TIM7 global interrupt"]
TIM7 = 50,
#[doc = "51 - TIM8 Break Interrupt"]
TIM8_BRK = 51,
#[doc = "52 - TIM8 Update Interrupt"]
TIM8_UP = 52,
#[doc = "53 - TIM8 Trigger and Commutation Interrupt"]
TIM8_TRG_COM = 53,
#[doc = "54 - TIM8 Capture Compare Interrupt"]
TIM8_CC = 54,
#[doc = "55 - I2C1 event interrupt"]
I2C1_EV = 55,
#[doc = "56 - I2C1 error interrupt"]
I2C1_ER = 56,
#[doc = "57 - I2C2 event interrupt"]
I2C2_EV = 57,
#[doc = "58 - I2C2 error interrupt"]
I2C2_ER = 58,
#[doc = "59 - SPI1 global interrupt"]
SPI1 = 59,
#[doc = "60 - SPI2 global interrupt"]
SPI2 = 60,
#[doc = "61 - USART1 global interrupt"]
USART1 = 61,
#[doc = "62 - USART2 global interrupt"]
USART2 = 62,
#[doc = "63 - USART3 global interrupt"]
USART3 = 63,
#[doc = "64 - UART4 global interrupt"]
UART4 = 64,
#[doc = "65 - UART5 global interrupt"]
UART5 = 65,
#[doc = "66 - LPUART1 global interrupt"]
LPUART1 = 66,
#[doc = "67 - LP TIM1 interrupt"]
LPTIM1 = 67,
#[doc = "68 - LP TIM2 interrupt"]
LPTIM2 = 68,
#[doc = "69 - TIM15 global interrupt"]
TIM15 = 69,
#[doc = "70 - TIM16 global interrupt"]
TIM16 = 70,
#[doc = "71 - TIM17 global interrupt"]
TIM17 = 71,
#[doc = "72 - COMP1 and COMP2 interrupts"]
COMP = 72,
#[doc = "73 - USB FS global interrupt"]
USB_FS = 73,
#[doc = "74 - Clock recovery system global interrupt"]
CRS = 74,
#[doc = "75 - FMC global interrupt"]
FMC = 75,
#[doc = "76 - OCTOSPI1 global interrupt"]
OCTOSPI1 = 76,
#[doc = "78 - SDMMC1 global interrupt"]
SDMMC1 = 78,
#[doc = "80 - DMA2_CH1"]
DMA2_CH1 = 80,
#[doc = "81 - DMA2_CH2"]
DMA2_CH2 = 81,
#[doc = "82 - DMA2_CH3"]
DMA2_CH3 = 82,
#[doc = "83 - DMA2_CH4"]
DMA2_CH4 = 83,
#[doc = "84 - DMA2_CH5"]
DMA2_CH5 = 84,
#[doc = "85 - DMA2_CH6"]
DMA2_CH6 = 85,
#[doc = "86 - DMA2_CH7"]
DMA2_CH7 = 86,
#[doc = "87 - DMA2_CH8"]
DMA2_CH8 = 87,
#[doc = "88 - I2C3 event interrupt"]
I2C3_EV = 88,
#[doc = "89 - I2C3 error interrupt"]
I2C3_ER = 89,
#[doc = "90 - SAI1 global interrupt"]
SAI1 = 90,
#[doc = "91 - SAI2 global interrupt"]
SAI2 = 91,
#[doc = "92 - TSC global interrupt"]
TSC = 92,
#[doc = "94 - RNG global interrupt"]
RNG = 94,
#[doc = "96 - HASH interrupt"]
HASH = 96,
#[doc = "98 - LPTIM3"]
LPTIM3 = 98,
#[doc = "99 - SPI3"]
SPI3 = 99,
#[doc = "100 - I2C4 error interrupt"]
I2C4_ER = 100,
#[doc = "101 - I2C4 event interrupt"]
I2C4_EV = 101,
#[doc = "102 - DFSDM1_FLT0 global interrupt"]
DFSDM1_FLT0 = 102,
#[doc = "103 - DFSDM1_FLT1 global interrupt"]
DFSDM1_FLT1 = 103,
#[doc = "104 - DFSDM1_FLT2 global interrupt"]
DFSDM1_FLT2 = 104,
#[doc = "105 - DFSDM1_FLT3 global interrupt"]
DFSDM1_FLT3 = 105,
#[doc = "106 - UCPD global interrupt"]
UCPD1 = 106,
#[doc = "107 - ICACHE"]
ICACHE = 107,
}
unsafe impl cortex_m::interrupt::InterruptNumber for Interrupt {
#[inline(always)]
fn number(self) -> u16 {
self as u16
}
}
#[doc = "Digital filter for sigma delta modulators"]
pub struct DFSDM1 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for DFSDM1 {}
impl DFSDM1 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const dfsdm1::RegisterBlock = 0x4001_6000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const dfsdm1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for DFSDM1 {
type Target = dfsdm1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for DFSDM1 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("DFSDM1").finish()
}
}
#[doc = "Digital filter for sigma delta modulators"]
pub mod dfsdm1;
#[doc = "Digital filter for sigma delta modulators"]
pub struct SEC_DFSDM1 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_DFSDM1 {}
impl SEC_DFSDM1 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const dfsdm1::RegisterBlock = 0x5001_6000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const dfsdm1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_DFSDM1 {
type Target = dfsdm1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_DFSDM1 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_DFSDM1").finish()
}
}
#[doc = "Digital filter for sigma delta modulators"]
pub use self::dfsdm1 as sec_dfsdm1;
#[doc = "Direct memory access Multiplexer"]
pub struct DMAMUX1 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for DMAMUX1 {}
impl DMAMUX1 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const dmamux1::RegisterBlock = 0x4002_0800 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const dmamux1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for DMAMUX1 {
type Target = dmamux1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for DMAMUX1 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("DMAMUX1").finish()
}
}
#[doc = "Direct memory access Multiplexer"]
pub mod dmamux1;
#[doc = "Direct memory access Multiplexer"]
pub struct SEC_DMAMUX1 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_DMAMUX1 {}
impl SEC_DMAMUX1 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const dmamux1::RegisterBlock = 0x5002_0800 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const dmamux1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_DMAMUX1 {
type Target = dmamux1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_DMAMUX1 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_DMAMUX1").finish()
}
}
#[doc = "Direct memory access Multiplexer"]
pub use self::dmamux1 as sec_dmamux1;
#[doc = "External interrupt/event controller"]
pub struct EXTI {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for EXTI {}
impl EXTI {
#[doc = r"Pointer to the register block"]
pub const PTR: *const exti::RegisterBlock = 0x4002_f400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const exti::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for EXTI {
type Target = exti::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for EXTI {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("EXTI").finish()
}
}
#[doc = "External interrupt/event controller"]
pub mod exti;
#[doc = "External interrupt/event controller"]
pub struct SEC_EXTI {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_EXTI {}
impl SEC_EXTI {
#[doc = r"Pointer to the register block"]
pub const PTR: *const exti::RegisterBlock = 0x5002_f400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const exti::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_EXTI {
type Target = exti::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_EXTI {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_EXTI").finish()
}
}
#[doc = "External interrupt/event controller"]
pub use self::exti as sec_exti;
#[doc = "Flash"]
pub struct FLASH {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for FLASH {}
impl FLASH {
#[doc = r"Pointer to the register block"]
pub const PTR: *const flash::RegisterBlock = 0x4002_2000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const flash::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for FLASH {
type Target = flash::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for FLASH {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("FLASH").finish()
}
}
#[doc = "Flash"]
pub mod flash;
#[doc = "Flash"]
pub struct SEC_FLASH {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_FLASH {}
impl SEC_FLASH {
#[doc = r"Pointer to the register block"]
pub const PTR: *const flash::RegisterBlock = 0x5002_2000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const flash::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_FLASH {
type Target = flash::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_FLASH {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_FLASH").finish()
}
}
#[doc = "Flash"]
pub use self::flash as sec_flash;
#[doc = "General-purpose I/Os"]
pub struct GPIOA {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for GPIOA {}
impl GPIOA {
#[doc = r"Pointer to the register block"]
pub const PTR: *const gpioa::RegisterBlock = 0x4202_0000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const gpioa::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for GPIOA {
type Target = gpioa::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for GPIOA {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("GPIOA").finish()
}
}
#[doc = "General-purpose I/Os"]
pub mod gpioa;
#[doc = "General-purpose I/Os"]
pub struct SEC_GPIOA {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_GPIOA {}
impl SEC_GPIOA {
#[doc = r"Pointer to the register block"]
pub const PTR: *const gpioa::RegisterBlock = 0x5202_0000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const gpioa::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_GPIOA {
type Target = gpioa::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_GPIOA {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_GPIOA").finish()
}
}
#[doc = "General-purpose I/Os"]
pub use self::gpioa as sec_gpioa;
#[doc = "General-purpose I/Os"]
pub struct GPIOB {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for GPIOB {}
impl GPIOB {
#[doc = r"Pointer to the register block"]
pub const PTR: *const gpiob::RegisterBlock = 0x4202_0400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const gpiob::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for GPIOB {
type Target = gpiob::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for GPIOB {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("GPIOB").finish()
}
}
#[doc = "General-purpose I/Os"]
pub mod gpiob;
#[doc = "General-purpose I/Os"]
pub struct SEC_GPIOB {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_GPIOB {}
impl SEC_GPIOB {
#[doc = r"Pointer to the register block"]
pub const PTR: *const gpiob::RegisterBlock = 0x5202_0400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const gpiob::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_GPIOB {
type Target = gpiob::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_GPIOB {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_GPIOB").finish()
}
}
#[doc = "General-purpose I/Os"]
pub use self::gpiob as sec_gpiob;
#[doc = "General-purpose I/Os"]
pub struct GPIOC {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for GPIOC {}
impl GPIOC {
#[doc = r"Pointer to the register block"]
pub const PTR: *const gpioc::RegisterBlock = 0x4202_0800 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const gpioc::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for GPIOC {
type Target = gpioc::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for GPIOC {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("GPIOC").finish()
}
}
#[doc = "General-purpose I/Os"]
pub mod gpioc;
#[doc = "General-purpose I/Os"]
pub struct GPIOD {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for GPIOD {}
impl GPIOD {
#[doc = r"Pointer to the register block"]
pub const PTR: *const gpioc::RegisterBlock = 0x4202_0c00 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const gpioc::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for GPIOD {
type Target = gpioc::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for GPIOD {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("GPIOD").finish()
}
}
#[doc = "General-purpose I/Os"]
pub use self::gpioc as gpiod;
#[doc = "General-purpose I/Os"]
pub struct GPIOE {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for GPIOE {}
impl GPIOE {
#[doc = r"Pointer to the register block"]
pub const PTR: *const gpioc::RegisterBlock = 0x4202_1000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const gpioc::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for GPIOE {
type Target = gpioc::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for GPIOE {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("GPIOE").finish()
}
}
#[doc = "General-purpose I/Os"]
pub use self::gpioc as gpioe;
#[doc = "General-purpose I/Os"]
pub struct GPIOF {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for GPIOF {}
impl GPIOF {
#[doc = r"Pointer to the register block"]
pub const PTR: *const gpioc::RegisterBlock = 0x4202_1400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const gpioc::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for GPIOF {
type Target = gpioc::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for GPIOF {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("GPIOF").finish()
}
}
#[doc = "General-purpose I/Os"]
pub use self::gpioc as gpiof;
#[doc = "General-purpose I/Os"]
pub struct GPIOG {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for GPIOG {}
impl GPIOG {
#[doc = r"Pointer to the register block"]
pub const PTR: *const gpioc::RegisterBlock = 0x4202_1800 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const gpioc::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for GPIOG {
type Target = gpioc::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for GPIOG {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("GPIOG").finish()
}
}
#[doc = "General-purpose I/Os"]
pub use self::gpioc as gpiog;
#[doc = "General-purpose I/Os"]
pub struct SEC_GPIOC {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_GPIOC {}
impl SEC_GPIOC {
#[doc = r"Pointer to the register block"]
pub const PTR: *const gpioc::RegisterBlock = 0x5202_0800 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const gpioc::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_GPIOC {
type Target = gpioc::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_GPIOC {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_GPIOC").finish()
}
}
#[doc = "General-purpose I/Os"]
pub use self::gpioc as sec_gpioc;
#[doc = "General-purpose I/Os"]
pub struct SEC_GPIOD {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_GPIOD {}
impl SEC_GPIOD {
#[doc = r"Pointer to the register block"]
pub const PTR: *const gpioc::RegisterBlock = 0x5202_0c00 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const gpioc::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_GPIOD {
type Target = gpioc::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_GPIOD {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_GPIOD").finish()
}
}
#[doc = "General-purpose I/Os"]
pub use self::gpioc as sec_gpiod;
#[doc = "General-purpose I/Os"]
pub struct SEC_GPIOE {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_GPIOE {}
impl SEC_GPIOE {
#[doc = r"Pointer to the register block"]
pub const PTR: *const gpioc::RegisterBlock = 0x5202_1000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const gpioc::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_GPIOE {
type Target = gpioc::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_GPIOE {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_GPIOE").finish()
}
}
#[doc = "General-purpose I/Os"]
pub use self::gpioc as sec_gpioe;
#[doc = "General-purpose I/Os"]
pub struct SEC_GPIOF {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_GPIOF {}
impl SEC_GPIOF {
#[doc = r"Pointer to the register block"]
pub const PTR: *const gpioc::RegisterBlock = 0x5202_1400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const gpioc::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_GPIOF {
type Target = gpioc::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_GPIOF {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_GPIOF").finish()
}
}
#[doc = "General-purpose I/Os"]
pub use self::gpioc as sec_gpiof;
#[doc = "General-purpose I/Os"]
pub struct SEC_GPIOG {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_GPIOG {}
impl SEC_GPIOG {
#[doc = r"Pointer to the register block"]
pub const PTR: *const gpioc::RegisterBlock = 0x5202_1800 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const gpioc::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_GPIOG {
type Target = gpioc::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_GPIOG {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_GPIOG").finish()
}
}
#[doc = "General-purpose I/Os"]
pub use self::gpioc as sec_gpiog;
#[doc = "General-purpose I/Os"]
pub struct GPIOH {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for GPIOH {}
impl GPIOH {
#[doc = r"Pointer to the register block"]
pub const PTR: *const gpioh::RegisterBlock = 0x4202_1c00 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const gpioh::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for GPIOH {
type Target = gpioh::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for GPIOH {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("GPIOH").finish()
}
}
#[doc = "General-purpose I/Os"]
pub mod gpioh;
#[doc = "General-purpose I/Os"]
pub struct SEC_GPIOH {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_GPIOH {}
impl SEC_GPIOH {
#[doc = r"Pointer to the register block"]
pub const PTR: *const gpioh::RegisterBlock = 0x5202_1c00 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const gpioh::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_GPIOH {
type Target = gpioh::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_GPIOH {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_GPIOH").finish()
}
}
#[doc = "General-purpose I/Os"]
pub use self::gpioh as sec_gpioh;
#[doc = "Tamper and backup registers"]
pub struct TAMP {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for TAMP {}
impl TAMP {
#[doc = r"Pointer to the register block"]
pub const PTR: *const tamp::RegisterBlock = 0x4000_3400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const tamp::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for TAMP {
type Target = tamp::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for TAMP {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("TAMP").finish()
}
}
#[doc = "Tamper and backup registers"]
pub mod tamp;
#[doc = "Tamper and backup registers"]
pub struct SEC_TAMP {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_TAMP {}
impl SEC_TAMP {
#[doc = r"Pointer to the register block"]
pub const PTR: *const tamp::RegisterBlock = 0x5000_3400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const tamp::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_TAMP {
type Target = tamp::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_TAMP {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_TAMP").finish()
}
}
#[doc = "Tamper and backup registers"]
pub use self::tamp as sec_tamp;
#[doc = "Inter-integrated circuit"]
pub struct I2C1 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for I2C1 {}
impl I2C1 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const i2c1::RegisterBlock = 0x4000_5400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const i2c1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for I2C1 {
type Target = i2c1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for I2C1 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("I2C1").finish()
}
}
#[doc = "Inter-integrated circuit"]
pub mod i2c1;
#[doc = "Inter-integrated circuit"]
pub struct I2C2 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for I2C2 {}
impl I2C2 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const i2c1::RegisterBlock = 0x4000_5800 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const i2c1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for I2C2 {
type Target = i2c1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for I2C2 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("I2C2").finish()
}
}
#[doc = "Inter-integrated circuit"]
pub use self::i2c1 as i2c2;
#[doc = "Inter-integrated circuit"]
pub struct I2C3 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for I2C3 {}
impl I2C3 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const i2c1::RegisterBlock = 0x4000_5c00 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const i2c1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for I2C3 {
type Target = i2c1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for I2C3 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("I2C3").finish()
}
}
#[doc = "Inter-integrated circuit"]
pub use self::i2c1 as i2c3;
#[doc = "Inter-integrated circuit"]
pub struct I2C4 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for I2C4 {}
impl I2C4 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const i2c1::RegisterBlock = 0x4000_8400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const i2c1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for I2C4 {
type Target = i2c1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for I2C4 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("I2C4").finish()
}
}
#[doc = "Inter-integrated circuit"]
pub use self::i2c1 as i2c4;
#[doc = "Inter-integrated circuit"]
pub struct SEC_I2C1 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_I2C1 {}
impl SEC_I2C1 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const i2c1::RegisterBlock = 0x5000_5400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const i2c1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_I2C1 {
type Target = i2c1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_I2C1 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_I2C1").finish()
}
}
#[doc = "Inter-integrated circuit"]
pub use self::i2c1 as sec_i2c1;
#[doc = "Inter-integrated circuit"]
pub struct SEC_I2C2 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_I2C2 {}
impl SEC_I2C2 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const i2c1::RegisterBlock = 0x5000_5800 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const i2c1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_I2C2 {
type Target = i2c1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_I2C2 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_I2C2").finish()
}
}
#[doc = "Inter-integrated circuit"]
pub use self::i2c1 as sec_i2c2;
#[doc = "Inter-integrated circuit"]
pub struct SEC_I2C3 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_I2C3 {}
impl SEC_I2C3 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const i2c1::RegisterBlock = 0x5000_5c00 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const i2c1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_I2C3 {
type Target = i2c1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_I2C3 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_I2C3").finish()
}
}
#[doc = "Inter-integrated circuit"]
pub use self::i2c1 as sec_i2c3;
#[doc = "Inter-integrated circuit"]
pub struct SEC_I2C4 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_I2C4 {}
impl SEC_I2C4 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const i2c1::RegisterBlock = 0x5000_8400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const i2c1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_I2C4 {
type Target = i2c1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_I2C4 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_I2C4").finish()
}
}
#[doc = "Inter-integrated circuit"]
pub use self::i2c1 as sec_i2c4;
#[doc = "ICache"]
pub struct ICACHE {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for ICACHE {}
impl ICACHE {
#[doc = r"Pointer to the register block"]
pub const PTR: *const icache::RegisterBlock = 0x4003_0400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const icache::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for ICACHE {
type Target = icache::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for ICACHE {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("ICACHE").finish()
}
}
#[doc = "ICache"]
pub mod icache;
#[doc = "ICache"]
pub struct SEC_ICACHE {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_ICACHE {}
impl SEC_ICACHE {
#[doc = r"Pointer to the register block"]
pub const PTR: *const icache::RegisterBlock = 0x5003_0400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const icache::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_ICACHE {
type Target = icache::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_ICACHE {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_ICACHE").finish()
}
}
#[doc = "ICache"]
pub use self::icache as sec_icache;
#[doc = "Independent watchdog"]
pub struct IWDG {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for IWDG {}
impl IWDG {
#[doc = r"Pointer to the register block"]
pub const PTR: *const iwdg::RegisterBlock = 0x4000_3000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const iwdg::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for IWDG {
type Target = iwdg::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for IWDG {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("IWDG").finish()
}
}
#[doc = "Independent watchdog"]
pub mod iwdg;
#[doc = "Independent watchdog"]
pub struct SEC_IWDG {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_IWDG {}
impl SEC_IWDG {
#[doc = r"Pointer to the register block"]
pub const PTR: *const iwdg::RegisterBlock = 0x5000_3000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const iwdg::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_IWDG {
type Target = iwdg::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_IWDG {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_IWDG").finish()
}
}
#[doc = "Independent watchdog"]
pub use self::iwdg as sec_iwdg;
#[doc = "Low power timer"]
pub struct LPTIM1 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for LPTIM1 {}
impl LPTIM1 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const lptim1::RegisterBlock = 0x4000_7c00 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const lptim1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for LPTIM1 {
type Target = lptim1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for LPTIM1 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("LPTIM1").finish()
}
}
#[doc = "Low power timer"]
pub mod lptim1;
#[doc = "Low power timer"]
pub struct LPTIM2 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for LPTIM2 {}
impl LPTIM2 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const lptim1::RegisterBlock = 0x4000_9400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const lptim1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for LPTIM2 {
type Target = lptim1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for LPTIM2 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("LPTIM2").finish()
}
}
#[doc = "Low power timer"]
pub use self::lptim1 as lptim2;
#[doc = "Low power timer"]
pub struct LPTIM3 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for LPTIM3 {}
impl LPTIM3 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const lptim1::RegisterBlock = 0x4000_9800 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const lptim1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for LPTIM3 {
type Target = lptim1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for LPTIM3 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("LPTIM3").finish()
}
}
#[doc = "Low power timer"]
pub use self::lptim1 as lptim3;
#[doc = "Low power timer"]
pub struct SEC_LPTIM1 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_LPTIM1 {}
impl SEC_LPTIM1 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const lptim1::RegisterBlock = 0x5000_7c00 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const lptim1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_LPTIM1 {
type Target = lptim1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_LPTIM1 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_LPTIM1").finish()
}
}
#[doc = "Low power timer"]
pub use self::lptim1 as sec_lptim1;
#[doc = "Low power timer"]
pub struct SEC_LPTIM2 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_LPTIM2 {}
impl SEC_LPTIM2 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const lptim1::RegisterBlock = 0x5000_9400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const lptim1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_LPTIM2 {
type Target = lptim1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_LPTIM2 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_LPTIM2").finish()
}
}
#[doc = "Low power timer"]
pub use self::lptim1 as sec_lptim2;
#[doc = "Low power timer"]
pub struct SEC_LPTIM3 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_LPTIM3 {}
impl SEC_LPTIM3 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const lptim1::RegisterBlock = 0x5000_9800 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const lptim1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_LPTIM3 {
type Target = lptim1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_LPTIM3 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_LPTIM3").finish()
}
}
#[doc = "Low power timer"]
pub use self::lptim1 as sec_lptim3;
#[doc = "GTZC_MPCBB1"]
pub struct GTZC_MPCBB1 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for GTZC_MPCBB1 {}
impl GTZC_MPCBB1 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const gtzc_mpcbb1::RegisterBlock = 0x4003_2c00 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const gtzc_mpcbb1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for GTZC_MPCBB1 {
type Target = gtzc_mpcbb1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for GTZC_MPCBB1 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("GTZC_MPCBB1").finish()
}
}
#[doc = "GTZC_MPCBB1"]
pub mod gtzc_mpcbb1;
#[doc = "GTZC_MPCBB2"]
pub struct GTZC_MPCBB2 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for GTZC_MPCBB2 {}
impl GTZC_MPCBB2 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const gtzc_mpcbb2::RegisterBlock = 0x4003_3000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const gtzc_mpcbb2::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for GTZC_MPCBB2 {
type Target = gtzc_mpcbb2::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for GTZC_MPCBB2 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("GTZC_MPCBB2").finish()
}
}
#[doc = "GTZC_MPCBB2"]
pub mod gtzc_mpcbb2;
#[doc = "Power control"]
pub struct PWR {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for PWR {}
impl PWR {
#[doc = r"Pointer to the register block"]
pub const PTR: *const pwr::RegisterBlock = 0x4000_7000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const pwr::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for PWR {
type Target = pwr::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for PWR {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("PWR").finish()
}
}
#[doc = "Power control"]
pub mod pwr;
#[doc = "Power control"]
pub struct SEC_PWR {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_PWR {}
impl SEC_PWR {
#[doc = r"Pointer to the register block"]
pub const PTR: *const pwr::RegisterBlock = 0x5000_7000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const pwr::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_PWR {
type Target = pwr::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_PWR {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_PWR").finish()
}
}
#[doc = "Power control"]
pub use self::pwr as sec_pwr;
#[doc = "Reset and clock control"]
pub struct RCC {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for RCC {}
impl RCC {
#[doc = r"Pointer to the register block"]
pub const PTR: *const rcc::RegisterBlock = 0x4002_1000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const rcc::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for RCC {
type Target = rcc::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for RCC {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("RCC").finish()
}
}
#[doc = "Reset and clock control"]
pub mod rcc;
#[doc = "Reset and clock control"]
pub struct SEC_RCC {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_RCC {}
impl SEC_RCC {
#[doc = r"Pointer to the register block"]
pub const PTR: *const rcc::RegisterBlock = 0x5002_1000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const rcc::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_RCC {
type Target = rcc::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_RCC {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_RCC").finish()
}
}
#[doc = "Reset and clock control"]
pub use self::rcc as sec_rcc;
#[doc = "Real-time clock"]
pub struct RTC {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for RTC {}
impl RTC {
#[doc = r"Pointer to the register block"]
pub const PTR: *const rtc::RegisterBlock = 0x4000_2800 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const rtc::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for RTC {
type Target = rtc::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for RTC {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("RTC").finish()
}
}
#[doc = "Real-time clock"]
pub mod rtc;
#[doc = "Real-time clock"]
pub struct SEC_RTC {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_RTC {}
impl SEC_RTC {
#[doc = r"Pointer to the register block"]
pub const PTR: *const rtc::RegisterBlock = 0x5000_2800 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const rtc::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_RTC {
type Target = rtc::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_RTC {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_RTC").finish()
}
}
#[doc = "Real-time clock"]
pub use self::rtc as sec_rtc;
#[doc = "Serial audio interface"]
pub struct SAI1 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SAI1 {}
impl SAI1 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const sai1::RegisterBlock = 0x4001_5400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const sai1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SAI1 {
type Target = sai1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SAI1 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SAI1").finish()
}
}
#[doc = "Serial audio interface"]
pub mod sai1;
#[doc = "Serial audio interface"]
pub struct SAI2 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SAI2 {}
impl SAI2 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const sai1::RegisterBlock = 0x4001_5800 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const sai1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SAI2 {
type Target = sai1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SAI2 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SAI2").finish()
}
}
#[doc = "Serial audio interface"]
pub use self::sai1 as sai2;
#[doc = "Serial audio interface"]
pub struct SEC_SAI1 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_SAI1 {}
impl SEC_SAI1 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const sai1::RegisterBlock = 0x5001_5400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const sai1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_SAI1 {
type Target = sai1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_SAI1 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_SAI1").finish()
}
}
#[doc = "Serial audio interface"]
pub use self::sai1 as sec_sai1;
#[doc = "Serial audio interface"]
pub struct SEC_SAI2 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_SAI2 {}
impl SEC_SAI2 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const sai1::RegisterBlock = 0x5001_5800 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const sai1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_SAI2 {
type Target = sai1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_SAI2 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_SAI2").finish()
}
}
#[doc = "Serial audio interface"]
pub use self::sai1 as sec_sai2;
#[doc = "Direct memory access controller"]
pub struct DMA1 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for DMA1 {}
impl DMA1 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const dma1::RegisterBlock = 0x4002_0000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const dma1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for DMA1 {
type Target = dma1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for DMA1 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("DMA1").finish()
}
}
#[doc = "Direct memory access controller"]
pub mod dma1;
#[doc = "Direct memory access controller"]
pub struct SEC_DMA1 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_DMA1 {}
impl SEC_DMA1 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const dma1::RegisterBlock = 0x5002_0000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const dma1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_DMA1 {
type Target = dma1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_DMA1 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_DMA1").finish()
}
}
#[doc = "Direct memory access controller"]
pub use self::dma1 as sec_dma1;
#[doc = "Direct memory access controller"]
pub struct DMA2 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for DMA2 {}
impl DMA2 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const dma1::RegisterBlock = 0x4002_0400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const dma1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for DMA2 {
type Target = dma1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for DMA2 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("DMA2").finish()
}
}
#[doc = "Direct memory access controller"]
pub use self::dma1 as dma2;
#[doc = "Direct memory access controller"]
pub struct SEC_DMA2 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_DMA2 {}
impl SEC_DMA2 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const dma1::RegisterBlock = 0x5002_0400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const dma1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_DMA2 {
type Target = dma1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_DMA2 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_DMA2").finish()
}
}
#[doc = "Direct memory access controller"]
pub use self::dma1 as sec_dma2;
#[doc = "SEC_GTZC_MPCBB1"]
pub struct SEC_GTZC_MPCBB1 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_GTZC_MPCBB1 {}
impl SEC_GTZC_MPCBB1 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const sec_gtzc_mpcbb1::RegisterBlock = 0x5003_2c00 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const sec_gtzc_mpcbb1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_GTZC_MPCBB1 {
type Target = sec_gtzc_mpcbb1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_GTZC_MPCBB1 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_GTZC_MPCBB1").finish()
}
}
#[doc = "SEC_GTZC_MPCBB1"]
pub mod sec_gtzc_mpcbb1;
#[doc = "SEC_GTZC_MPCBB2"]
pub struct SEC_GTZC_MPCBB2 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_GTZC_MPCBB2 {}
impl SEC_GTZC_MPCBB2 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const sec_gtzc_mpcbb2::RegisterBlock = 0x5003_3000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const sec_gtzc_mpcbb2::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_GTZC_MPCBB2 {
type Target = sec_gtzc_mpcbb2::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_GTZC_MPCBB2 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_GTZC_MPCBB2").finish()
}
}
#[doc = "SEC_GTZC_MPCBB2"]
pub mod sec_gtzc_mpcbb2;
#[doc = "Serial peripheral interface"]
pub struct SPI1 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SPI1 {}
impl SPI1 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const spi1::RegisterBlock = 0x4001_3000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const spi1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SPI1 {
type Target = spi1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SPI1 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SPI1").finish()
}
}
#[doc = "Serial peripheral interface"]
pub mod spi1;
#[doc = "Serial peripheral interface"]
pub struct SPI2 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SPI2 {}
impl SPI2 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const spi1::RegisterBlock = 0x4000_3800 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const spi1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SPI2 {
type Target = spi1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SPI2 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SPI2").finish()
}
}
#[doc = "Serial peripheral interface"]
pub use self::spi1 as spi2;
#[doc = "Serial peripheral interface"]
pub struct SPI3 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SPI3 {}
impl SPI3 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const spi1::RegisterBlock = 0x4000_3c00 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const spi1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SPI3 {
type Target = spi1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SPI3 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SPI3").finish()
}
}
#[doc = "Serial peripheral interface"]
pub use self::spi1 as spi3;
#[doc = "Serial peripheral interface"]
pub struct SEC_SPI1 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_SPI1 {}
impl SEC_SPI1 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const spi1::RegisterBlock = 0x5001_3000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const spi1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_SPI1 {
type Target = spi1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_SPI1 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_SPI1").finish()
}
}
#[doc = "Serial peripheral interface"]
pub use self::spi1 as sec_spi1;
#[doc = "Serial peripheral interface"]
pub struct SEC_SPI2 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_SPI2 {}
impl SEC_SPI2 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const spi1::RegisterBlock = 0x5000_3800 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const spi1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_SPI2 {
type Target = spi1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_SPI2 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_SPI2").finish()
}
}
#[doc = "Serial peripheral interface"]
pub use self::spi1 as sec_spi2;
#[doc = "Serial peripheral interface"]
pub struct SEC_SPI3 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_SPI3 {}
impl SEC_SPI3 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const spi1::RegisterBlock = 0x5000_3c00 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const spi1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_SPI3 {
type Target = spi1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_SPI3 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_SPI3").finish()
}
}
#[doc = "Serial peripheral interface"]
pub use self::spi1 as sec_spi3;
#[doc = "Advanced-timers"]
pub struct TIM1 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for TIM1 {}
impl TIM1 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const tim1::RegisterBlock = 0x4001_2c00 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const tim1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for TIM1 {
type Target = tim1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for TIM1 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("TIM1").finish()
}
}
#[doc = "Advanced-timers"]
pub mod tim1;
#[doc = "Advanced-timers"]
pub struct SEC_TIM1 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_TIM1 {}
impl SEC_TIM1 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const tim1::RegisterBlock = 0x5001_2c00 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const tim1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_TIM1 {
type Target = tim1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_TIM1 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_TIM1").finish()
}
}
#[doc = "Advanced-timers"]
pub use self::tim1 as sec_tim1;
#[doc = "General purpose timers"]
pub struct TIM15 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for TIM15 {}
impl TIM15 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const tim15::RegisterBlock = 0x4001_4000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const tim15::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for TIM15 {
type Target = tim15::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for TIM15 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("TIM15").finish()
}
}
#[doc = "General purpose timers"]
pub mod tim15;
#[doc = "General purpose timers"]
pub struct SEC_TIM15 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_TIM15 {}
impl SEC_TIM15 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const tim15::RegisterBlock = 0x5001_4000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const tim15::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_TIM15 {
type Target = tim15::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_TIM15 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_TIM15").finish()
}
}
#[doc = "General purpose timers"]
pub use self::tim15 as sec_tim15;
#[doc = "General purpose timers"]
pub struct TIM16 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for TIM16 {}
impl TIM16 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const tim16::RegisterBlock = 0x4001_4400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const tim16::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for TIM16 {
type Target = tim16::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for TIM16 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("TIM16").finish()
}
}
#[doc = "General purpose timers"]
pub mod tim16;
#[doc = "General purpose timers"]
pub struct SEC_TIM16 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_TIM16 {}
impl SEC_TIM16 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const tim16::RegisterBlock = 0x5001_4400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const tim16::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_TIM16 {
type Target = tim16::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_TIM16 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_TIM16").finish()
}
}
#[doc = "General purpose timers"]
pub use self::tim16 as sec_tim16;
#[doc = "General purpose timers"]
pub struct TIM17 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for TIM17 {}
impl TIM17 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const tim17::RegisterBlock = 0x4001_4800 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const tim17::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for TIM17 {
type Target = tim17::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for TIM17 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("TIM17").finish()
}
}
#[doc = "General purpose timers"]
pub mod tim17;
#[doc = "General purpose timers"]
pub struct SEC_TIM17 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_TIM17 {}
impl SEC_TIM17 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const tim17::RegisterBlock = 0x5001_4800 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const tim17::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_TIM17 {
type Target = tim17::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_TIM17 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_TIM17").finish()
}
}
#[doc = "General purpose timers"]
pub use self::tim17 as sec_tim17;
#[doc = "General-purpose-timers"]
pub struct TIM2 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for TIM2 {}
impl TIM2 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const tim2::RegisterBlock = 0x4000_0000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const tim2::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for TIM2 {
type Target = tim2::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for TIM2 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("TIM2").finish()
}
}
#[doc = "General-purpose-timers"]
pub mod tim2;
#[doc = "General-purpose-timers"]
pub struct SEC_TIM2 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_TIM2 {}
impl SEC_TIM2 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const tim2::RegisterBlock = 0x5000_0000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const tim2::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_TIM2 {
type Target = tim2::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_TIM2 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_TIM2").finish()
}
}
#[doc = "General-purpose-timers"]
pub use self::tim2 as sec_tim2;
#[doc = "General-purpose-timers"]
pub struct TIM3 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for TIM3 {}
impl TIM3 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const tim3::RegisterBlock = 0x4000_0400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const tim3::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for TIM3 {
type Target = tim3::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for TIM3 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("TIM3").finish()
}
}
#[doc = "General-purpose-timers"]
pub mod tim3;
#[doc = "General-purpose-timers"]
pub struct SEC_TIM3 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_TIM3 {}
impl SEC_TIM3 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const tim3::RegisterBlock = 0x5000_0400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const tim3::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_TIM3 {
type Target = tim3::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_TIM3 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_TIM3").finish()
}
}
#[doc = "General-purpose-timers"]
pub use self::tim3 as sec_tim3;
#[doc = "General-purpose-timers"]
pub struct TIM4 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for TIM4 {}
impl TIM4 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const tim4::RegisterBlock = 0x4000_0800 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const tim4::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for TIM4 {
type Target = tim4::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for TIM4 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("TIM4").finish()
}
}
#[doc = "General-purpose-timers"]
pub mod tim4;
#[doc = "General-purpose-timers"]
pub struct SEC_TIM4 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_TIM4 {}
impl SEC_TIM4 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const tim4::RegisterBlock = 0x5000_0800 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const tim4::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_TIM4 {
type Target = tim4::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_TIM4 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_TIM4").finish()
}
}
#[doc = "General-purpose-timers"]
pub use self::tim4 as sec_tim4;
#[doc = "General-purpose-timers"]
pub struct TIM5 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for TIM5 {}
impl TIM5 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const tim4::RegisterBlock = 0x4000_0c00 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const tim4::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for TIM5 {
type Target = tim4::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for TIM5 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("TIM5").finish()
}
}
#[doc = "General-purpose-timers"]
pub use self::tim4 as tim5;
#[doc = "General-purpose-timers"]
pub struct SEC_TIM5 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_TIM5 {}
impl SEC_TIM5 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const tim4::RegisterBlock = 0x5000_0c00 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const tim4::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_TIM5 {
type Target = tim4::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_TIM5 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_TIM5").finish()
}
}
#[doc = "General-purpose-timers"]
pub use self::tim4 as sec_tim5;
#[doc = "General-purpose-timers"]
pub struct TIM6 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for TIM6 {}
impl TIM6 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const tim6::RegisterBlock = 0x4000_1000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const tim6::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for TIM6 {
type Target = tim6::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for TIM6 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("TIM6").finish()
}
}
#[doc = "General-purpose-timers"]
pub mod tim6;
#[doc = "General-purpose-timers"]
pub struct SEC_TIM6 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_TIM6 {}
impl SEC_TIM6 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const tim6::RegisterBlock = 0x5000_1000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const tim6::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_TIM6 {
type Target = tim6::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_TIM6 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_TIM6").finish()
}
}
#[doc = "General-purpose-timers"]
pub use self::tim6 as sec_tim6;
#[doc = "General-purpose-timers"]
pub struct TIM7 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for TIM7 {}
impl TIM7 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const tim7::RegisterBlock = 0x4000_1400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const tim7::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for TIM7 {
type Target = tim7::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for TIM7 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("TIM7").finish()
}
}
#[doc = "General-purpose-timers"]
pub mod tim7;
#[doc = "General-purpose-timers"]
pub struct SEC_TIM7 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_TIM7 {}
impl SEC_TIM7 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const tim7::RegisterBlock = 0x5000_1400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const tim7::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_TIM7 {
type Target = tim7::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_TIM7 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_TIM7").finish()
}
}
#[doc = "General-purpose-timers"]
pub use self::tim7 as sec_tim7;
#[doc = "DAC"]
pub struct DAC {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for DAC {}
impl DAC {
#[doc = r"Pointer to the register block"]
pub const PTR: *const dac::RegisterBlock = 0x4000_7400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const dac::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for DAC {
type Target = dac::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for DAC {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("DAC").finish()
}
}
#[doc = "DAC"]
pub mod dac;
#[doc = "DAC"]
pub struct SEC_DAC {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_DAC {}
impl SEC_DAC {
#[doc = r"Pointer to the register block"]
pub const PTR: *const dac::RegisterBlock = 0x5000_7400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const dac::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_DAC {
type Target = dac::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_DAC {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_DAC").finish()
}
}
#[doc = "DAC"]
pub use self::dac as sec_dac;
#[doc = "Operational amplifiers"]
pub struct OPAMP {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for OPAMP {}
impl OPAMP {
#[doc = r"Pointer to the register block"]
pub const PTR: *const opamp::RegisterBlock = 0x4000_7800 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const opamp::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for OPAMP {
type Target = opamp::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for OPAMP {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("OPAMP").finish()
}
}
#[doc = "Operational amplifiers"]
pub mod opamp;
#[doc = "Operational amplifiers"]
pub struct SEC_OPAMP {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_OPAMP {}
impl SEC_OPAMP {
#[doc = r"Pointer to the register block"]
pub const PTR: *const opamp::RegisterBlock = 0x5000_7800 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const opamp::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_OPAMP {
type Target = opamp::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_OPAMP {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_OPAMP").finish()
}
}
#[doc = "Operational amplifiers"]
pub use self::opamp as sec_opamp;
#[doc = "Advanced-timers"]
pub struct TIM8 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for TIM8 {}
impl TIM8 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const tim8::RegisterBlock = 0x4001_3400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const tim8::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for TIM8 {
type Target = tim8::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for TIM8 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("TIM8").finish()
}
}
#[doc = "Advanced-timers"]
pub mod tim8;
#[doc = "Advanced-timers"]
pub struct SEC_TIM8 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_TIM8 {}
impl SEC_TIM8 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const tim8::RegisterBlock = 0x5001_3400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const tim8::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_TIM8 {
type Target = tim8::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_TIM8 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_TIM8").finish()
}
}
#[doc = "Advanced-timers"]
pub use self::tim8 as sec_tim8;
#[doc = "GTZC_TZIC"]
pub struct GTZC_TZIC {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for GTZC_TZIC {}
impl GTZC_TZIC {
#[doc = r"Pointer to the register block"]
pub const PTR: *const gtzc_tzic::RegisterBlock = 0x4003_2800 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const gtzc_tzic::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for GTZC_TZIC {
type Target = gtzc_tzic::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for GTZC_TZIC {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("GTZC_TZIC").finish()
}
}
#[doc = "GTZC_TZIC"]
pub mod gtzc_tzic;
#[doc = "GTZC_TZIC"]
pub struct SEC_GTZC_TZIC {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_GTZC_TZIC {}
impl SEC_GTZC_TZIC {
#[doc = r"Pointer to the register block"]
pub const PTR: *const gtzc_tzic::RegisterBlock = 0x5003_2800 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const gtzc_tzic::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_GTZC_TZIC {
type Target = gtzc_tzic::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_GTZC_TZIC {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_GTZC_TZIC").finish()
}
}
#[doc = "GTZC_TZIC"]
pub use self::gtzc_tzic as sec_gtzc_tzic;
#[doc = "GTZC_TZSC"]
pub struct GTZC_TZSC {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for GTZC_TZSC {}
impl GTZC_TZSC {
#[doc = r"Pointer to the register block"]
pub const PTR: *const gtzc_tzsc::RegisterBlock = 0x4003_2400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const gtzc_tzsc::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for GTZC_TZSC {
type Target = gtzc_tzsc::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for GTZC_TZSC {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("GTZC_TZSC").finish()
}
}
#[doc = "GTZC_TZSC"]
pub mod gtzc_tzsc;
#[doc = "GTZC_TZSC"]
pub struct SEC_GTZC_TZSC {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_GTZC_TZSC {}
impl SEC_GTZC_TZSC {
#[doc = r"Pointer to the register block"]
pub const PTR: *const gtzc_tzsc::RegisterBlock = 0x5003_2400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const gtzc_tzsc::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_GTZC_TZSC {
type Target = gtzc_tzsc::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_GTZC_TZSC {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_GTZC_TZSC").finish()
}
}
#[doc = "GTZC_TZSC"]
pub use self::gtzc_tzsc as sec_gtzc_tzsc;
#[doc = "System window watchdog"]
pub struct WWDG {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for WWDG {}
impl WWDG {
#[doc = r"Pointer to the register block"]
pub const PTR: *const wwdg::RegisterBlock = 0x4000_2c00 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const wwdg::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for WWDG {
type Target = wwdg::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for WWDG {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("WWDG").finish()
}
}
#[doc = "System window watchdog"]
pub mod wwdg;
#[doc = "System window watchdog"]
pub struct SEC_WWDG {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_WWDG {}
impl SEC_WWDG {
#[doc = r"Pointer to the register block"]
pub const PTR: *const wwdg::RegisterBlock = 0x5000_2c00 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const wwdg::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_WWDG {
type Target = wwdg::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_WWDG {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_WWDG").finish()
}
}
#[doc = "System window watchdog"]
pub use self::wwdg as sec_wwdg;
#[doc = "System configuration controller"]
pub struct SYSCFG {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SYSCFG {}
impl SYSCFG {
#[doc = r"Pointer to the register block"]
pub const PTR: *const syscfg::RegisterBlock = 0x4001_0000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const syscfg::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SYSCFG {
type Target = syscfg::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SYSCFG {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SYSCFG").finish()
}
}
#[doc = "System configuration controller"]
pub mod syscfg;
#[doc = "System configuration controller"]
pub struct SEC_SYSCFG {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_SYSCFG {}
impl SEC_SYSCFG {
#[doc = r"Pointer to the register block"]
pub const PTR: *const syscfg::RegisterBlock = 0x5001_0000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const syscfg::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_SYSCFG {
type Target = syscfg::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_SYSCFG {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_SYSCFG").finish()
}
}
#[doc = "System configuration controller"]
pub use self::syscfg as sec_syscfg;
#[doc = "MCU debug component"]
pub struct DBGMCU {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for DBGMCU {}
impl DBGMCU {
#[doc = r"Pointer to the register block"]
pub const PTR: *const dbgmcu::RegisterBlock = 0xe004_4000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const dbgmcu::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for DBGMCU {
type Target = dbgmcu::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for DBGMCU {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("DBGMCU").finish()
}
}
#[doc = "MCU debug component"]
pub mod dbgmcu;
#[doc = "Universal serial bus full-speed device interface"]
pub struct USB {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for USB {}
impl USB {
#[doc = r"Pointer to the register block"]
pub const PTR: *const usb::RegisterBlock = 0x4000_d400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const usb::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for USB {
type Target = usb::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for USB {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("USB").finish()
}
}
#[doc = "Universal serial bus full-speed device interface"]
pub mod usb;
#[doc = "Universal serial bus full-speed device interface"]
pub struct SEC_USB {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_USB {}
impl SEC_USB {
#[doc = r"Pointer to the register block"]
pub const PTR: *const usb::RegisterBlock = 0x5000_d400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const usb::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_USB {
type Target = usb::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_USB {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_USB").finish()
}
}
#[doc = "Universal serial bus full-speed device interface"]
pub use self::usb as sec_usb;
#[doc = "OctoSPI"]
pub struct OCTOSPI1 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for OCTOSPI1 {}
impl OCTOSPI1 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const octospi1::RegisterBlock = 0x4402_1000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const octospi1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for OCTOSPI1 {
type Target = octospi1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for OCTOSPI1 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("OCTOSPI1").finish()
}
}
#[doc = "OctoSPI"]
pub mod octospi1;
#[doc = "OctoSPI"]
pub struct SEC_OCTOSPI1 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_OCTOSPI1 {}
impl SEC_OCTOSPI1 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const octospi1::RegisterBlock = 0x5402_1000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const octospi1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_OCTOSPI1 {
type Target = octospi1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_OCTOSPI1 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_OCTOSPI1").finish()
}
}
#[doc = "OctoSPI"]
pub use self::octospi1 as sec_octospi1;
#[doc = "Universal synchronous asynchronous receiver transmitter"]
pub struct LPUART1 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for LPUART1 {}
impl LPUART1 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const lpuart1::RegisterBlock = 0x4000_8000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const lpuart1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for LPUART1 {
type Target = lpuart1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for LPUART1 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("LPUART1").finish()
}
}
#[doc = "Universal synchronous asynchronous receiver transmitter"]
pub mod lpuart1;
#[doc = "Universal synchronous asynchronous receiver transmitter"]
pub struct SEC_LPUART1 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_LPUART1 {}
impl SEC_LPUART1 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const lpuart1::RegisterBlock = 0x5000_8000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const lpuart1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_LPUART1 {
type Target = lpuart1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_LPUART1 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_LPUART1").finish()
}
}
#[doc = "Universal synchronous asynchronous receiver transmitter"]
pub use self::lpuart1 as sec_lpuart1;
#[doc = "Comparator"]
pub struct COMP {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for COMP {}
impl COMP {
#[doc = r"Pointer to the register block"]
pub const PTR: *const comp::RegisterBlock = 0x4001_0200 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const comp::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for COMP {
type Target = comp::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for COMP {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("COMP").finish()
}
}
#[doc = "Comparator"]
pub mod comp;
#[doc = "Comparator"]
pub struct SEC_COMP {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_COMP {}
impl SEC_COMP {
#[doc = r"Pointer to the register block"]
pub const PTR: *const comp::RegisterBlock = 0x5001_0200 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const comp::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_COMP {
type Target = comp::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_COMP {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_COMP").finish()
}
}
#[doc = "Comparator"]
pub use self::comp as sec_comp;
#[doc = "Voltage reference buffer"]
pub struct VREFBUF {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for VREFBUF {}
impl VREFBUF {
#[doc = r"Pointer to the register block"]
pub const PTR: *const vrefbuf::RegisterBlock = 0x4001_0030 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const vrefbuf::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for VREFBUF {
type Target = vrefbuf::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for VREFBUF {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("VREFBUF").finish()
}
}
#[doc = "Voltage reference buffer"]
pub mod vrefbuf;
#[doc = "Voltage reference buffer"]
pub struct SEC_VREFBUF {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_VREFBUF {}
impl SEC_VREFBUF {
#[doc = r"Pointer to the register block"]
pub const PTR: *const vrefbuf::RegisterBlock = 0x5001_0030 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const vrefbuf::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_VREFBUF {
type Target = vrefbuf::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_VREFBUF {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_VREFBUF").finish()
}
}
#[doc = "Voltage reference buffer"]
pub use self::vrefbuf as sec_vrefbuf;
#[doc = "Touch sensing controller"]
pub struct TSC {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for TSC {}
impl TSC {
#[doc = r"Pointer to the register block"]
pub const PTR: *const tsc::RegisterBlock = 0x4002_4000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const tsc::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for TSC {
type Target = tsc::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for TSC {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("TSC").finish()
}
}
#[doc = "Touch sensing controller"]
pub mod tsc;
#[doc = "Touch sensing controller"]
pub struct SEC_TSC {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_TSC {}
impl SEC_TSC {
#[doc = r"Pointer to the register block"]
pub const PTR: *const tsc::RegisterBlock = 0x5002_4000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const tsc::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_TSC {
type Target = tsc::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_TSC {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_TSC").finish()
}
}
#[doc = "Touch sensing controller"]
pub use self::tsc as sec_tsc;
#[doc = "USB Power Delivery interface"]
pub struct UCPD1 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for UCPD1 {}
impl UCPD1 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const ucpd1::RegisterBlock = 0x4000_dc00 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const ucpd1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for UCPD1 {
type Target = ucpd1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for UCPD1 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("UCPD1").finish()
}
}
#[doc = "USB Power Delivery interface"]
pub mod ucpd1;
#[doc = "USB Power Delivery interface"]
pub struct SEC_UCPD1 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_UCPD1 {}
impl SEC_UCPD1 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const ucpd1::RegisterBlock = 0x5000_dc00 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const ucpd1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_UCPD1 {
type Target = ucpd1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_UCPD1 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_UCPD1").finish()
}
}
#[doc = "USB Power Delivery interface"]
pub use self::ucpd1 as sec_ucpd1;
#[doc = "FDCAN1"]
pub struct FDCAN1 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for FDCAN1 {}
impl FDCAN1 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const fdcan1::RegisterBlock = 0x4000_a400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const fdcan1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for FDCAN1 {
type Target = fdcan1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for FDCAN1 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("FDCAN1").finish()
}
}
#[doc = "FDCAN1"]
pub mod fdcan1;
#[doc = "FDCAN1"]
pub struct SEC_FDCAN1 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_FDCAN1 {}
impl SEC_FDCAN1 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const fdcan1::RegisterBlock = 0x5000_a400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const fdcan1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_FDCAN1 {
type Target = fdcan1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_FDCAN1 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_FDCAN1").finish()
}
}
#[doc = "FDCAN1"]
pub use self::fdcan1 as sec_fdcan1;
#[doc = "Cyclic redundancy check calculation unit"]
pub struct CRC {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for CRC {}
impl CRC {
#[doc = r"Pointer to the register block"]
pub const PTR: *const crc::RegisterBlock = 0x4002_3000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const crc::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for CRC {
type Target = crc::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for CRC {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("CRC").finish()
}
}
#[doc = "Cyclic redundancy check calculation unit"]
pub mod crc;
#[doc = "Cyclic redundancy check calculation unit"]
pub struct SEC_CRC {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_CRC {}
impl SEC_CRC {
#[doc = r"Pointer to the register block"]
pub const PTR: *const crc::RegisterBlock = 0x5002_3000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const crc::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_CRC {
type Target = crc::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_CRC {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_CRC").finish()
}
}
#[doc = "Cyclic redundancy check calculation unit"]
pub use self::crc as sec_crc;
#[doc = "Clock recovery system"]
pub struct CRS {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for CRS {}
impl CRS {
#[doc = r"Pointer to the register block"]
pub const PTR: *const crs::RegisterBlock = 0x4000_6000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const crs::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for CRS {
type Target = crs::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for CRS {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("CRS").finish()
}
}
#[doc = "Clock recovery system"]
pub mod crs;
#[doc = "Clock recovery system"]
pub struct SEC_CRS {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_CRS {}
impl SEC_CRS {
#[doc = r"Pointer to the register block"]
pub const PTR: *const crs::RegisterBlock = 0x5000_6000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const crs::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_CRS {
type Target = crs::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_CRS {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_CRS").finish()
}
}
#[doc = "Clock recovery system"]
pub use self::crs as sec_crs;
#[doc = "Universal synchronous asynchronous receiver transmitter"]
pub struct USART1 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for USART1 {}
impl USART1 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const usart1::RegisterBlock = 0x4001_3800 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const usart1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for USART1 {
type Target = usart1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for USART1 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("USART1").finish()
}
}
#[doc = "Universal synchronous asynchronous receiver transmitter"]
pub mod usart1;
#[doc = "Universal synchronous asynchronous receiver transmitter"]
pub struct SEC_USART1 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_USART1 {}
impl SEC_USART1 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const usart1::RegisterBlock = 0x5001_3800 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const usart1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_USART1 {
type Target = usart1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_USART1 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_USART1").finish()
}
}
#[doc = "Universal synchronous asynchronous receiver transmitter"]
pub use self::usart1 as sec_usart1;
#[doc = "Universal synchronous asynchronous receiver transmitter"]
pub struct USART2 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for USART2 {}
impl USART2 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const usart1::RegisterBlock = 0x4000_4400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const usart1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for USART2 {
type Target = usart1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for USART2 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("USART2").finish()
}
}
#[doc = "Universal synchronous asynchronous receiver transmitter"]
pub use self::usart1 as usart2;
#[doc = "Universal synchronous asynchronous receiver transmitter"]
pub struct SEC_USART2 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_USART2 {}
impl SEC_USART2 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const usart1::RegisterBlock = 0x5000_4400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const usart1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_USART2 {
type Target = usart1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_USART2 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_USART2").finish()
}
}
#[doc = "Universal synchronous asynchronous receiver transmitter"]
pub use self::usart1 as sec_usart2;
#[doc = "Universal synchronous asynchronous receiver transmitter"]
pub struct USART3 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for USART3 {}
impl USART3 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const usart1::RegisterBlock = 0x4000_4800 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const usart1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for USART3 {
type Target = usart1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for USART3 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("USART3").finish()
}
}
#[doc = "Universal synchronous asynchronous receiver transmitter"]
pub use self::usart1 as usart3;
#[doc = "Universal synchronous asynchronous receiver transmitter"]
pub struct SEC_USART3 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_USART3 {}
impl SEC_USART3 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const usart1::RegisterBlock = 0x5000_4800 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const usart1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_USART3 {
type Target = usart1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_USART3 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_USART3").finish()
}
}
#[doc = "Universal synchronous asynchronous receiver transmitter"]
pub use self::usart1 as sec_usart3;
#[doc = "Universal synchronous asynchronous receiver transmitter"]
pub struct UART4 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for UART4 {}
impl UART4 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const usart1::RegisterBlock = 0x4000_4c00 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const usart1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for UART4 {
type Target = usart1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for UART4 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("UART4").finish()
}
}
#[doc = "Universal synchronous asynchronous receiver transmitter"]
pub use self::usart1 as uart4;
#[doc = "Universal synchronous asynchronous receiver transmitter"]
pub struct UART5 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for UART5 {}
impl UART5 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const usart1::RegisterBlock = 0x4000_5000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const usart1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for UART5 {
type Target = usart1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for UART5 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("UART5").finish()
}
}
#[doc = "Universal synchronous asynchronous receiver transmitter"]
pub use self::usart1 as uart5;
#[doc = "Universal synchronous asynchronous receiver transmitter"]
pub struct SEC_UART4 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_UART4 {}
impl SEC_UART4 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const usart1::RegisterBlock = 0x5000_4c00 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const usart1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_UART4 {
type Target = usart1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_UART4 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_UART4").finish()
}
}
#[doc = "Universal synchronous asynchronous receiver transmitter"]
pub use self::usart1 as sec_uart4;
#[doc = "Universal synchronous asynchronous receiver transmitter"]
pub struct SEC_UART5 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_UART5 {}
impl SEC_UART5 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const usart1::RegisterBlock = 0x5000_5000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const usart1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_UART5 {
type Target = usart1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_UART5 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_UART5").finish()
}
}
#[doc = "Universal synchronous asynchronous receiver transmitter"]
pub use self::usart1 as sec_uart5;
#[doc = "Analog-to-Digital Converter"]
pub struct ADC_COMMON {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for ADC_COMMON {}
impl ADC_COMMON {
#[doc = r"Pointer to the register block"]
pub const PTR: *const adc_common::RegisterBlock = 0x4202_8300 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const adc_common::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for ADC_COMMON {
type Target = adc_common::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for ADC_COMMON {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("ADC_COMMON").finish()
}
}
#[doc = "Analog-to-Digital Converter"]
pub mod adc_common;
#[doc = "Analog-to-Digital Converter"]
pub struct SEC_ADC_COMMON {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_ADC_COMMON {}
impl SEC_ADC_COMMON {
#[doc = r"Pointer to the register block"]
pub const PTR: *const adc_common::RegisterBlock = 0x5202_8300 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const adc_common::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_ADC_COMMON {
type Target = adc_common::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_ADC_COMMON {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_ADC_COMMON").finish()
}
}
#[doc = "Analog-to-Digital Converter"]
pub use self::adc_common as sec_adc_common;
#[doc = "Analog-to-Digital Converter"]
pub struct ADC1 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for ADC1 {}
impl ADC1 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const adc1::RegisterBlock = 0x4202_8000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const adc1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for ADC1 {
type Target = adc1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for ADC1 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("ADC1").finish()
}
}
#[doc = "Analog-to-Digital Converter"]
pub mod adc1;
#[doc = "Analog-to-Digital Converter"]
pub struct SEC_ADC1 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_ADC1 {}
impl SEC_ADC1 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const adc1::RegisterBlock = 0x5202_8000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const adc1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_ADC1 {
type Target = adc1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_ADC1 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_ADC1").finish()
}
}
#[doc = "Analog-to-Digital Converter"]
pub use self::adc1 as sec_adc1;
#[doc = "Analog-to-Digital Converter"]
pub struct ADC2 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for ADC2 {}
impl ADC2 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const adc2::RegisterBlock = 0x4202_8100 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const adc2::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for ADC2 {
type Target = adc2::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for ADC2 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("ADC2").finish()
}
}
#[doc = "Analog-to-Digital Converter"]
pub mod adc2;
#[doc = "Analog-to-Digital Converter"]
pub struct SEC_ADC2 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_ADC2 {}
impl SEC_ADC2 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const adc2::RegisterBlock = 0x5202_8100 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const adc2::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_ADC2 {
type Target = adc2::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_ADC2 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_ADC2").finish()
}
}
#[doc = "Analog-to-Digital Converter"]
pub use self::adc2 as sec_adc2;
#[doc = "Nested vectored interrupt controller"]
pub struct NVIC_STIR {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for NVIC_STIR {}
impl NVIC_STIR {
#[doc = r"Pointer to the register block"]
pub const PTR: *const nvic_stir::RegisterBlock = 0xe000_ef00 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const nvic_stir::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for NVIC_STIR {
type Target = nvic_stir::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for NVIC_STIR {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("NVIC_STIR").finish()
}
}
#[doc = "Nested vectored interrupt controller"]
pub mod nvic_stir;
#[doc = "FMC"]
pub struct FMC {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for FMC {}
impl FMC {
#[doc = r"Pointer to the register block"]
pub const PTR: *const fmc::RegisterBlock = 0x4402_0000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const fmc::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for FMC {
type Target = fmc::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for FMC {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("FMC").finish()
}
}
#[doc = "FMC"]
pub mod fmc;
#[doc = "FMC"]
pub struct SEC_FMC {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_FMC {}
impl SEC_FMC {
#[doc = r"Pointer to the register block"]
pub const PTR: *const fmc::RegisterBlock = 0x5402_0000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const fmc::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_FMC {
type Target = fmc::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_FMC {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_FMC").finish()
}
}
#[doc = "FMC"]
pub use self::fmc as sec_fmc;
#[doc = "RNG"]
pub struct RNG {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for RNG {}
impl RNG {
#[doc = r"Pointer to the register block"]
pub const PTR: *const rng::RegisterBlock = 0x420c_0800 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const rng::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for RNG {
type Target = rng::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for RNG {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("RNG").finish()
}
}
#[doc = "RNG"]
pub mod rng;
#[doc = "RNG"]
pub struct SEC_RNG {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_RNG {}
impl SEC_RNG {
#[doc = r"Pointer to the register block"]
pub const PTR: *const rng::RegisterBlock = 0x520c_0800 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const rng::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_RNG {
type Target = rng::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_RNG {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_RNG").finish()
}
}
#[doc = "RNG"]
pub use self::rng as sec_rng;
#[doc = "SDMMC1"]
pub struct SDMMC1 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SDMMC1 {}
impl SDMMC1 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const sdmmc1::RegisterBlock = 0x420c_8000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const sdmmc1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SDMMC1 {
type Target = sdmmc1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SDMMC1 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SDMMC1").finish()
}
}
#[doc = "SDMMC1"]
pub mod sdmmc1;
#[doc = "SDMMC1"]
pub struct SEC_SDMMC1 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_SDMMC1 {}
impl SEC_SDMMC1 {
#[doc = r"Pointer to the register block"]
pub const PTR: *const sdmmc1::RegisterBlock = 0x520c_8000 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const sdmmc1::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_SDMMC1 {
type Target = sdmmc1::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_SDMMC1 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_SDMMC1").finish()
}
}
#[doc = "SDMMC1"]
pub use self::sdmmc1 as sec_sdmmc1;
#[doc = "Hash processor"]
pub struct HASH {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for HASH {}
impl HASH {
#[doc = r"Pointer to the register block"]
pub const PTR: *const hash::RegisterBlock = 0x420c_0400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const hash::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for HASH {
type Target = hash::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for HASH {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("HASH").finish()
}
}
#[doc = "Hash processor"]
pub mod hash;
#[doc = "Hash processor"]
pub struct SEC_HASH {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for SEC_HASH {}
impl SEC_HASH {
#[doc = r"Pointer to the register block"]
pub const PTR: *const hash::RegisterBlock = 0x520c_0400 as *const _;
#[doc = r"Return the pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const hash::RegisterBlock {
Self::PTR
}
#[doc = r" Steal an instance of this peripheral"]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Ensure that the new instance of the peripheral cannot be used in a way"]
#[doc = r" that may race with any existing instances, for example by only"]
#[doc = r" accessing read-only or write-only registers, or by consuming the"]
#[doc = r" original peripheral and using critical sections to coordinate"]
#[doc = r" access between multiple new instances."]
#[doc = r""]
#[doc = r" Additionally, other software such as HALs may rely on only one"]
#[doc = r" peripheral instance existing to ensure memory safety; ensure"]
#[doc = r" no stolen instances are passed to such software."]
pub unsafe fn steal() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl Deref for SEC_HASH {
type Target = hash::RegisterBlock;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*Self::PTR }
}
}
impl core::fmt::Debug for SEC_HASH {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("SEC_HASH").finish()
}
}
#[doc = "Hash processor"]
pub use self::hash as sec_hash;
#[no_mangle]
static mut DEVICE_PERIPHERALS: bool = false;
#[doc = r" All the peripherals."]
#[allow(non_snake_case)]
pub struct Peripherals {
#[doc = "DFSDM1"]
pub DFSDM1: DFSDM1,
#[doc = "SEC_DFSDM1"]
pub SEC_DFSDM1: SEC_DFSDM1,
#[doc = "DMAMUX1"]
pub DMAMUX1: DMAMUX1,
#[doc = "SEC_DMAMUX1"]
pub SEC_DMAMUX1: SEC_DMAMUX1,
#[doc = "EXTI"]
pub EXTI: EXTI,
#[doc = "SEC_EXTI"]
pub SEC_EXTI: SEC_EXTI,
#[doc = "FLASH"]
pub FLASH: FLASH,
#[doc = "SEC_FLASH"]
pub SEC_FLASH: SEC_FLASH,
#[doc = "GPIOA"]
pub GPIOA: GPIOA,
#[doc = "SEC_GPIOA"]
pub SEC_GPIOA: SEC_GPIOA,
#[doc = "GPIOB"]
pub GPIOB: GPIOB,
#[doc = "SEC_GPIOB"]
pub SEC_GPIOB: SEC_GPIOB,
#[doc = "GPIOC"]
pub GPIOC: GPIOC,
#[doc = "GPIOD"]
pub GPIOD: GPIOD,
#[doc = "GPIOE"]
pub GPIOE: GPIOE,
#[doc = "GPIOF"]
pub GPIOF: GPIOF,
#[doc = "GPIOG"]
pub GPIOG: GPIOG,
#[doc = "SEC_GPIOC"]
pub SEC_GPIOC: SEC_GPIOC,
#[doc = "SEC_GPIOD"]
pub SEC_GPIOD: SEC_GPIOD,
#[doc = "SEC_GPIOE"]
pub SEC_GPIOE: SEC_GPIOE,
#[doc = "SEC_GPIOF"]
pub SEC_GPIOF: SEC_GPIOF,
#[doc = "SEC_GPIOG"]
pub SEC_GPIOG: SEC_GPIOG,
#[doc = "GPIOH"]
pub GPIOH: GPIOH,
#[doc = "SEC_GPIOH"]
pub SEC_GPIOH: SEC_GPIOH,
#[doc = "TAMP"]
pub TAMP: TAMP,
#[doc = "SEC_TAMP"]
pub SEC_TAMP: SEC_TAMP,
#[doc = "I2C1"]
pub I2C1: I2C1,
#[doc = "I2C2"]
pub I2C2: I2C2,
#[doc = "I2C3"]
pub I2C3: I2C3,
#[doc = "I2C4"]
pub I2C4: I2C4,
#[doc = "SEC_I2C1"]
pub SEC_I2C1: SEC_I2C1,
#[doc = "SEC_I2C2"]
pub SEC_I2C2: SEC_I2C2,
#[doc = "SEC_I2C3"]
pub SEC_I2C3: SEC_I2C3,
#[doc = "SEC_I2C4"]
pub SEC_I2C4: SEC_I2C4,
#[doc = "ICACHE"]
pub ICACHE: ICACHE,
#[doc = "SEC_ICACHE"]
pub SEC_ICACHE: SEC_ICACHE,
#[doc = "IWDG"]
pub IWDG: IWDG,
#[doc = "SEC_IWDG"]
pub SEC_IWDG: SEC_IWDG,
#[doc = "LPTIM1"]
pub LPTIM1: LPTIM1,
#[doc = "LPTIM2"]
pub LPTIM2: LPTIM2,
#[doc = "LPTIM3"]
pub LPTIM3: LPTIM3,
#[doc = "SEC_LPTIM1"]
pub SEC_LPTIM1: SEC_LPTIM1,
#[doc = "SEC_LPTIM2"]
pub SEC_LPTIM2: SEC_LPTIM2,
#[doc = "SEC_LPTIM3"]
pub SEC_LPTIM3: SEC_LPTIM3,
#[doc = "GTZC_MPCBB1"]
pub GTZC_MPCBB1: GTZC_MPCBB1,
#[doc = "GTZC_MPCBB2"]
pub GTZC_MPCBB2: GTZC_MPCBB2,
#[doc = "PWR"]
pub PWR: PWR,
#[doc = "SEC_PWR"]
pub SEC_PWR: SEC_PWR,
#[doc = "RCC"]
pub RCC: RCC,
#[doc = "SEC_RCC"]
pub SEC_RCC: SEC_RCC,
#[doc = "RTC"]
pub RTC: RTC,
#[doc = "SEC_RTC"]
pub SEC_RTC: SEC_RTC,
#[doc = "SAI1"]
pub SAI1: SAI1,
#[doc = "SAI2"]
pub SAI2: SAI2,
#[doc = "SEC_SAI1"]
pub SEC_SAI1: SEC_SAI1,
#[doc = "SEC_SAI2"]
pub SEC_SAI2: SEC_SAI2,
#[doc = "DMA1"]
pub DMA1: DMA1,
#[doc = "SEC_DMA1"]
pub SEC_DMA1: SEC_DMA1,
#[doc = "DMA2"]
pub DMA2: DMA2,
#[doc = "SEC_DMA2"]
pub SEC_DMA2: SEC_DMA2,
#[doc = "SEC_GTZC_MPCBB1"]
pub SEC_GTZC_MPCBB1: SEC_GTZC_MPCBB1,
#[doc = "SEC_GTZC_MPCBB2"]
pub SEC_GTZC_MPCBB2: SEC_GTZC_MPCBB2,
#[doc = "SPI1"]
pub SPI1: SPI1,
#[doc = "SPI2"]
pub SPI2: SPI2,
#[doc = "SPI3"]
pub SPI3: SPI3,
#[doc = "SEC_SPI1"]
pub SEC_SPI1: SEC_SPI1,
#[doc = "SEC_SPI2"]
pub SEC_SPI2: SEC_SPI2,
#[doc = "SEC_SPI3"]
pub SEC_SPI3: SEC_SPI3,
#[doc = "TIM1"]
pub TIM1: TIM1,
#[doc = "SEC_TIM1"]
pub SEC_TIM1: SEC_TIM1,
#[doc = "TIM15"]
pub TIM15: TIM15,
#[doc = "SEC_TIM15"]
pub SEC_TIM15: SEC_TIM15,
#[doc = "TIM16"]
pub TIM16: TIM16,
#[doc = "SEC_TIM16"]
pub SEC_TIM16: SEC_TIM16,
#[doc = "TIM17"]
pub TIM17: TIM17,
#[doc = "SEC_TIM17"]
pub SEC_TIM17: SEC_TIM17,
#[doc = "TIM2"]
pub TIM2: TIM2,
#[doc = "SEC_TIM2"]
pub SEC_TIM2: SEC_TIM2,
#[doc = "TIM3"]
pub TIM3: TIM3,
#[doc = "SEC_TIM3"]
pub SEC_TIM3: SEC_TIM3,
#[doc = "TIM4"]
pub TIM4: TIM4,
#[doc = "SEC_TIM4"]
pub SEC_TIM4: SEC_TIM4,
#[doc = "TIM5"]
pub TIM5: TIM5,
#[doc = "SEC_TIM5"]
pub SEC_TIM5: SEC_TIM5,
#[doc = "TIM6"]
pub TIM6: TIM6,
#[doc = "SEC_TIM6"]
pub SEC_TIM6: SEC_TIM6,
#[doc = "TIM7"]
pub TIM7: TIM7,
#[doc = "SEC_TIM7"]
pub SEC_TIM7: SEC_TIM7,
#[doc = "DAC"]
pub DAC: DAC,
#[doc = "SEC_DAC"]
pub SEC_DAC: SEC_DAC,
#[doc = "OPAMP"]
pub OPAMP: OPAMP,
#[doc = "SEC_OPAMP"]
pub SEC_OPAMP: SEC_OPAMP,
#[doc = "TIM8"]
pub TIM8: TIM8,
#[doc = "SEC_TIM8"]
pub SEC_TIM8: SEC_TIM8,
#[doc = "GTZC_TZIC"]
pub GTZC_TZIC: GTZC_TZIC,
#[doc = "SEC_GTZC_TZIC"]
pub SEC_GTZC_TZIC: SEC_GTZC_TZIC,
#[doc = "GTZC_TZSC"]
pub GTZC_TZSC: GTZC_TZSC,
#[doc = "SEC_GTZC_TZSC"]
pub SEC_GTZC_TZSC: SEC_GTZC_TZSC,
#[doc = "WWDG"]
pub WWDG: WWDG,
#[doc = "SEC_WWDG"]
pub SEC_WWDG: SEC_WWDG,
#[doc = "SYSCFG"]
pub SYSCFG: SYSCFG,
#[doc = "SEC_SYSCFG"]
pub SEC_SYSCFG: SEC_SYSCFG,
#[doc = "DBGMCU"]
pub DBGMCU: DBGMCU,
#[doc = "USB"]
pub USB: USB,
#[doc = "SEC_USB"]
pub SEC_USB: SEC_USB,
#[doc = "OCTOSPI1"]
pub OCTOSPI1: OCTOSPI1,
#[doc = "SEC_OCTOSPI1"]
pub SEC_OCTOSPI1: SEC_OCTOSPI1,
#[doc = "LPUART1"]
pub LPUART1: LPUART1,
#[doc = "SEC_LPUART1"]
pub SEC_LPUART1: SEC_LPUART1,
#[doc = "COMP"]
pub COMP: COMP,
#[doc = "SEC_COMP"]
pub SEC_COMP: SEC_COMP,
#[doc = "VREFBUF"]
pub VREFBUF: VREFBUF,
#[doc = "SEC_VREFBUF"]
pub SEC_VREFBUF: SEC_VREFBUF,
#[doc = "TSC"]
pub TSC: TSC,
#[doc = "SEC_TSC"]
pub SEC_TSC: SEC_TSC,
#[doc = "UCPD1"]
pub UCPD1: UCPD1,
#[doc = "SEC_UCPD1"]
pub SEC_UCPD1: SEC_UCPD1,
#[doc = "FDCAN1"]
pub FDCAN1: FDCAN1,
#[doc = "SEC_FDCAN1"]
pub SEC_FDCAN1: SEC_FDCAN1,
#[doc = "CRC"]
pub CRC: CRC,
#[doc = "SEC_CRC"]
pub SEC_CRC: SEC_CRC,
#[doc = "CRS"]
pub CRS: CRS,
#[doc = "SEC_CRS"]
pub SEC_CRS: SEC_CRS,
#[doc = "USART1"]
pub USART1: USART1,
#[doc = "SEC_USART1"]
pub SEC_USART1: SEC_USART1,
#[doc = "USART2"]
pub USART2: USART2,
#[doc = "SEC_USART2"]
pub SEC_USART2: SEC_USART2,
#[doc = "USART3"]
pub USART3: USART3,
#[doc = "SEC_USART3"]
pub SEC_USART3: SEC_USART3,
#[doc = "UART4"]
pub UART4: UART4,
#[doc = "UART5"]
pub UART5: UART5,
#[doc = "SEC_UART4"]
pub SEC_UART4: SEC_UART4,
#[doc = "SEC_UART5"]
pub SEC_UART5: SEC_UART5,
#[doc = "ADC_COMMON"]
pub ADC_COMMON: ADC_COMMON,
#[doc = "SEC_ADC_COMMON"]
pub SEC_ADC_COMMON: SEC_ADC_COMMON,
#[doc = "ADC1"]
pub ADC1: ADC1,
#[doc = "SEC_ADC1"]
pub SEC_ADC1: SEC_ADC1,
#[doc = "ADC2"]
pub ADC2: ADC2,
#[doc = "SEC_ADC2"]
pub SEC_ADC2: SEC_ADC2,
#[doc = "NVIC_STIR"]
pub NVIC_STIR: NVIC_STIR,
#[doc = "FMC"]
pub FMC: FMC,
#[doc = "SEC_FMC"]
pub SEC_FMC: SEC_FMC,
#[doc = "RNG"]
pub RNG: RNG,
#[doc = "SEC_RNG"]
pub SEC_RNG: SEC_RNG,
#[doc = "SDMMC1"]
pub SDMMC1: SDMMC1,
#[doc = "SEC_SDMMC1"]
pub SEC_SDMMC1: SEC_SDMMC1,
#[doc = "HASH"]
pub HASH: HASH,
#[doc = "SEC_HASH"]
pub SEC_HASH: SEC_HASH,
}
impl Peripherals {
#[doc = r" Returns all the peripherals *once*."]
#[cfg(feature = "critical-section")]
#[inline]
pub fn take() -> Option<Self> {
critical_section::with(|_| {
if unsafe { DEVICE_PERIPHERALS } {
return None;
}
Some(unsafe { Peripherals::steal() })
})
}
#[doc = r" Unchecked version of `Peripherals::take`."]
#[doc = r""]
#[doc = r" # Safety"]
#[doc = r""]
#[doc = r" Each of the returned peripherals must be used at most once."]
#[inline]
pub unsafe fn steal() -> Self {
DEVICE_PERIPHERALS = true;
Peripherals {
DFSDM1: DFSDM1 {
_marker: PhantomData,
},
SEC_DFSDM1: SEC_DFSDM1 {
_marker: PhantomData,
},
DMAMUX1: DMAMUX1 {
_marker: PhantomData,
},
SEC_DMAMUX1: SEC_DMAMUX1 {
_marker: PhantomData,
},
EXTI: EXTI {
_marker: PhantomData,
},
SEC_EXTI: SEC_EXTI {
_marker: PhantomData,
},
FLASH: FLASH {
_marker: PhantomData,
},
SEC_FLASH: SEC_FLASH {
_marker: PhantomData,
},
GPIOA: GPIOA {
_marker: PhantomData,
},
SEC_GPIOA: SEC_GPIOA {
_marker: PhantomData,
},
GPIOB: GPIOB {
_marker: PhantomData,
},
SEC_GPIOB: SEC_GPIOB {
_marker: PhantomData,
},
GPIOC: GPIOC {
_marker: PhantomData,
},
GPIOD: GPIOD {
_marker: PhantomData,
},
GPIOE: GPIOE {
_marker: PhantomData,
},
GPIOF: GPIOF {
_marker: PhantomData,
},
GPIOG: GPIOG {
_marker: PhantomData,
},
SEC_GPIOC: SEC_GPIOC {
_marker: PhantomData,
},
SEC_GPIOD: SEC_GPIOD {
_marker: PhantomData,
},
SEC_GPIOE: SEC_GPIOE {
_marker: PhantomData,
},
SEC_GPIOF: SEC_GPIOF {
_marker: PhantomData,
},
SEC_GPIOG: SEC_GPIOG {
_marker: PhantomData,
},
GPIOH: GPIOH {
_marker: PhantomData,
},
SEC_GPIOH: SEC_GPIOH {
_marker: PhantomData,
},
TAMP: TAMP {
_marker: PhantomData,
},
SEC_TAMP: SEC_TAMP {
_marker: PhantomData,
},
I2C1: I2C1 {
_marker: PhantomData,
},
I2C2: I2C2 {
_marker: PhantomData,
},
I2C3: I2C3 {
_marker: PhantomData,
},
I2C4: I2C4 {
_marker: PhantomData,
},
SEC_I2C1: SEC_I2C1 {
_marker: PhantomData,
},
SEC_I2C2: SEC_I2C2 {
_marker: PhantomData,
},
SEC_I2C3: SEC_I2C3 {
_marker: PhantomData,
},
SEC_I2C4: SEC_I2C4 {
_marker: PhantomData,
},
ICACHE: ICACHE {
_marker: PhantomData,
},
SEC_ICACHE: SEC_ICACHE {
_marker: PhantomData,
},
IWDG: IWDG {
_marker: PhantomData,
},
SEC_IWDG: SEC_IWDG {
_marker: PhantomData,
},
LPTIM1: LPTIM1 {
_marker: PhantomData,
},
LPTIM2: LPTIM2 {
_marker: PhantomData,
},
LPTIM3: LPTIM3 {
_marker: PhantomData,
},
SEC_LPTIM1: SEC_LPTIM1 {
_marker: PhantomData,
},
SEC_LPTIM2: SEC_LPTIM2 {
_marker: PhantomData,
},
SEC_LPTIM3: SEC_LPTIM3 {
_marker: PhantomData,
},
GTZC_MPCBB1: GTZC_MPCBB1 {
_marker: PhantomData,
},
GTZC_MPCBB2: GTZC_MPCBB2 {
_marker: PhantomData,
},
PWR: PWR {
_marker: PhantomData,
},
SEC_PWR: SEC_PWR {
_marker: PhantomData,
},
RCC: RCC {
_marker: PhantomData,
},
SEC_RCC: SEC_RCC {
_marker: PhantomData,
},
RTC: RTC {
_marker: PhantomData,
},
SEC_RTC: SEC_RTC {
_marker: PhantomData,
},
SAI1: SAI1 {
_marker: PhantomData,
},
SAI2: SAI2 {
_marker: PhantomData,
},
SEC_SAI1: SEC_SAI1 {
_marker: PhantomData,
},
SEC_SAI2: SEC_SAI2 {
_marker: PhantomData,
},
DMA1: DMA1 {
_marker: PhantomData,
},
SEC_DMA1: SEC_DMA1 {
_marker: PhantomData,
},
DMA2: DMA2 {
_marker: PhantomData,
},
SEC_DMA2: SEC_DMA2 {
_marker: PhantomData,
},
SEC_GTZC_MPCBB1: SEC_GTZC_MPCBB1 {
_marker: PhantomData,
},
SEC_GTZC_MPCBB2: SEC_GTZC_MPCBB2 {
_marker: PhantomData,
},
SPI1: SPI1 {
_marker: PhantomData,
},
SPI2: SPI2 {
_marker: PhantomData,
},
SPI3: SPI3 {
_marker: PhantomData,
},
SEC_SPI1: SEC_SPI1 {
_marker: PhantomData,
},
SEC_SPI2: SEC_SPI2 {
_marker: PhantomData,
},
SEC_SPI3: SEC_SPI3 {
_marker: PhantomData,
},
TIM1: TIM1 {
_marker: PhantomData,
},
SEC_TIM1: SEC_TIM1 {
_marker: PhantomData,
},
TIM15: TIM15 {
_marker: PhantomData,
},
SEC_TIM15: SEC_TIM15 {
_marker: PhantomData,
},
TIM16: TIM16 {
_marker: PhantomData,
},
SEC_TIM16: SEC_TIM16 {
_marker: PhantomData,
},
TIM17: TIM17 {
_marker: PhantomData,
},
SEC_TIM17: SEC_TIM17 {
_marker: PhantomData,
},
TIM2: TIM2 {
_marker: PhantomData,
},
SEC_TIM2: SEC_TIM2 {
_marker: PhantomData,
},
TIM3: TIM3 {
_marker: PhantomData,
},
SEC_TIM3: SEC_TIM3 {
_marker: PhantomData,
},
TIM4: TIM4 {
_marker: PhantomData,
},
SEC_TIM4: SEC_TIM4 {
_marker: PhantomData,
},
TIM5: TIM5 {
_marker: PhantomData,
},
SEC_TIM5: SEC_TIM5 {
_marker: PhantomData,
},
TIM6: TIM6 {
_marker: PhantomData,
},
SEC_TIM6: SEC_TIM6 {
_marker: PhantomData,
},
TIM7: TIM7 {
_marker: PhantomData,
},
SEC_TIM7: SEC_TIM7 {
_marker: PhantomData,
},
DAC: DAC {
_marker: PhantomData,
},
SEC_DAC: SEC_DAC {
_marker: PhantomData,
},
OPAMP: OPAMP {
_marker: PhantomData,
},
SEC_OPAMP: SEC_OPAMP {
_marker: PhantomData,
},
TIM8: TIM8 {
_marker: PhantomData,
},
SEC_TIM8: SEC_TIM8 {
_marker: PhantomData,
},
GTZC_TZIC: GTZC_TZIC {
_marker: PhantomData,
},
SEC_GTZC_TZIC: SEC_GTZC_TZIC {
_marker: PhantomData,
},
GTZC_TZSC: GTZC_TZSC {
_marker: PhantomData,
},
SEC_GTZC_TZSC: SEC_GTZC_TZSC {
_marker: PhantomData,
},
WWDG: WWDG {
_marker: PhantomData,
},
SEC_WWDG: SEC_WWDG {
_marker: PhantomData,
},
SYSCFG: SYSCFG {
_marker: PhantomData,
},
SEC_SYSCFG: SEC_SYSCFG {
_marker: PhantomData,
},
DBGMCU: DBGMCU {
_marker: PhantomData,
},
USB: USB {
_marker: PhantomData,
},
SEC_USB: SEC_USB {
_marker: PhantomData,
},
OCTOSPI1: OCTOSPI1 {
_marker: PhantomData,
},
SEC_OCTOSPI1: SEC_OCTOSPI1 {
_marker: PhantomData,
},
LPUART1: LPUART1 {
_marker: PhantomData,
},
SEC_LPUART1: SEC_LPUART1 {
_marker: PhantomData,
},
COMP: COMP {
_marker: PhantomData,
},
SEC_COMP: SEC_COMP {
_marker: PhantomData,
},
VREFBUF: VREFBUF {
_marker: PhantomData,
},
SEC_VREFBUF: SEC_VREFBUF {
_marker: PhantomData,
},
TSC: TSC {
_marker: PhantomData,
},
SEC_TSC: SEC_TSC {
_marker: PhantomData,
},
UCPD1: UCPD1 {
_marker: PhantomData,
},
SEC_UCPD1: SEC_UCPD1 {
_marker: PhantomData,
},
FDCAN1: FDCAN1 {
_marker: PhantomData,
},
SEC_FDCAN1: SEC_FDCAN1 {
_marker: PhantomData,
},
CRC: CRC {
_marker: PhantomData,
},
SEC_CRC: SEC_CRC {
_marker: PhantomData,
},
CRS: CRS {
_marker: PhantomData,
},
SEC_CRS: SEC_CRS {
_marker: PhantomData,
},
USART1: USART1 {
_marker: PhantomData,
},
SEC_USART1: SEC_USART1 {
_marker: PhantomData,
},
USART2: USART2 {
_marker: PhantomData,
},
SEC_USART2: SEC_USART2 {
_marker: PhantomData,
},
USART3: USART3 {
_marker: PhantomData,
},
SEC_USART3: SEC_USART3 {
_marker: PhantomData,
},
UART4: UART4 {
_marker: PhantomData,
},
UART5: UART5 {
_marker: PhantomData,
},
SEC_UART4: SEC_UART4 {
_marker: PhantomData,
},
SEC_UART5: SEC_UART5 {
_marker: PhantomData,
},
ADC_COMMON: ADC_COMMON {
_marker: PhantomData,
},
SEC_ADC_COMMON: SEC_ADC_COMMON {
_marker: PhantomData,
},
ADC1: ADC1 {
_marker: PhantomData,
},
SEC_ADC1: SEC_ADC1 {
_marker: PhantomData,
},
ADC2: ADC2 {
_marker: PhantomData,
},
SEC_ADC2: SEC_ADC2 {
_marker: PhantomData,
},
NVIC_STIR: NVIC_STIR {
_marker: PhantomData,
},
FMC: FMC {
_marker: PhantomData,
},
SEC_FMC: SEC_FMC {
_marker: PhantomData,
},
RNG: RNG {
_marker: PhantomData,
},
SEC_RNG: SEC_RNG {
_marker: PhantomData,
},
SDMMC1: SDMMC1 {
_marker: PhantomData,
},
SEC_SDMMC1: SEC_SDMMC1 {
_marker: PhantomData,
},
HASH: HASH {
_marker: PhantomData,
},
SEC_HASH: SEC_HASH {
_marker: PhantomData,
},
}
}
}
|
use actix::{
dev::{MessageResponse, OneshotSender},
Actor, Message,
};
use chrono::{DateTime, Utc};
use yahoo_finance_api::Quote;
use crate::{cli_error::SymbolError, model::ProcessedQuote};
pub struct FetchAll;
impl Message for FetchAll {
type Result = ();
}
pub struct Fetch {
pub symbol: String,
pub start: DateTime<Utc>,
pub end: DateTime<Utc>,
}
impl Fetch {
pub fn new(symbol: String, start: DateTime<Utc>, end: DateTime<Utc>) -> Self {
Fetch { symbol, start, end }
}
}
impl Message for Fetch {
type Result = ();
}
pub struct ProcessQuote {
pub symbol: String,
pub start: DateTime<Utc>,
pub quotes: Vec<Quote>,
}
impl ProcessQuote {
pub fn new(symbol: String, start: DateTime<Utc>, quotes: Vec<Quote>) -> Self {
ProcessQuote {
symbol,
start,
quotes,
}
}
}
impl Message for ProcessQuote {
type Result = ();
}
pub struct CalcQuoteData(pub Vec<f64>);
impl Message for CalcQuoteData {
type Result = CalculatedData;
}
pub struct CalculatedData {
pub min: Option<f64>,
pub max: Option<f64>,
pub sma: Option<Vec<f64>>,
pub percent_diff: Option<f64>,
pub absolute_diff: Option<f64>,
}
impl CalculatedData {
pub fn new(
min: Option<f64>,
max: Option<f64>,
sma: Option<Vec<f64>>,
percent_diff: Option<f64>,
absolute_diff: Option<f64>,
) -> Self {
CalculatedData {
min,
max,
sma,
percent_diff,
absolute_diff,
}
}
}
impl<A, M> MessageResponse<A, M> for CalculatedData
where
A: Actor,
M: Message<Result = CalculatedData>,
{
fn handle(self, _ctx: &mut A::Context, tx: Option<OneshotSender<M::Result>>) {
if let Some(tx) = tx {
if tx.send(self).is_err() {
eprintln!("Error sending CalculatedData");
}
}
}
}
pub struct HandleError(pub SymbolError);
impl Message for HandleError {
type Result = ();
}
pub struct PrintString(pub String);
impl Message for PrintString {
type Result = ();
}
pub struct PrintProcessedQuote(pub ProcessedQuote);
impl Message for PrintProcessedQuote {
type Result = ();
}
|
use async_trait::async_trait;
use stable_eyre::eyre;
use tokio::sync::mpsc::Sender;
use toml::value::Datetime;
use super::{util, Graphql, Producer};
#[derive(Debug)]
pub struct ListReposForOrg {
graphql: Graphql,
org_name: String,
repo_names: Vec<String>,
start_date: Datetime,
end_date: Datetime,
}
impl ListReposForOrg {
pub fn new(
graphql: Graphql,
org_name: String,
repo_names: Vec<String>,
start_date: Datetime,
end_date: Datetime,
) -> Self {
ListReposForOrg {
graphql,
org_name,
repo_names,
start_date,
end_date,
}
}
}
#[async_trait]
impl Producer for ListReposForOrg {
fn column_names(&self) -> Vec<String> {
vec![String::from("Repository Name"), String::from("# of PRs")]
}
async fn producer_task(mut self, tx: Sender<Vec<String>>) -> Result<(), eyre::Error> {
for repo in &self.repo_names {
let count_prs = util::count_pull_requests(
&mut self.graphql,
&self.org_name,
&repo,
&self.start_date,
&self.end_date,
)
.await?;
tx.send(vec![repo.to_owned(), count_prs.to_string()])
.await?;
}
Ok(())
}
}
|
use cgmath::{Point3, Vector3, InnerSpace};
use std::cmp::{PartialOrd, Ord, Ordering};
#[derive(Debug, Clone, PartialEq)]
pub struct Intersection {
pub ray_t: f64,
pub origin: Point3<f64>,
pub normal: Vector3<f64>,
}
impl Intersection {
pub fn new(ray_t: f64, origin: Point3<f64>, normal: Vector3<f64>) -> Self {
let normal = normal.normalize();
Self { ray_t, origin, normal }
}
}
impl Eq for Intersection { }
impl PartialOrd for Intersection {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
self.ray_t.partial_cmp(&other.ray_t)
}
}
impl Ord for Intersection {
fn cmp(&self, other: &Self) -> Ordering {
self.partial_cmp(other).expect("invalid value for ray_t")
}
}
#[cfg(test)]
mod test;
|
use std::cmp::max;
use std::io::{self, BufRead};
fn mass_to_fuel(mass: u64) -> u64 {
max(mass / 3, 2) - 2
}
fn mass_to_fuel_recursive(mass: u64) -> u64 {
let fuel = mass_to_fuel(mass);
if fuel <= 6 {
return fuel;
}
fuel + mass_to_fuel_recursive(fuel)
}
fn part_one() {
let stdin = io::stdin();
let lines = stdin.lock().lines();
let sum: u64 = lines
.map(|res| res.unwrap())
.map(|line| line.parse::<u64>().unwrap())
.map(mass_to_fuel)
.sum();
println!("\n{}", sum);
}
fn part_two() {
let stdin = io::stdin();
let lines = stdin.lock().lines();
let sum: u64 = lines
.map(|res| res.unwrap())
.map(|line| line.parse::<u64>().unwrap())
.map(mass_to_fuel_recursive)
.sum();
println!("\n{}", sum);
}
fn main() {
part_two();
}
|
extern crate libc;
#[link(name = "mt", kind = "static")]
extern {
fn sgrnd_(seed: *const libc::c_int);
fn grnd_() -> libc::c_double;
fn gaussrnd_(rr: *mut libc::c_double);
}
pub fn sgrnd(seed: i32) {
unsafe { sgrnd_(&seed); }
}
pub fn seed(seed: &[u8]) {
sgrnd(*::utils::repack_u8s(&seed).get(0).unwrap_or(&0));
}
pub fn grnd() -> f64 {
unsafe { grnd_() }
}
pub fn gaussrnd() -> f64 {
unsafe {
let mut rr = ::std::mem::uninitialized();
gaussrnd_(&mut rr);
rr
}
}
|
use std::env;
use std::fs;
#[derive(Copy, Clone, Debug)]
enum Dir {
N = 0,
E = 90,
S = 180,
W = 270,
}
impl Dir {
fn from_val(val: i32) -> Dir {
match val {
0 => Dir::N,
90 => Dir::E,
180 => Dir::S,
270 => Dir::W,
_ => panic!("Invalid direction: {}", val),
}
}
fn rotate(&self, amount: &i32) -> Dir {
Dir::from_val(((*self as i32) + amount + 360) % 360)
}
}
#[derive(Debug)]
struct Motion {
dir: Dir,
amount: i32,
}
impl Motion {
fn execute(&self, pos: Position) -> Position {
match *self {
Motion {
dir: Dir::N,
amount,
} => Position {
y: pos.y + amount,
..pos
},
Motion {
dir: Dir::E,
amount,
} => Position {
x: pos.x + amount,
..pos
},
Motion {
dir: Dir::S,
amount,
} => Position {
y: pos.y - amount,
..pos
},
Motion {
dir: Dir::W,
amount,
} => Position {
x: pos.x - amount,
..pos
},
}
}
}
#[derive(Debug)]
enum Op {
F(i32),
L(i32),
R(i32),
}
impl Op {
fn execute(&self, pos: Position) -> Position {
match *self {
Op::F(amount) => {
let motion = Motion {
dir: pos.dir,
amount: amount,
};
motion.execute(pos)
}
Op::R(amount) => Position {
dir: pos.dir.rotate(&amount),
..pos
},
Op::L(amount) => Position {
dir: pos.dir.rotate(&(-1 * amount)),
..pos
},
}
}
}
#[derive(Debug)]
enum Command {
Motion(Motion),
Op(Op),
}
impl Command {
fn execute(&self, pos: Position) -> Position {
match self {
Command::Motion(motion) => motion.execute(pos),
Command::Op(op) => op.execute(pos),
}
}
}
#[derive(Debug)]
struct Position {
x: i32,
y: i32,
}
fn main() {
let args: Vec<String> = env::args().collect();
let filename = &args[1];
let file = fs::read_to_string(filename).expect("Couldn't read file");
let commands: Vec<Command> = file
.lines()
.map(|line: &str| {
let mut chars = line.chars();
let direction = chars.nth(0).expect("Empty string");
let amount = &line[1..];
let amount: i32 = String::from(amount).parse().expect("Couldn't parse number");
match direction {
'N' => Command::Motion(Motion {
dir: Dir::N,
amount,
}),
'S' => Command::Motion(Motion {
dir: Dir::S,
amount,
}),
'E' => Command::Motion(Motion {
dir: Dir::E,
amount,
}),
'W' => Command::Motion(Motion {
dir: Dir::W,
amount,
}),
'L' => Command::Op(Op::L(amount)),
'R' => Command::Op(Op::R(amount)),
'F' => Command::Op(Op::F(amount)),
_ => panic!("Invalid command"),
}
})
.collect();
let mut waypointRel = Position { x: 10, y: 1 };
let mut
for command in commands {
waypointRel = command.execute(waypointRel);
println!("{:?}, {:?}", command, waypointRel)
}
println!(
"Pos: ({}, {}), Manhattan distance: {}",
waypointRel.x,
waypointRel.y,
waypointRel.x + waypointRel.y
);
}
|
use serenity::{
client::{bridge::gateway::ShardId, Context},
framework::standard::{macros::command, CommandResult},
model::channel::Message,
};
use crate::{
common::{get_locale, tt},
data::{DatabasePool, ShardManagerContainer},
reply,
};
#[command]
async fn ping(ctx: &Context, msg: &Message) -> CommandResult {
let data = ctx.data.read().await;
let shard_manager = match data.get::<ShardManagerContainer>() {
Some(v) => v,
None => {
reply!((ctx, msg) => "Unexpected Error");
return Ok(());
}
};
let pool = {
let data = ctx.data.as_ref().read().await;
data.get::<DatabasePool>().unwrap().clone()
};
let locale = get_locale(&pool, msg).await;
let manager = shard_manager.lock().await;
let runners = manager.runners.lock().await;
let runner = match runners.get(&ShardId(ctx.shard_id.into())) {
Some(runner) => runner,
None => {
reply!((ctx, msg) => "{}", tt(&locale, "PingError"));
return Ok(());
}
};
let latency = match runner.latency {
Some(latency) => latency,
None => {
reply!((ctx, msg) => "{}", tt(&locale, "PingRetry"));
return Ok(());
}
};
reply!((ctx, msg) => "🏓 Pong! **{}** ms", latency.as_millis());
Ok(())
}
|
use crate::context::Data;
use crate::http::{GQLError, GQLRequest, GQLResponse};
use crate::{
ConnectionTransport, Error, FieldError, FieldResult, ObjectType, QueryBuilder, QueryError,
QueryResponse, Result, Schema, SubscriptionStreams, SubscriptionType, Variables,
};
use bytes::Bytes;
use std::collections::HashMap;
use std::sync::Arc;
#[derive(Serialize, Deserialize)]
struct OperationMessage {
#[serde(rename = "type")]
ty: String,
#[serde(skip_serializing_if = "Option::is_none")]
id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
payload: Option<serde_json::Value>,
}
/// WebSocket transport for subscription
#[derive(Default)]
pub struct WebSocketTransport {
id_to_sid: HashMap<String, usize>,
sid_to_id: HashMap<usize, String>,
data: Arc<Data>,
init_context_data: Option<Box<dyn Fn(serde_json::Value) -> FieldResult<Data> + Send + Sync>>,
}
impl WebSocketTransport {
/// Creates a websocket transport and sets the function that converts the `payload` of the `connect_init` message to `Data`.
pub fn new<F: Fn(serde_json::Value) -> FieldResult<Data> + Send + Sync + 'static>(
init_context_data: F,
) -> Self {
WebSocketTransport {
init_context_data: Some(Box::new(init_context_data)),
..WebSocketTransport::default()
}
}
}
#[async_trait::async_trait]
impl ConnectionTransport for WebSocketTransport {
type Error = FieldError;
async fn handle_request<Query, Mutation, Subscription>(
&mut self,
schema: &Schema<Query, Mutation, Subscription>,
streams: &mut SubscriptionStreams,
data: Bytes,
) -> std::result::Result<Option<Vec<Bytes>>, Self::Error>
where
Query: ObjectType + Sync + Send + 'static,
Mutation: ObjectType + Sync + Send + 'static,
Subscription: SubscriptionType + Sync + Send + 'static,
{
match serde_json::from_slice::<OperationMessage>(&data) {
Ok(msg) => match msg.ty.as_str() {
"connection_init" => {
if let Some(payload) = msg.payload {
if let Some(init_context_data) = &self.init_context_data {
self.data = Arc::new(init_context_data(payload)?);
}
}
Ok(Some(vec![serde_json::to_vec(&OperationMessage {
ty: "connection_ack".to_string(),
id: None,
payload: None,
})
.unwrap()
.into()]))
}
"start" => {
if let (Some(id), Some(payload)) = (msg.id, msg.payload) {
if let Ok(request) = serde_json::from_value::<GQLRequest>(payload) {
let variables = request
.variables
.map(|value| Variables::parse_from_json(value).ok())
.flatten()
.unwrap_or_default();
match schema
.create_subscription_stream(
&request.query,
request.operation_name.as_deref(),
variables.clone(),
Some(self.data.clone()),
)
.await
{
Ok(stream) => {
let stream_id = streams.add(stream);
self.id_to_sid.insert(id.clone(), stream_id);
self.sid_to_id.insert(stream_id, id);
Ok(None)
}
Err(Error::Query { err, .. })
if err == QueryError::NotSupported =>
{
// Is query or mutation
let mut builder =
QueryBuilder::new(&request.query).variables(variables);
if let Some(operation_name) = &request.operation_name {
builder = builder.operation_name(operation_name);
}
match builder.execute(schema).await {
Ok(resp) => Ok(Some(vec![
serde_json::to_vec(&OperationMessage {
ty: "data".to_string(),
id: Some(id.clone()),
payload: Some(
serde_json::to_value(&GQLResponse(Ok(resp)))
.unwrap(),
),
})
.unwrap()
.into(),
serde_json::to_vec(&OperationMessage {
ty: "complete".to_string(),
id: Some(id),
payload: None,
})
.unwrap()
.into(),
])),
Err(err) => {
Ok(Some(vec![serde_json::to_vec(&OperationMessage {
ty: "error".to_string(),
id: Some(id),
payload: Some(
serde_json::to_value(GQLError(&err)).unwrap(),
),
})
.unwrap()
.into()]))
}
}
}
Err(err) => Ok(Some(vec![serde_json::to_vec(&OperationMessage {
ty: "error".to_string(),
id: Some(id),
payload: Some(serde_json::to_value(GQLError(&err)).unwrap()),
})
.unwrap()
.into()])),
}
} else {
Ok(None)
}
} else {
Ok(None)
}
}
"stop" => {
if let Some(id) = msg.id {
if let Some(sid) = self.id_to_sid.remove(&id) {
self.sid_to_id.remove(&sid);
streams.remove(sid);
return Ok(Some(vec![serde_json::to_vec(&OperationMessage {
ty: "complete".to_string(),
id: Some(id),
payload: None,
})
.unwrap()
.into()]));
}
}
Ok(None)
}
"connection_terminate" => Err("connection_terminate".into()),
_ => Err("Unknown op".into()),
},
Err(err) => Err(err.into()),
}
}
fn handle_response(&mut self, id: usize, res: Result<serde_json::Value>) -> Option<Bytes> {
if let Some(id) = self.sid_to_id.get(&id) {
match res {
Ok(value) => Some(
serde_json::to_vec(&OperationMessage {
ty: "data".to_string(),
id: Some(id.clone()),
payload: Some(
serde_json::to_value(GQLResponse(Ok(QueryResponse {
data: value,
extensions: None,
cache_control: Default::default(),
})))
.unwrap(),
),
})
.unwrap()
.into(),
),
Err(err) => Some(
serde_json::to_vec(&OperationMessage {
ty: "error".to_string(),
id: Some(id.to_string()),
payload: Some(serde_json::to_value(GQLError(&err)).unwrap()),
})
.unwrap()
.into(),
),
}
} else {
None
}
}
}
|
use fmod_studio;
use fmod_studio::guid::Guid;
use fmod_studio::error::FmodError;
pub use audio::update::AudioUpdate;
pub mod update;
pub struct System {
pub studio: fmod_studio::system::System,
}
impl System {
pub fn get_id(&self, object: &str) -> Option<Guid> {
match self.studio.lookup_id(object) {
Ok(guid) => Some(guid),
Err(FmodError::EventNotFound) => None,
Err(err) => {
eprintln!(
"[WARNING] event lookup of {:?}: {:?}({})",
object,
err,
err.description()
);
None
}
}
}
pub fn play_oneoff(&self, id: &Guid) {
self.studio
.get_event_by_id(id)
.and_then(|desc| desc.create_instance())
.and_then(|inst| inst.start())
.map_err(|err| {
eprintln!("[WARNING] play_oneoff: {}", err.description())
})
.ok();
}
}
impl Default for System {
fn default() -> Self {
let mut studio = fmod_studio::system::System::new(512, true).unwrap();
studio
.load_bank_file("resources/audio/fmod/Desktop/Master Bank.bank", false)
.unwrap();
studio
.load_bank_file(
"resources/audio/fmod/Desktop/Master Bank.strings.bank",
false,
)
.unwrap();
System { studio }
}
}
|
extern crate ini;
use self::ini::Ini;
extern crate time;
#[cfg(target_os = "macos")]
use super::osx;
use std::env;
use std::fs;
use std::path;
const INIFILE: &'static str = "connectr.ini";
pub struct Settings {
pub port: u32,
pub secret: String,
pub client_id: String,
pub access_token: Option<String>,
pub refresh_token: Option<String>,
pub expire_utc: Option<u64>,
pub presets: Vec<(String,String)>,
}
#[cfg(target_os = "macos")]
fn bundled_ini() -> String {
match osx::bundled_resource_path("connectr", "ini") {
Some(path) => path,
None => String::new(),
}
}
#[cfg(not(target_os = "macos"))]
fn bundled_ini() -> String {
String::new()
}
fn inifile() -> String {
// Try to load INI file from home directory
let path = format!("{}/.{}", env::home_dir().unwrap().display(), INIFILE);
if path::Path::new(&path).exists() {
info!("Found config: {}", path);
return path;
}
// If it doesn't exist, try to copy the template from the app bundle, if
// such a thing exists.
let bundle_ini = bundled_ini();
if path::Path::new(&bundle_ini).exists() {
info!("Copied config: {}", bundle_ini);
let _ = fs::copy(bundle_ini, path.clone());
return path;
}
// Default to looking in current working directory
let path = INIFILE.to_string();
if path::Path::new(&path).exists() {
info!("Found config: {}", path);
return path;
}
String::new()
}
pub fn read_settings() -> Option<Settings> {
info!("Attempting to read config file.");
let conf = match Ini::load_from_file(&inifile()) {
Ok(c) => c,
Err(e) => {
info!("Load file error: {}", e);
// No connectr.ini found. Generate a junk one in-memory, which
// will fail shortly after with the nice error message.
let mut c = Ini::new();
info!("No config file found.");
c.with_section(Some("connectr".to_owned()))
.set("port", 5657.to_string());
c.with_section(Some("application".to_owned()))
.set("secret", "<PLACEHOLDER>".to_string())
.set("client_id", "<PLACEHOLDER>".to_string());
c
}
};
let section = conf.section(Some("connectr".to_owned())).unwrap();
let port = section.get("port").unwrap().parse().unwrap();
let section = conf.section(Some("application".to_owned())).unwrap();
let secret = section.get("secret").unwrap();
let client_id = section.get("client_id").unwrap();
if client_id.starts_with('<') || secret.starts_with('<') {
error!("Invalid or missing configuration. Cannot continue.");
println!("");
println!("ERROR: Spotify Client ID or Secret not set in connectr.ini!");
println!("");
println!("Create a Spotify application at https://developer.spotify.com/my-applications/ and");
println!("add the client ID and secret to connectr.ini.");
println!("");
println!("Be sure to add a redirect URI of http://127.0.0.1:<PORT> to your Spotify application,");
println!("and make sure the port matches in connectr.ini.");
println!("");
return None;
}
let mut access = None;
let mut refresh = None;
let mut expire_utc = None;
if let Some(section) = conf.section(Some("tokens".to_owned())) {
access = Some(section.get("access").unwrap().clone());
refresh = Some(section.get("refresh").unwrap().clone());
expire_utc = Some(section.get("expire").unwrap().parse().unwrap());
println!("Read access token from INI!");
}
let mut presets = Vec::<(String,String)>::new();
if let Some(section) = conf.section(Some("presets".to_owned())) {
for (key, value) in section {
presets.push((key.to_owned(), value.to_owned()));
}
}
Some(Settings { secret: secret.to_string(), client_id: client_id.to_string(), port: port,
access_token: access, refresh_token: refresh, expire_utc: expire_utc,
presets: presets})
}
pub type SettingsError = String;
pub fn save_tokens(access: &str, refresh: &str, expire_utc: u64) -> Result<(), SettingsError> {
let mut conf = Ini::load_from_file(&inifile()).unwrap();
conf.with_section(Some("tokens".to_owned()))
.set("access", access)
.set("refresh", refresh)
.set("expire", expire_utc.to_string());
conf.write_to_file(&inifile()).unwrap();
Ok(())
}
|
use std::sync::mpsc::channel;
use std::thread;
use criterion::{black_box, criterion_group, criterion_main, Criterion};
use hydroflow::hydroflow_syntax;
use hydroflow::scheduled::graph_ext::GraphExt;
use static_assertions::const_assert;
use timely::dataflow::operators::{Inspect, Map, ToStream};
const NUM_OPS: usize = 20;
const NUM_INTS: usize = 1_000_000;
fn benchmark_pipeline(c: &mut Criterion) {
c.bench_function("identity/pipeline", |b| {
b.iter(|| {
let (input, mut output) = channel();
for _ in 0..NUM_OPS {
let (tx, mut rx) = channel();
std::mem::swap(&mut output, &mut rx);
thread::spawn(move || {
for elt in rx {
tx.send(elt).unwrap();
}
});
}
for i in 0..NUM_INTS {
input.send(i).unwrap();
}
drop(input);
for elt in output {
black_box(elt);
}
});
});
}
// This benchmark just copies around a bunch of data with basically zero
// overhead, so this should theoretically be the fastest achievable (with a
// single thread).
fn benchmark_raw_copy(c: &mut Criterion) {
c.bench_function("identity/raw", |b| {
b.iter(|| {
let mut data: Vec<_> = (0..NUM_INTS).collect();
let mut next = Vec::new();
for _ in 0..NUM_OPS {
next.append(&mut data);
std::mem::swap(&mut data, &mut next);
}
for elt in data {
black_box(elt);
}
})
});
}
fn benchmark_iter(c: &mut Criterion) {
c.bench_function("identity/iter", |b| {
b.iter(|| {
let iter = 0..NUM_INTS;
///// MAGIC NUMBER!!!!!!!! is NUM_OPS
seq_macro::seq!(_ in 0..20 {
let iter = iter.map(black_box);
});
let data: Vec<_> = iter.collect();
for elt in data {
black_box(elt);
}
});
});
}
fn benchmark_iter_collect(c: &mut Criterion) {
c.bench_function("identity/iter-collect", |b| {
b.iter(|| {
let mut data: Vec<_> = (0..NUM_INTS).collect();
for _ in 0..NUM_OPS {
let iter = data.into_iter();
let iter = iter.map(black_box);
data = iter.collect();
}
for elt in data {
black_box(elt);
}
});
});
}
fn benchmark_timely(c: &mut Criterion) {
c.bench_function("identity/timely", |b| {
b.iter(|| {
timely::example(|scope| {
let mut op = (0..NUM_INTS).to_stream(scope);
for _ in 0..NUM_OPS {
op = op.map(black_box)
}
op.inspect(|i| {
black_box(i);
});
});
})
});
}
fn benchmark_hydroflow_compiled(c: &mut Criterion) {
use hydroflow::pusherator::{InputBuild, Pusherator, PusheratorBuild};
c.bench_function("identity/hydroflow/compiled", |b| {
b.iter(|| {
let mut pusherator = InputBuild::<usize>::new()
.map(black_box)
.map(black_box)
.map(black_box)
.map(black_box)
.map(black_box)
.map(black_box)
.map(black_box)
.map(black_box)
.map(black_box)
.map(black_box)
.map(black_box)
.map(black_box)
.map(black_box)
.map(black_box)
.map(black_box)
.map(black_box)
.map(black_box)
.map(black_box)
.map(black_box)
.map(black_box)
.for_each(|x| {
black_box(x);
});
for i in 0..NUM_INTS {
pusherator.give(i);
}
});
});
}
fn benchmark_hydroflow(c: &mut Criterion) {
use hydroflow::scheduled::graph::Hydroflow;
use hydroflow::scheduled::handoff::{Iter, VecHandoff};
c.bench_function("identity/hydroflow", |b| {
b.iter(|| {
let mut df = Hydroflow::new();
let (next_send, mut next_recv) = df.make_edge::<_, VecHandoff<usize>>("end");
let mut sent = false;
df.add_subgraph_source("source", next_send, move |_ctx, send| {
if !sent {
sent = true;
send.give(Iter(0..NUM_INTS));
}
});
for _ in 0..NUM_OPS {
let (next_send, next_next_recv) = df.make_edge("handoff");
df.add_subgraph_in_out("identity", next_recv, next_send, |_ctx, recv, send| {
send.give(Iter(recv.take_inner().into_iter()));
});
next_recv = next_next_recv;
}
df.add_subgraph_sink("sink", next_recv, |_ctx, recv| {
for x in recv.take_inner() {
black_box(x);
}
});
df.run_available();
});
});
}
fn benchmark_hydroflow_surface(c: &mut Criterion) {
const_assert!(NUM_OPS == 20); // This benchmark is hardcoded for 20 ops, so assert that NUM_OPS is 20.
c.bench_function("identity/hydroflow/surface", |b| {
b.iter(|| {
let mut df = hydroflow_syntax! {
source_iter(black_box(0..NUM_INTS))
-> map(black_box)
-> map(black_box)
-> map(black_box)
-> map(black_box)
-> map(black_box)
-> map(black_box)
-> map(black_box)
-> map(black_box)
-> map(black_box)
-> map(black_box)
-> map(black_box)
-> map(black_box)
-> map(black_box)
-> map(black_box)
-> map(black_box)
-> map(black_box)
-> map(black_box)
-> map(black_box)
-> map(black_box)
-> map(black_box)
-> for_each(|x| { black_box(x); });
};
df.run_available();
})
});
}
criterion_group!(
identity_dataflow,
benchmark_timely,
benchmark_pipeline,
benchmark_iter,
benchmark_iter_collect,
benchmark_raw_copy,
benchmark_hydroflow,
benchmark_hydroflow_compiled,
benchmark_hydroflow_surface,
);
criterion_main!(identity_dataflow);
|
use crate::*;
use crate::{percolator::TimestampOracle, rpc::kvs_service::*};
use std::{net::SocketAddr, time::Duration};
use tonic::{Request, Response, Status};
/// Kvs Server
// #[derive(Clone)]
pub struct KvsBasicServer {
store: MultiStore,
addr: SocketAddr,
ts_oracle: TimestampOracle,
}
impl KvsBasicServer {
/// Construct a new Kvs Server from given engine at specific path.
/// Use `run()` to listen on given addr.
pub fn new(store: MultiStore, addr: SocketAddr, ts_oracle: TimestampOracle) -> Result<Self> {
Ok(KvsBasicServer {
store,
addr,
ts_oracle,
})
}
pub fn start(self) -> Result<()> {
let threaded_rt = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.unwrap();
let handle = std::thread::spawn(move || {
threaded_rt.block_on(async move {
let addr = self.addr.clone();
tonic::transport::Server::builder()
.add_service(KvRpcServer::new(self))
.serve(addr)
.await
.map_err(|e| KvError::StringError(e.to_string()))
})
});
handle.join().unwrap()
}
fn lock_back_off_or_clean_up(&self, key: String, ts: u64) {
if let Some((lock_key, lock_value)) = self.store.read_lock(key.clone(), None, Some(ts)) {
let primary = lock_value.primary().to_owned();
let primary_ts = lock_key.ts();
if let Some((_pri_lock_key, pri_lock_value)) =
self.store.read_lock(primary.clone(), None, Some(ts))
{
if pri_lock_value.elapsed() >= Duration::from_secs(3) {
self.store.erase_lock(primary, ts);
self.store.erase_lock(key, ts);
}
} else {
if let Some((write_key, write_value)) =
self.store.read_write(primary, Some(primary_ts), None)
{
if write_value.ts() == primary_ts {
let primary_commit_ts = write_key.ts();
self.store.write_write(
key.clone(),
primary_commit_ts,
primary_ts,
lock_value.op(),
);
self.store.erase_lock(key, primary_ts);
}
} else {
self.store.erase_lock(key, ts);
}
}
}
}
}
#[tonic::async_trait]
impl KvRpc for KvsBasicServer {
async fn get_timestamp(
&self,
request: Request<TsRequest>,
) -> std::result::Result<Response<TsReply>, Status> {
let name = request.into_inner().name;
let ts = self.ts_oracle.fetch_one().unwrap();
let reply = TsReply { name, ts };
Ok(tonic::Response::new(reply))
}
async fn txn_get(
&self,
req: Request<GetRequest>,
) -> std::result::Result<Response<GetReply>, Status> {
let req = req.into_inner();
loop {
if self
.store
.read_lock(req.key.clone(), None, Some(req.ts))
.is_some()
{
self.lock_back_off_or_clean_up(req.key.clone(), req.ts);
continue;
}
let last_write = self.store.read_write(req.key.clone(), None, Some(req.ts));
if last_write.is_none() || last_write.clone().unwrap().1.op() == WriteOp::Delete {
return Err(KvRpcError::KeyNotFound)?;
}
let start_ts = last_write.unwrap().1.ts();
let value = self
.store
.read_data(req.key.clone(), Some(start_ts), Some(start_ts))
.unwrap()
.1
.value();
let reply = GetReply {
message: value,
ts: req.ts,
seq: req.seq,
};
return Ok(Response::new(reply));
}
}
async fn txn_prewrite(
&self,
req: Request<PrewriteRequest>,
) -> std::result::Result<Response<PrewriteReply>, Status> {
let req = req.into_inner();
if self
.store
.read_write(req.key.clone(), Some(req.ts), None)
.is_some()
{
return Err(KvRpcError::Abort(String::from("find write after ts")))?;
}
if self.store.read_lock(req.key.clone(), None, None).is_some() {
return Err(KvRpcError::Abort(String::from("find another lock")))?;
}
self.store
.write_data(req.key.clone(), req.ts, req.value.clone());
self.store.write_lock(
req.key.clone(),
req.ts,
req.primary.clone(),
WriteOp::from_i32(req.op).unwrap(),
);
// for update primary ttl
self.store.update_lock(req.primary.clone(), req.ts);
let reply = PrewriteReply {
ok: true,
ts: req.ts,
seq: req.seq,
};
Ok(Response::new(reply))
}
async fn txn_commit(
&self,
request: Request<CommitRequest>,
) -> std::result::Result<Response<CommitReply>, Status> {
let req = request.into_inner();
if req.is_primary {
if self
.store
.read_lock(req.primary, Some(req.start_ts), Some(req.start_ts))
.is_none()
{
return Err(KvRpcError::Abort(String::from("primary lock missing")))?;
}
}
self.store.write_write(
req.key.clone(),
req.commit_ts,
req.start_ts,
WriteOp::from_i32(req.op).unwrap(),
);
self.store.erase_lock(req.key, req.commit_ts);
let reply = CommitReply {
ok: true,
ts: req.commit_ts,
seq: req.seq,
};
Ok(Response::new(reply))
}
}
|
#[macro_use] extern crate proc_macro_starter;
extern crate rocket;
#[derive(FromFormValue)]
pub enum Value {
A,
B,
C,
SomethingElse,
}
pub fn main() { }
|
pub use crate::macros::*;
pub use crate::node::*;
|
#[cfg(not(feature = "std"))]
use crate::no_std_prelude::*;
#[cfg(feature = "std")]
use crate::Sign;
use crate::{
format::parse::{parse, ParseResult, ParsedItems},
Date, DeferredFormat, Duration, OffsetDateTime, Time, UtcOffset, Weekday,
};
#[cfg(feature = "std")]
use core::convert::From;
use core::{
cmp::Ordering,
convert::TryFrom,
ops::{Add, AddAssign, Sub, SubAssign},
time::Duration as StdDuration,
};
#[cfg(feature = "std")]
use std::time::SystemTime;
/// Combined date and time.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
feature = "serde",
serde(
try_from = "crate::serde::PrimitiveDateTime",
into = "crate::serde::PrimitiveDateTime"
)
)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct PrimitiveDateTime {
#[allow(clippy::missing_docs_in_private_items)]
pub(crate) date: Date,
#[allow(clippy::missing_docs_in_private_items)]
pub(crate) time: Time,
}
impl PrimitiveDateTime {
/// Create a new `PrimitiveDateTime` from the provided `Date` and `Time`.
///
/// ```rust
/// # use time::{Date, PrimitiveDateTime, Time};
/// assert_eq!(
/// PrimitiveDateTime::new(Date::from_ymd(2019, 1, 1), Time::midnight()),
/// Date::from_ymd(2019, 1, 1).midnight(),
/// );
/// ```
#[inline(always)]
pub const fn new(date: Date, time: Time) -> Self {
Self { date, time }
}
/// Create a new `PrimitiveDateTime` with the current date and time (UTC).
///
/// ```rust
/// # use time::PrimitiveDateTime;
/// assert!(PrimitiveDateTime::now().year() >= 2019);
/// ```
#[inline(always)]
#[cfg(feature = "std")]
#[cfg_attr(doc, doc(cfg(feature = "std")))]
pub fn now() -> Self {
SystemTime::now().into()
}
/// Midnight, 1 January, 1970 (UTC).
///
/// ```rust
/// # use time::{Date, PrimitiveDateTime, Time};
/// assert_eq!(
/// PrimitiveDateTime::unix_epoch(),
/// Date::from_ymd(1970, 1, 1).midnight()
/// );
/// ```
#[inline(always)]
pub const fn unix_epoch() -> Self {
Self {
date: Date {
year: 1970,
ordinal: 1,
},
time: Time {
hour: 0,
minute: 0,
second: 0,
nanosecond: 0,
},
}
}
/// Create a `PrimitiveDateTime` from the provided [Unix timestamp](https://en.wikipedia.org/wiki/Unix_time).
///
/// ```rust
/// # use time::{Date, PrimitiveDateTime};
/// assert_eq!(
/// PrimitiveDateTime::from_unix_timestamp(0),
/// PrimitiveDateTime::unix_epoch()
/// );
/// assert_eq!(
/// PrimitiveDateTime::from_unix_timestamp(1_546_300_800),
/// Date::from_ymd(2019, 1, 1).midnight(),
/// );
/// ```
#[inline(always)]
pub fn from_unix_timestamp(timestamp: i64) -> Self {
Self::unix_epoch() + Duration::seconds(timestamp)
}
/// Get the [Unix timestamp](https://en.wikipedia.org/wiki/Unix_time)
/// representing the `PrimitiveDateTime`.
///
/// ```rust
/// # use time::{Date, PrimitiveDateTime};
/// assert_eq!(PrimitiveDateTime::unix_epoch().timestamp(), 0);
/// assert_eq!(
/// Date::from_ymd(2019, 1, 1).midnight().timestamp(),
/// 1_546_300_800
/// );
/// ```
#[inline(always)]
pub fn timestamp(self) -> i64 {
(self - Self::unix_epoch()).whole_seconds()
}
/// Get the `Date` component of the `PrimitiveDateTime`.
///
/// ```rust
/// # use time::Date;
/// assert_eq!(
/// Date::from_ymd(2019, 1, 1).midnight().date(),
/// Date::from_ymd(2019, 1, 1)
/// );
/// ```
#[inline(always)]
pub const fn date(self) -> Date {
self.date
}
/// Get the `Time` component of the `PrimitiveDateTime`.
///
/// ```rust
/// # use time::{Date, Time};
/// assert_eq!(Date::from_ymd(2019, 1, 1).midnight().time(), Time::midnight());
#[inline(always)]
pub const fn time(self) -> Time {
self.time
}
/// Get the year of the date.
///
/// ```rust
/// # use time::Date;
/// assert_eq!(Date::from_ymd(2019, 1, 1).midnight().year(), 2019);
/// assert_eq!(Date::from_ymd(2019, 12, 31).midnight().year(), 2019);
/// assert_eq!(Date::from_ymd(2020, 1, 1).midnight().year(), 2020);
/// ```
#[inline(always)]
pub fn year(self) -> i32 {
self.date().year()
}
/// Get the month of the date. If fetching both the month and day, it is
/// more efficient to use [`PrimitiveDateTime::month_day`].
///
/// The returned value will always be in the range `1..=12`.
///
/// ```rust
/// # use time::Date;
/// assert_eq!(Date::from_ymd(2019, 1, 1).midnight().month(), 1);
/// assert_eq!(Date::from_ymd(2019, 12, 31).midnight().month(), 12);
/// ```
#[inline(always)]
pub fn month(self) -> u8 {
self.date().month()
}
/// Get the day of the date. If fetching both the month and day, it is
/// more efficient to use [`PrimitiveDateTime::month_day`].
///
/// The returned value will always be in the range `1..=31`.
///
/// ```rust
/// # use time::Date;
/// assert_eq!(Date::from_ymd(2019, 1, 1).midnight().day(), 1);
/// assert_eq!(Date::from_ymd(2019, 12, 31).midnight().day(), 31);
/// ```
#[inline(always)]
pub fn day(self) -> u8 {
self.date().day()
}
/// Get the month and day of the date. This is more efficient than fetching
/// the components individually.
///
/// The month component will always be in the range `1..=12`;
/// the day component in `1..=31`.
///
/// ```rust
/// # use time::Date;
/// assert_eq!(Date::from_ymd(2019, 1, 1).midnight().month_day(), (1, 1));
/// assert_eq!(
/// Date::from_ymd(2019, 12, 31).midnight().month_day(),
/// (12, 31)
/// );
/// ```
#[inline(always)]
pub fn month_day(self) -> (u8, u8) {
self.date().month_day()
}
/// Get the day of the year.
///
/// The returned value will always be in the range `1..=366` (`1..=365` for
/// common years).
///
/// ```rust
/// # use time::Date;
/// assert_eq!(Date::from_ymd(2019, 1, 1).midnight().ordinal(), 1);
/// assert_eq!(Date::from_ymd(2019, 12, 31).midnight().ordinal(), 365);
/// ```
#[inline(always)]
pub fn ordinal(self) -> u16 {
self.date().ordinal()
}
/// Get the ISO 8601 year and week number.
///
/// ```rust
/// # use time::Date;
/// assert_eq!(
/// Date::from_ymd(2019, 1, 1).midnight().iso_year_week(),
/// (2019, 1)
/// );
/// assert_eq!(
/// Date::from_ymd(2019, 10, 4).midnight().iso_year_week(),
/// (2019, 40)
/// );
/// assert_eq!(
/// Date::from_ymd(2020, 1, 1).midnight().iso_year_week(),
/// (2020, 1)
/// );
/// assert_eq!(
/// Date::from_ymd(2020, 12, 31).midnight().iso_year_week(),
/// (2020, 53)
/// );
/// assert_eq!(
/// Date::from_ymd(2021, 1, 1).midnight().iso_year_week(),
/// (2020, 53)
/// );
/// ```
#[inline]
pub fn iso_year_week(self) -> (i32, u8) {
self.date().iso_year_week()
}
/// Get the ISO week number.
///
/// The returned value will always be in the range `1..=53`.
///
/// ```rust
/// # use time::Date;
/// assert_eq!(Date::from_ymd(2019, 1, 1).midnight().week(), 1);
/// assert_eq!(Date::from_ymd(2019, 10, 4).midnight().week(), 40);
/// assert_eq!(Date::from_ymd(2020, 1, 1).midnight().week(), 1);
/// assert_eq!(Date::from_ymd(2020, 12, 31).midnight().week(), 53);
/// assert_eq!(Date::from_ymd(2021, 1, 1).midnight().week(), 53);
/// ```
#[inline(always)]
pub fn week(self) -> u8 {
self.date().week()
}
/// Get the week number where week 1 begins on the first Sunday.
///
/// The returned value will always be in the range `0..=53`.
///
/// ```rust
/// # use time::Date;
/// assert_eq!(Date::from_ymd(2019, 1, 1).midnight().sunday_based_week(), 0);
/// assert_eq!(Date::from_ymd(2020, 1, 1).midnight().sunday_based_week(), 0);
/// assert_eq!(
/// Date::from_ymd(2020, 12, 31).midnight().sunday_based_week(),
/// 52
/// );
/// assert_eq!(Date::from_ymd(2021, 1, 1).midnight().sunday_based_week(), 0);
/// ```
#[inline(always)]
pub fn sunday_based_week(self) -> u8 {
self.date().sunday_based_week()
}
/// Get the week number where week 1 begins on the first Monday.
///
/// The returned value will always be in the range `0..=53`.
///
/// ```rust
/// # use time::Date;
/// assert_eq!(Date::from_ymd(2019, 1, 1).midnight().monday_based_week(), 0);
/// assert_eq!(Date::from_ymd(2020, 1, 1).midnight().monday_based_week(), 0);
/// assert_eq!(
/// Date::from_ymd(2020, 12, 31).midnight().monday_based_week(),
/// 52
/// );
/// assert_eq!(Date::from_ymd(2021, 1, 1).midnight().monday_based_week(), 0);
/// ```
#[inline(always)]
pub fn monday_based_week(self) -> u8 {
self.date().monday_based_week()
}
/// Get the weekday.
///
/// This current uses [Zeller's congruence](https://en.wikipedia.org/wiki/Zeller%27s_congruence)
/// internally.
///
/// ```rust
/// # use time::{Date, Weekday::*};
/// assert_eq!(Date::from_ymd(2019, 1, 1).midnight().weekday(), Tuesday);
/// assert_eq!(Date::from_ymd(2019, 2, 1).midnight().weekday(), Friday);
/// assert_eq!(Date::from_ymd(2019, 3, 1).midnight().weekday(), Friday);
/// assert_eq!(Date::from_ymd(2019, 4, 1).midnight().weekday(), Monday);
/// assert_eq!(Date::from_ymd(2019, 5, 1).midnight().weekday(), Wednesday);
/// assert_eq!(Date::from_ymd(2019, 6, 1).midnight().weekday(), Saturday);
/// assert_eq!(Date::from_ymd(2019, 7, 1).midnight().weekday(), Monday);
/// assert_eq!(Date::from_ymd(2019, 8, 1).midnight().weekday(), Thursday);
/// assert_eq!(Date::from_ymd(2019, 9, 1).midnight().weekday(), Sunday);
/// assert_eq!(Date::from_ymd(2019, 10, 1).midnight().weekday(), Tuesday);
/// assert_eq!(Date::from_ymd(2019, 11, 1).midnight().weekday(), Friday);
/// assert_eq!(Date::from_ymd(2019, 12, 1).midnight().weekday(), Sunday);
/// ```
#[inline(always)]
pub fn weekday(self) -> Weekday {
self.date().weekday()
}
/// Get the clock hour.
///
/// The returned value will always be in the range `0..24`.
///
/// ```rust
/// # use time::Date;
/// assert_eq!(Date::from_ymd(2019, 1, 1).with_hms(0, 0, 0).hour(), 0);
/// assert_eq!(Date::from_ymd(2019, 1, 1).with_hms(23, 59, 59).hour(), 23);
/// ```
#[inline(always)]
pub const fn hour(self) -> u8 {
self.time().hour()
}
/// Get the minute within the hour.
///
/// The returned value will always be in the range `0..60`.
///
/// ```rust
/// # use time::Date;
/// assert_eq!(Date::from_ymd(2019, 1, 1).with_hms(0, 0, 0).minute(), 0);
/// assert_eq!(Date::from_ymd(2019, 1, 1).with_hms(23, 59, 59).minute(), 59);
/// ```
#[inline(always)]
pub const fn minute(self) -> u8 {
self.time().minute()
}
/// Get the second within the minute.
///
/// The returned value will always be in the range `0..60`.
///
/// ```rust
/// # use time::Date;
/// assert_eq!(Date::from_ymd(2019, 1, 1).with_hms(0, 0, 0).second(), 0);
/// assert_eq!(Date::from_ymd(2019, 1, 1).with_hms(23, 59, 59).second(), 59);
/// ```
#[inline(always)]
pub const fn second(self) -> u8 {
self.time().second()
}
/// Get the milliseconds within the second.
///
/// The returned value will always be in the range `0..1_000`.
///
/// ```rust
/// # use time::Date;
/// assert_eq!(
/// Date::from_ymd(2019, 1, 1)
/// .with_hms_milli(0, 0, 0, 0)
/// .millisecond(),
/// 0
/// );
/// assert_eq!(
/// Date::from_ymd(2019, 1, 1)
/// .with_hms_milli(23, 59, 59, 999)
/// .millisecond(),
/// 999
/// );
/// ```
#[inline(always)]
pub const fn millisecond(self) -> u16 {
self.time().millisecond()
}
/// Get the microseconds within the second.
///
/// The returned value will always be in the range `0..1_000_000`.
///
/// ```rust
/// # use time::Date;
/// assert_eq!(
/// Date::from_ymd(2019, 1, 1)
/// .with_hms_micro(0, 0, 0, 0)
/// .microsecond(),
/// 0
/// );
/// assert_eq!(
/// Date::from_ymd(2019, 1, 1)
/// .with_hms_micro(23, 59, 59, 999_999)
/// .microsecond(),
/// 999_999
/// );
/// ```
#[inline(always)]
pub const fn microsecond(self) -> u32 {
self.time().microsecond()
}
/// Get the nanoseconds within the second.
///
/// The returned value will always be in the range `0..1_000_000_000`.
///
/// ```rust
/// # use time::Date;
/// assert_eq!(
/// Date::from_ymd(2019, 1, 1)
/// .with_hms_nano(0, 0, 0, 0)
/// .nanosecond(),
/// 0
/// );
/// assert_eq!(
/// Date::from_ymd(2019, 1, 1)
/// .with_hms_nano(23, 59, 59, 999_999_999)
/// .nanosecond(),
/// 999_999_999
/// );
/// ```
#[inline(always)]
pub const fn nanosecond(self) -> u32 {
self.time().nanosecond()
}
/// Create an `OffsetDateTime` from the existing `PrimitiveDateTime` and provided
/// `UtcOffset`.
///
/// ```rust
/// # use time::{Date, UtcOffset};
/// assert_eq!(
/// Date::from_ymd(2019, 1, 1)
/// .midnight()
/// .using_offset(UtcOffset::UTC)
/// .timestamp(),
/// 1_546_300_800,
/// );
/// ```
#[inline(always)]
pub const fn using_offset(self, offset: UtcOffset) -> OffsetDateTime {
OffsetDateTime {
datetime: self,
offset,
}
}
}
/// Methods that allow formatting the `PrimitiveDateTime`.
impl PrimitiveDateTime {
/// Format the `PrimitiveDateTime` using the provided string.
///
/// ```rust
/// # use time::Date;
/// assert_eq!(
/// Date::from_ymd(2019, 1, 2).midnight().format("%F %r"),
/// "2019-01-02 12:00:00 am"
/// );
/// ```
#[inline(always)]
pub fn format(self, format: &str) -> String {
DeferredFormat {
date: Some(self.date()),
time: Some(self.time()),
offset: None,
format: crate::format::parse_fmt_string(format),
}
.to_string()
}
/// Attempt to parse a `PrimitiveDateTime` using the provided string.
///
/// ```rust
/// # use time::{Date, PrimitiveDateTime, Weekday::Wednesday};
/// assert_eq!(
/// PrimitiveDateTime::parse("2019-01-02 00:00:00", "%F %T"),
/// Ok(Date::from_ymd(2019, 1, 2).midnight()),
/// );
/// assert_eq!(
/// PrimitiveDateTime::parse("2019-002 23:59:59", "%Y-%j %T"),
/// Ok(Date::from_yo(2019, 2).with_hms(23, 59, 59))
/// );
/// assert_eq!(
/// PrimitiveDateTime::parse("2019-W01-3 12:00:00 pm", "%G-W%V-%u %r"),
/// Ok(Date::from_iso_ywd(2019, 1, Wednesday).with_hms(12, 0, 0)),
/// );
/// ```
#[inline(always)]
pub fn parse(s: &str, format: &str) -> ParseResult<Self> {
Self::try_from_parsed_items(parse(s, format)?)
}
/// Given the items already parsed, attempt to create a `PrimitiveDateTime`.
#[inline(always)]
pub(crate) fn try_from_parsed_items(items: ParsedItems) -> ParseResult<Self> {
Ok(Self {
date: Date::try_from_parsed_items(items)?,
time: Time::try_from_parsed_items(items)?,
})
}
}
impl Add<Duration> for PrimitiveDateTime {
type Output = Self;
#[inline]
fn add(self, duration: Duration) -> Self::Output {
#[allow(clippy::cast_possible_truncation)]
let nanos = self.time.nanoseconds_since_midnight() as i64
+ (duration.whole_nanoseconds() % 86_400_000_000_000) as i64;
let date_modifier = if nanos < 0 {
-Duration::day()
} else if nanos >= 86_400_000_000_000 {
Duration::day()
} else {
Duration::zero()
};
Self::new(self.date + duration + date_modifier, self.time + duration)
}
}
#[cfg(feature = "std")]
impl Add<Duration> for SystemTime {
type Output = Self;
#[inline(always)]
fn add(self, duration: Duration) -> Self::Output {
(PrimitiveDateTime::from(self) + duration).into()
}
}
impl Add<StdDuration> for PrimitiveDateTime {
type Output = Self;
#[inline(always)]
fn add(self, duration: StdDuration) -> Self::Output {
#[allow(clippy::cast_possible_truncation)]
let nanos = self.time.nanoseconds_since_midnight()
+ (duration.as_nanos() % 86_400_000_000_000) as u64;
let date_modifier = if nanos >= 86_400_000_000_000 {
Duration::day()
} else {
Duration::zero()
};
Self::new(self.date + duration + date_modifier, self.time + duration)
}
}
impl AddAssign<Duration> for PrimitiveDateTime {
#[inline(always)]
fn add_assign(&mut self, duration: Duration) {
*self = *self + duration;
}
}
impl AddAssign<StdDuration> for PrimitiveDateTime {
#[inline(always)]
fn add_assign(&mut self, duration: StdDuration) {
*self = *self + duration;
}
}
#[cfg(feature = "std")]
impl AddAssign<Duration> for SystemTime {
#[inline(always)]
fn add_assign(&mut self, duration: Duration) {
*self = *self + duration;
}
}
impl Sub<Duration> for PrimitiveDateTime {
type Output = Self;
#[inline(always)]
fn sub(self, duration: Duration) -> Self::Output {
self + -duration
}
}
impl Sub<StdDuration> for PrimitiveDateTime {
type Output = Self;
#[inline(always)]
fn sub(self, duration: StdDuration) -> Self::Output {
#[allow(clippy::cast_possible_truncation)]
let nanos = self.time.nanoseconds_since_midnight() as i64
- (duration.as_nanos() % 86_400_000_000_000) as i64;
let date_modifier = if nanos < 0 {
-Duration::day()
} else {
Duration::zero()
};
Self::new(self.date - duration + date_modifier, self.time - duration)
}
}
#[cfg(feature = "std")]
impl Sub<Duration> for SystemTime {
type Output = Self;
#[inline(always)]
fn sub(self, duration: Duration) -> Self::Output {
(PrimitiveDateTime::from(self) - duration).into()
}
}
impl SubAssign<Duration> for PrimitiveDateTime {
#[inline(always)]
fn sub_assign(&mut self, duration: Duration) {
*self = *self - duration;
}
}
impl SubAssign<StdDuration> for PrimitiveDateTime {
#[inline(always)]
fn sub_assign(&mut self, duration: StdDuration) {
*self = *self - duration;
}
}
#[cfg(feature = "std")]
impl SubAssign<Duration> for SystemTime {
#[inline(always)]
fn sub_assign(&mut self, duration: Duration) {
*self = *self - duration;
}
}
impl Sub<PrimitiveDateTime> for PrimitiveDateTime {
type Output = Duration;
#[inline(always)]
fn sub(self, rhs: Self) -> Self::Output {
(self.date - rhs.date) + (self.time - rhs.time)
}
}
#[cfg(feature = "std")]
impl Sub<SystemTime> for PrimitiveDateTime {
type Output = Duration;
#[inline(always)]
fn sub(self, rhs: SystemTime) -> Self::Output {
self - Self::from(rhs)
}
}
#[cfg(feature = "std")]
impl Sub<PrimitiveDateTime> for SystemTime {
type Output = Duration;
#[inline(always)]
fn sub(self, rhs: PrimitiveDateTime) -> Self::Output {
PrimitiveDateTime::from(self) - rhs
}
}
impl PartialOrd for PrimitiveDateTime {
#[inline(always)]
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
#[cfg(feature = "std")]
impl PartialEq<SystemTime> for PrimitiveDateTime {
#[inline(always)]
fn eq(&self, rhs: &SystemTime) -> bool {
self == &Self::from(*rhs)
}
}
#[cfg(feature = "std")]
impl PartialEq<PrimitiveDateTime> for SystemTime {
#[inline(always)]
fn eq(&self, rhs: &PrimitiveDateTime) -> bool {
&PrimitiveDateTime::from(*self) == rhs
}
}
#[cfg(feature = "std")]
impl PartialOrd<SystemTime> for PrimitiveDateTime {
#[inline(always)]
fn partial_cmp(&self, other: &SystemTime) -> Option<Ordering> {
self.partial_cmp(&Self::from(*other))
}
}
#[cfg(feature = "std")]
impl PartialOrd<PrimitiveDateTime> for SystemTime {
#[inline(always)]
fn partial_cmp(&self, other: &PrimitiveDateTime) -> Option<Ordering> {
PrimitiveDateTime::from(*self).partial_cmp(other)
}
}
impl Ord for PrimitiveDateTime {
#[inline]
fn cmp(&self, other: &Self) -> Ordering {
match self.date.cmp(&other.date) {
Ordering::Equal => match self.time.hour.cmp(&other.time.hour) {
Ordering::Equal => match self.time.minute.cmp(&other.time.minute) {
Ordering::Equal => match self.time.second.cmp(&other.time.second) {
Ordering::Equal => self.time.nanosecond.cmp(&other.time.nanosecond),
other => other,
},
other => other,
},
other => other,
},
other => other,
}
}
}
#[cfg(feature = "std")]
impl From<SystemTime> for PrimitiveDateTime {
#[inline(always)]
fn from(system_time: SystemTime) -> Self {
let duration = match system_time.duration_since(SystemTime::UNIX_EPOCH) {
Ok(duration) => Duration::try_from(duration)
.expect("overflow converting `std::time::Duration` to `time::Duration`"),
Err(err) => -Duration::try_from(err.duration())
.expect("overflow converting `std::time::Duration` to `time::Duration`"),
};
Self::unix_epoch() + duration
}
}
#[cfg(feature = "std")]
#[allow(clippy::fallible_impl_from)]
impl From<PrimitiveDateTime> for SystemTime {
#[inline]
fn from(datetime: PrimitiveDateTime) -> Self {
let duration = datetime - PrimitiveDateTime::unix_epoch();
match duration.sign() {
Sign::Positive => Self::UNIX_EPOCH + duration.std,
Sign::Negative => Self::UNIX_EPOCH - duration.std,
Sign::Zero => Self::UNIX_EPOCH,
}
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::prelude::*;
macro_rules! ymd {
($year:literal, $month:literal, $day:literal) => {
Date::from_ymd($year, $month, $day)
};
}
#[test]
fn new() {
assert_eq!(
PrimitiveDateTime::new(ymd!(2019, 1, 1), Time::midnight()),
ymd!(2019, 1, 1).midnight(),
);
}
#[test]
#[cfg(feature = "std")]
fn now() {
assert!(PrimitiveDateTime::now().year() >= 2019);
}
#[test]
fn unix_epoch() {
assert_eq!(PrimitiveDateTime::unix_epoch(), ymd!(1970, 1, 1).midnight());
}
#[test]
fn from_unix_timestamp() {
assert_eq!(
PrimitiveDateTime::from_unix_timestamp(0),
PrimitiveDateTime::unix_epoch()
);
assert_eq!(
PrimitiveDateTime::from_unix_timestamp(1_546_300_800),
ymd!(2019, 1, 1).midnight(),
);
}
#[test]
fn timestamp() {
assert_eq!(PrimitiveDateTime::unix_epoch().timestamp(), 0);
assert_eq!(ymd!(2019, 1, 1).midnight().timestamp(), 1_546_300_800);
}
#[test]
fn date() {
assert_eq!(ymd!(2019, 1, 1).midnight().date(), ymd!(2019, 1, 1));
}
#[test]
fn time() {
assert_eq!(ymd!(2019, 1, 1).midnight().time(), Time::midnight());
}
#[test]
fn year() {
assert_eq!(ymd!(2019, 1, 1).midnight().year(), 2019);
assert_eq!(ymd!(2019, 12, 31).midnight().year(), 2019);
assert_eq!(ymd!(2020, 1, 1).midnight().year(), 2020);
}
#[test]
fn month() {
assert_eq!(ymd!(2019, 1, 1).midnight().month(), 1);
assert_eq!(ymd!(2019, 12, 31).midnight().month(), 12);
}
#[test]
fn day() {
assert_eq!(ymd!(2019, 1, 1).midnight().day(), 1);
assert_eq!(ymd!(2019, 12, 31).midnight().day(), 31);
}
#[test]
fn month_day() {
assert_eq!(ymd!(2019, 1, 1).midnight().month_day(), (1, 1));
assert_eq!(ymd!(2019, 12, 31).midnight().month_day(), (12, 31));
}
#[test]
fn ordinal() {
assert_eq!(ymd!(2019, 1, 1).midnight().ordinal(), 1);
assert_eq!(ymd!(2019, 12, 31).midnight().ordinal(), 365);
}
#[test]
fn week() {
assert_eq!(ymd!(2019, 1, 1).midnight().week(), 1);
assert_eq!(ymd!(2019, 10, 4).midnight().week(), 40);
assert_eq!(ymd!(2020, 1, 1).midnight().week(), 1);
assert_eq!(ymd!(2020, 12, 31).midnight().week(), 53);
assert_eq!(ymd!(2021, 1, 1).midnight().week(), 53);
}
#[test]
fn sunday_based_week() {
assert_eq!(ymd!(2019, 1, 1).midnight().sunday_based_week(), 0);
assert_eq!(ymd!(2020, 1, 1).midnight().sunday_based_week(), 0);
assert_eq!(ymd!(2020, 12, 31).midnight().sunday_based_week(), 52);
assert_eq!(ymd!(2021, 1, 1).midnight().sunday_based_week(), 0);
}
#[test]
fn monday_based_week() {
assert_eq!(ymd!(2019, 1, 1).midnight().monday_based_week(), 0);
assert_eq!(ymd!(2020, 1, 1).midnight().monday_based_week(), 0);
assert_eq!(ymd!(2020, 12, 31).midnight().monday_based_week(), 52);
assert_eq!(ymd!(2021, 1, 1).midnight().monday_based_week(), 0);
}
#[test]
fn weekday() {
use Weekday::*;
assert_eq!(ymd!(2019, 1, 1).midnight().weekday(), Tuesday);
assert_eq!(ymd!(2019, 2, 1).midnight().weekday(), Friday);
assert_eq!(ymd!(2019, 3, 1).midnight().weekday(), Friday);
assert_eq!(ymd!(2019, 4, 1).midnight().weekday(), Monday);
assert_eq!(ymd!(2019, 5, 1).midnight().weekday(), Wednesday);
assert_eq!(ymd!(2019, 6, 1).midnight().weekday(), Saturday);
assert_eq!(ymd!(2019, 7, 1).midnight().weekday(), Monday);
assert_eq!(ymd!(2019, 8, 1).midnight().weekday(), Thursday);
assert_eq!(ymd!(2019, 9, 1).midnight().weekday(), Sunday);
assert_eq!(ymd!(2019, 10, 1).midnight().weekday(), Tuesday);
assert_eq!(ymd!(2019, 11, 1).midnight().weekday(), Friday);
assert_eq!(ymd!(2019, 12, 1).midnight().weekday(), Sunday);
}
#[test]
fn hour() {
assert_eq!(ymd!(2019, 1, 1).with_hms(0, 0, 0).hour(), 0);
assert_eq!(ymd!(2019, 1, 1).with_hms(23, 59, 59).hour(), 23);
}
#[test]
fn minute() {
assert_eq!(ymd!(2019, 1, 1).with_hms(0, 0, 0).minute(), 0);
assert_eq!(ymd!(2019, 1, 1).with_hms(23, 59, 59).minute(), 59);
}
#[test]
fn second() {
assert_eq!(ymd!(2019, 1, 1).with_hms(0, 0, 0).second(), 0);
assert_eq!(ymd!(2019, 1, 1).with_hms(23, 59, 59).second(), 59);
}
#[test]
fn millisecond() {
assert_eq!(ymd!(2019, 1, 1).with_hms_milli(0, 0, 0, 0).millisecond(), 0);
assert_eq!(
ymd!(2019, 1, 1)
.with_hms_milli(23, 59, 59, 999)
.millisecond(),
999
);
}
#[test]
fn microsecond() {
assert_eq!(ymd!(2019, 1, 1).with_hms_micro(0, 0, 0, 0).microsecond(), 0);
assert_eq!(
ymd!(2019, 1, 1)
.with_hms_micro(23, 59, 59, 999_999)
.microsecond(),
999_999
);
}
#[test]
fn nanosecond() {
assert_eq!(ymd!(2019, 1, 1).with_hms_nano(0, 0, 0, 0).nanosecond(), 0);
assert_eq!(
ymd!(2019, 1, 1)
.with_hms_nano(23, 59, 59, 999_999_999)
.nanosecond(),
999_999_999
);
}
#[test]
fn using_offset() {
assert_eq!(
ymd!(2019, 1, 1)
.midnight()
.using_offset(UtcOffset::UTC)
.timestamp(),
1_546_300_800,
);
}
#[test]
fn format() {
assert_eq!(
ymd!(2019, 1, 2).midnight().format("%F %r"),
"2019-01-02 12:00:00 am"
);
}
#[test]
fn parse() {
assert_eq!(
PrimitiveDateTime::parse("2019-01-02 00:00:00", "%F %T"),
Ok(ymd!(2019, 1, 2).midnight()),
);
assert_eq!(
PrimitiveDateTime::parse("2019-002 23:59:59", "%Y-%j %T"),
Ok(Date::from_yo(2019, 2).with_hms(23, 59, 59))
);
assert_eq!(
PrimitiveDateTime::parse("2019-W01-3 12:00:00 pm", "%G-W%V-%u %r"),
Ok(Date::from_iso_ywd(2019, 1, Weekday::Wednesday).with_hms(12, 0, 0)),
);
}
#[test]
fn add_duration() {
assert_eq!(
ymd!(2019, 1, 1).midnight() + 5.days(),
ymd!(2019, 1, 6).midnight(),
);
assert_eq!(
ymd!(2019, 12, 31).midnight() + 1.days(),
ymd!(2020, 1, 1).midnight(),
);
assert_eq!(
ymd!(2019, 12, 31).with_hms(23, 59, 59) + 2.seconds(),
ymd!(2020, 1, 1).with_hms(0, 0, 1),
);
assert_eq!(
ymd!(2020, 1, 1).with_hms(0, 0, 1) + (-2).seconds(),
ymd!(2019, 12, 31).with_hms(23, 59, 59),
);
assert_eq!(
ymd!(1999, 12, 31).with_hms(23, 0, 0) + 1.hours(),
ymd!(2000, 1, 1).midnight(),
);
}
#[test]
#[cfg(feature = "std")]
fn std_add_duration() {
assert_eq!(
SystemTime::from(ymd!(2019, 1, 1).midnight()) + 5.days(),
SystemTime::from(ymd!(2019, 1, 6).midnight()),
);
assert_eq!(
SystemTime::from(ymd!(2019, 12, 31).midnight()) + 1.days(),
SystemTime::from(ymd!(2020, 1, 1).midnight()),
);
assert_eq!(
SystemTime::from(ymd!(2019, 12, 31).with_hms(23, 59, 59)) + 2.seconds(),
SystemTime::from(ymd!(2020, 1, 1).with_hms(0, 0, 1)),
);
assert_eq!(
SystemTime::from(ymd!(2020, 1, 1).with_hms(0, 0, 1)) + (-2).seconds(),
SystemTime::from(ymd!(2019, 12, 31).with_hms(23, 59, 59)),
);
}
#[test]
fn add_std_duration() {
assert_eq!(
ymd!(2019, 1, 1).midnight() + 5.std_days(),
ymd!(2019, 1, 6).midnight(),
);
assert_eq!(
ymd!(2019, 12, 31).midnight() + 1.std_days(),
ymd!(2020, 1, 1).midnight(),
);
assert_eq!(
ymd!(2019, 12, 31).with_hms(23, 59, 59) + 2.std_seconds(),
ymd!(2020, 1, 1).with_hms(0, 0, 1),
);
}
#[test]
fn add_assign_duration() {
let mut ny19 = ymd!(2019, 1, 1).midnight();
ny19 += 5.days();
assert_eq!(ny19, ymd!(2019, 1, 6).midnight());
let mut nye20 = ymd!(2019, 12, 31).midnight();
nye20 += 1.days();
assert_eq!(nye20, ymd!(2020, 1, 1).midnight());
let mut nye20t = ymd!(2019, 12, 31).with_hms(23, 59, 59);
nye20t += 2.seconds();
assert_eq!(nye20t, ymd!(2020, 1, 1).with_hms(0, 0, 1));
let mut ny20t = ymd!(2020, 1, 1).with_hms(0, 0, 1);
ny20t += (-2).seconds();
assert_eq!(ny20t, ymd!(2019, 12, 31).with_hms(23, 59, 59));
}
#[test]
fn add_assign_std_duration() {
let mut ny19 = ymd!(2019, 1, 1).midnight();
ny19 += 5.std_days();
assert_eq!(ny19, ymd!(2019, 1, 6).midnight());
let mut nye20 = ymd!(2019, 12, 31).midnight();
nye20 += 1.std_days();
assert_eq!(nye20, ymd!(2020, 1, 1).midnight());
let mut nye20t = ymd!(2019, 12, 31).with_hms(23, 59, 59);
nye20t += 2.std_seconds();
assert_eq!(nye20t, ymd!(2020, 1, 1).with_hms(0, 0, 1));
}
#[test]
#[cfg(feature = "std")]
fn std_add_assign_duration() {
let mut ny19 = SystemTime::from(ymd!(2019, 1, 1).midnight());
ny19 += 5.days();
assert_eq!(ny19, ymd!(2019, 1, 6).midnight());
let mut nye20 = SystemTime::from(ymd!(2019, 12, 31).midnight());
nye20 += 1.days();
assert_eq!(nye20, ymd!(2020, 1, 1).midnight());
let mut nye20t = SystemTime::from(ymd!(2019, 12, 31).with_hms(23, 59, 59));
nye20t += 2.seconds();
assert_eq!(nye20t, ymd!(2020, 1, 1).with_hms(0, 0, 1));
let mut ny20t = SystemTime::from(ymd!(2020, 1, 1).with_hms(0, 0, 1));
ny20t += (-2).seconds();
assert_eq!(ny20t, ymd!(2019, 12, 31).with_hms(23, 59, 59));
}
#[test]
fn sub_duration() {
assert_eq!(
ymd!(2019, 1, 6).midnight() - 5.days(),
ymd!(2019, 1, 1).midnight(),
);
assert_eq!(
ymd!(2020, 1, 1).midnight() - 1.days(),
ymd!(2019, 12, 31).midnight(),
);
assert_eq!(
ymd!(2020, 1, 1).with_hms(0, 0, 1) - 2.seconds(),
ymd!(2019, 12, 31).with_hms(23, 59, 59),
);
assert_eq!(
ymd!(2019, 12, 31).with_hms(23, 59, 59) - (-2).seconds(),
ymd!(2020, 1, 1).with_hms(0, 0, 1),
);
assert_eq!(
ymd!(1999, 12, 31).with_hms(23, 0, 0) - (-1).hours(),
ymd!(2000, 1, 1).midnight(),
);
}
#[test]
fn sub_std_duration() {
assert_eq!(
ymd!(2019, 1, 6).midnight() - 5.std_days(),
ymd!(2019, 1, 1).midnight(),
);
assert_eq!(
ymd!(2020, 1, 1).midnight() - 1.std_days(),
ymd!(2019, 12, 31).midnight(),
);
assert_eq!(
ymd!(2020, 1, 1).with_hms(0, 0, 1) - 2.std_seconds(),
ymd!(2019, 12, 31).with_hms(23, 59, 59),
);
}
#[test]
#[cfg(feature = "std")]
fn std_sub_duration() {
assert_eq!(
SystemTime::from(ymd!(2019, 1, 6).midnight()) - 5.days(),
SystemTime::from(ymd!(2019, 1, 1).midnight()),
);
assert_eq!(
SystemTime::from(ymd!(2020, 1, 1).midnight()) - 1.days(),
SystemTime::from(ymd!(2019, 12, 31).midnight()),
);
assert_eq!(
SystemTime::from(ymd!(2020, 1, 1).with_hms(0, 0, 1)) - 2.seconds(),
SystemTime::from(ymd!(2019, 12, 31).with_hms(23, 59, 59)),
);
assert_eq!(
SystemTime::from(ymd!(2019, 12, 31).with_hms(23, 59, 59)) - (-2).seconds(),
SystemTime::from(ymd!(2020, 1, 1).with_hms(0, 0, 1)),
);
}
#[test]
fn sub_assign_duration() {
let mut ny19 = ymd!(2019, 1, 6).midnight();
ny19 -= 5.days();
assert_eq!(ny19, ymd!(2019, 1, 1).midnight());
let mut ny20 = ymd!(2020, 1, 1).midnight();
ny20 -= 1.days();
assert_eq!(ny20, ymd!(2019, 12, 31).midnight());
let mut ny20t = ymd!(2020, 1, 1).with_hms(0, 0, 1);
ny20t -= 2.seconds();
assert_eq!(ny20t, ymd!(2019, 12, 31).with_hms(23, 59, 59));
let mut nye20t = ymd!(2019, 12, 31).with_hms(23, 59, 59);
nye20t -= (-2).seconds();
assert_eq!(nye20t, ymd!(2020, 1, 1).with_hms(0, 0, 1));
}
#[test]
fn sub_assign_std_duration() {
let mut ny19 = ymd!(2019, 1, 6).midnight();
ny19 -= 5.std_days();
assert_eq!(ny19, ymd!(2019, 1, 1).midnight());
let mut ny20 = ymd!(2020, 1, 1).midnight();
ny20 -= 1.std_days();
assert_eq!(ny20, ymd!(2019, 12, 31).midnight());
let mut ny20t = ymd!(2020, 1, 1).with_hms(0, 0, 1);
ny20t -= 2.std_seconds();
assert_eq!(ny20t, ymd!(2019, 12, 31).with_hms(23, 59, 59));
}
#[test]
#[cfg(feature = "std")]
fn std_sub_assign_duration() {
let mut ny19 = SystemTime::from(ymd!(2019, 1, 6).midnight());
ny19 -= 5.days();
assert_eq!(ny19, ymd!(2019, 1, 1).midnight());
let mut ny20 = SystemTime::from(ymd!(2020, 1, 1).midnight());
ny20 -= 1.days();
assert_eq!(ny20, ymd!(2019, 12, 31).midnight());
let mut ny20t = SystemTime::from(ymd!(2020, 1, 1).with_hms(0, 0, 1));
ny20t -= 2.seconds();
assert_eq!(ny20t, ymd!(2019, 12, 31).with_hms(23, 59, 59));
let mut nye20t = SystemTime::from(ymd!(2019, 12, 31).with_hms(23, 59, 59));
nye20t -= (-2).seconds();
assert_eq!(nye20t, ymd!(2020, 1, 1).with_hms(0, 0, 1));
}
#[test]
fn sub_datetime() {
assert_eq!(
ymd!(2019, 1, 2).midnight() - ymd!(2019, 1, 1).midnight(),
1.days()
);
assert_eq!(
ymd!(2019, 1, 1).midnight() - ymd!(2019, 1, 2).midnight(),
(-1).days()
);
assert_eq!(
ymd!(2020, 1, 1).midnight() - ymd!(2019, 12, 31).midnight(),
1.days()
);
assert_eq!(
ymd!(2019, 12, 31).midnight() - ymd!(2020, 1, 1).midnight(),
(-1).days()
);
}
#[test]
#[cfg(feature = "std")]
fn std_sub_datetime() {
assert_eq!(
SystemTime::from(ymd!(2019, 1, 2).midnight()) - ymd!(2019, 1, 1).midnight(),
1.days()
);
assert_eq!(
SystemTime::from(ymd!(2019, 1, 1).midnight()) - ymd!(2019, 1, 2).midnight(),
(-1).days()
);
assert_eq!(
SystemTime::from(ymd!(2020, 1, 1).midnight()) - ymd!(2019, 12, 31).midnight(),
1.days()
);
assert_eq!(
SystemTime::from(ymd!(2019, 12, 31).midnight()) - ymd!(2020, 1, 1).midnight(),
(-1).days()
);
}
#[test]
#[cfg(feature = "std")]
fn sub_std() {
assert_eq!(
ymd!(2019, 1, 2).midnight() - SystemTime::from(ymd!(2019, 1, 1).midnight()),
1.days()
);
assert_eq!(
ymd!(2019, 1, 1).midnight() - SystemTime::from(ymd!(2019, 1, 2).midnight()),
(-1).days()
);
assert_eq!(
ymd!(2020, 1, 1).midnight() - SystemTime::from(ymd!(2019, 12, 31).midnight()),
1.days()
);
assert_eq!(
ymd!(2019, 12, 31).midnight() - SystemTime::from(ymd!(2020, 1, 1).midnight()),
(-1).days()
);
}
#[test]
fn ord() {
use Ordering::*;
assert_eq!(
ymd!(2019, 1, 1)
.midnight()
.partial_cmp(&ymd!(2019, 1, 1).midnight()),
Some(Equal)
);
assert_eq!(
ymd!(2019, 1, 1)
.midnight()
.partial_cmp(&ymd!(2020, 1, 1).midnight()),
Some(Less)
);
assert_eq!(
ymd!(2019, 1, 1)
.midnight()
.partial_cmp(&ymd!(2019, 2, 1).midnight()),
Some(Less)
);
assert_eq!(
ymd!(2019, 1, 1)
.midnight()
.partial_cmp(&ymd!(2019, 1, 2).midnight()),
Some(Less)
);
assert_eq!(
ymd!(2019, 1, 1)
.midnight()
.partial_cmp(&ymd!(2019, 1, 1).with_hms(1, 0, 0)),
Some(Less)
);
assert_eq!(
ymd!(2019, 1, 1)
.midnight()
.partial_cmp(&ymd!(2019, 1, 1).with_hms(0, 1, 0)),
Some(Less)
);
assert_eq!(
ymd!(2019, 1, 1)
.midnight()
.partial_cmp(&ymd!(2019, 1, 1).with_hms(0, 0, 1)),
Some(Less)
);
assert_eq!(
ymd!(2019, 1, 1)
.midnight()
.partial_cmp(&ymd!(2019, 1, 1).with_hms_nano(0, 0, 0, 1)),
Some(Less)
);
assert_eq!(
ymd!(2020, 1, 1)
.midnight()
.partial_cmp(&ymd!(2019, 1, 1).midnight()),
Some(Greater)
);
assert_eq!(
ymd!(2019, 2, 1)
.midnight()
.partial_cmp(&ymd!(2019, 1, 1).midnight()),
Some(Greater)
);
assert_eq!(
ymd!(2019, 1, 2)
.midnight()
.partial_cmp(&ymd!(2019, 1, 1).midnight()),
Some(Greater)
);
assert_eq!(
ymd!(2019, 1, 1)
.with_hms(1, 0, 0)
.partial_cmp(&ymd!(2019, 1, 1).midnight()),
Some(Greater)
);
assert_eq!(
ymd!(2019, 1, 1)
.with_hms(0, 1, 0)
.partial_cmp(&ymd!(2019, 1, 1).midnight()),
Some(Greater)
);
assert_eq!(
ymd!(2019, 1, 1)
.with_hms(0, 0, 1)
.partial_cmp(&ymd!(2019, 1, 1).midnight()),
Some(Greater)
);
assert_eq!(
ymd!(2019, 1, 1)
.with_hms_nano(0, 0, 0, 1)
.partial_cmp(&ymd!(2019, 1, 1).midnight()),
Some(Greater)
);
}
#[test]
#[cfg(feature = "std")]
fn eq_std() {
let now_datetime = PrimitiveDateTime::now();
let now_systemtime = SystemTime::from(now_datetime);
assert_eq!(now_datetime, now_systemtime);
}
#[test]
#[cfg(feature = "std")]
fn std_eq() {
#[cfg(feature = "std")]
let now_datetime = PrimitiveDateTime::now();
let now_systemtime = SystemTime::from(now_datetime);
assert_eq!(now_datetime, now_systemtime);
}
#[test]
#[cfg(feature = "std")]
fn ord_std() {
assert_eq!(
ymd!(2019, 1, 1).midnight(),
SystemTime::from(ymd!(2019, 1, 1).midnight())
);
assert!(ymd!(2019, 1, 1).midnight() < SystemTime::from(ymd!(2020, 1, 1).midnight()));
assert!(ymd!(2019, 1, 1).midnight() < SystemTime::from(ymd!(2019, 2, 1).midnight()));
assert!(ymd!(2019, 1, 1).midnight() < SystemTime::from(ymd!(2019, 1, 2).midnight()));
assert!(ymd!(2019, 1, 1).midnight() < SystemTime::from(ymd!(2019, 1, 1).with_hms(1, 0, 0)));
assert!(ymd!(2019, 1, 1).midnight() < SystemTime::from(ymd!(2019, 1, 1).with_hms(0, 1, 0)));
assert!(ymd!(2019, 1, 1).midnight() < SystemTime::from(ymd!(2019, 1, 1).with_hms(0, 0, 1)));
assert!(
ymd!(2019, 1, 1).midnight()
< SystemTime::from(ymd!(2019, 1, 1).with_hms_milli(0, 0, 0, 1))
);
assert!(ymd!(2020, 1, 1).midnight() > SystemTime::from(ymd!(2019, 1, 1).midnight()));
assert!(ymd!(2019, 2, 1).midnight() > SystemTime::from(ymd!(2019, 1, 1).midnight()));
assert!(ymd!(2019, 1, 2).midnight() > SystemTime::from(ymd!(2019, 1, 1).midnight()));
assert!(ymd!(2019, 1, 1).with_hms(1, 0, 0) > SystemTime::from(ymd!(2019, 1, 1).midnight()));
assert!(ymd!(2019, 1, 1).with_hms(0, 1, 0) > SystemTime::from(ymd!(2019, 1, 1).midnight()));
assert!(ymd!(2019, 1, 1).with_hms(0, 0, 1) > SystemTime::from(ymd!(2019, 1, 1).midnight()));
assert!(
ymd!(2019, 1, 1).with_hms_nano(0, 0, 0, 1)
> SystemTime::from(ymd!(2019, 1, 1).midnight())
);
}
#[test]
#[cfg(feature = "std")]
fn std_ord() {
assert_eq!(
SystemTime::from(ymd!(2019, 1, 1).midnight()),
ymd!(2019, 1, 1).midnight()
);
assert!(SystemTime::from(ymd!(2019, 1, 1).midnight()) < ymd!(2020, 1, 1).midnight());
assert!(SystemTime::from(ymd!(2019, 1, 1).midnight()) < ymd!(2019, 2, 1).midnight());
assert!(SystemTime::from(ymd!(2019, 1, 1).midnight()) < ymd!(2019, 1, 2).midnight());
assert!(SystemTime::from(ymd!(2019, 1, 1).midnight()) < ymd!(2019, 1, 1).with_hms(1, 0, 0));
assert!(SystemTime::from(ymd!(2019, 1, 1).midnight()) < ymd!(2019, 1, 1).with_hms(0, 1, 0));
assert!(SystemTime::from(ymd!(2019, 1, 1).midnight()) < ymd!(2019, 1, 1).with_hms(0, 0, 1));
assert!(
SystemTime::from(ymd!(2019, 1, 1).midnight())
< ymd!(2019, 1, 1).with_hms_nano(0, 0, 0, 1)
);
assert!(SystemTime::from(ymd!(2020, 1, 1).midnight()) > ymd!(2019, 1, 1).midnight());
assert!(SystemTime::from(ymd!(2019, 2, 1).midnight()) > ymd!(2019, 1, 1).midnight());
assert!(SystemTime::from(ymd!(2019, 1, 2).midnight()) > ymd!(2019, 1, 1).midnight());
assert!(SystemTime::from(ymd!(2019, 1, 1).with_hms(1, 0, 0)) > ymd!(2019, 1, 1).midnight());
assert!(SystemTime::from(ymd!(2019, 1, 1).with_hms(0, 1, 0)) > ymd!(2019, 1, 1).midnight());
assert!(SystemTime::from(ymd!(2019, 1, 1).with_hms(0, 0, 1)) > ymd!(2019, 1, 1).midnight());
assert!(
SystemTime::from(ymd!(2019, 1, 1).with_hms_milli(0, 0, 0, 1))
> ymd!(2019, 1, 1).midnight()
);
}
#[test]
#[cfg(feature = "std")]
fn from_std() {
assert_eq!(
PrimitiveDateTime::from(SystemTime::UNIX_EPOCH),
PrimitiveDateTime::unix_epoch()
);
}
#[test]
#[cfg(feature = "std")]
fn to_std() {
assert_eq!(
SystemTime::from(PrimitiveDateTime::unix_epoch()),
SystemTime::UNIX_EPOCH
);
}
}
|
use std::collections::HashSet;
use std::env;
use std::fs::File;
use std::io::prelude::*;
use std::io::BufReader;
use std::process;
fn main() {
let args: Vec<String> = env::args().collect();
if args.len() != 3 {
println!("Invalid arguments, expected 2 args");
process::exit(1);
}
let total = args[1].parse::<i32>().expect("arg1 not an int");
let file = File::open(&args[2]).expect("arg2 not a file on disk");
let reader = BufReader::new(file);
let mut data = HashSet::new();
for line in reader.lines() {
let num = line
.unwrap()
.parse::<i32>()
.expect("File has a non-numeric entry");
let to_find = total - num;
if to_find <= 0 {
continue;
}
for rest in &data {
let val = to_find - rest;
if val <= 0 {
continue;
}
if data.contains(&val) {
println!(
"Result = {}, from {}, {} and {}",
num * rest * val,
num,
rest,
val
);
process::exit(0);
}
}
data.insert(num);
}
println!("no match found at all");
process::exit(1);
}
|
extern crate rustty;
use rustty::{
Terminal,
Event,
Color,
};
struct Cursor {
pos: Position,
lpos: Position,
color: Color,
}
#[derive(Copy, Clone)]
struct Position {
x: usize,
y: usize,
}
fn main() {
let mut cursor = Cursor {
pos: Position { x: 0, y: 0 },
lpos: Position { x: 0, y: 0 },
color: Color::Red,
};
let mut term = Terminal::new().unwrap();
term[(cursor.pos.x, cursor.pos.y)].set_bg(cursor.color);
term.swap_buffers().unwrap();
loop {
let evt = term.get_event(100).unwrap();
if let Some(Event::Key(ch)) = evt {
match ch {
'`' => {
break;
},
'\x7f' => {
cursor.lpos = cursor.pos;
if cursor.pos.x == 0 {
cursor.pos.y = cursor.pos.y.saturating_sub(1);
} else {
cursor.pos.x -= 1;
}
term[(cursor.pos.x, cursor.pos.y)].set_ch(' ');
},
'\r' => {
cursor.lpos = cursor.pos;
cursor.pos.x = 0;
cursor.pos.y += 1;
},
c @ _ => {
term[(cursor.pos.x, cursor.pos.y)].set_ch(c);
cursor.lpos = cursor.pos;
cursor.pos.x += 1;
},
}
if cursor.pos.x >= term.cols()-1 {
term[(cursor.lpos.x, cursor.lpos.y)].set_bg(Color::Default);
cursor.lpos = cursor.pos;
cursor.pos.x = 0;
cursor.pos.y += 1;
}
if cursor.pos.y >= term.rows()-1 {
term[(cursor.lpos.x, cursor.lpos.y)].set_bg(Color::Default);
cursor.lpos = cursor.pos;
cursor.pos.x = 0;
cursor.pos.y = 0;
}
term[(cursor.lpos.x, cursor.lpos.y)].set_bg(Color::Default);
term[(cursor.pos.x, cursor.pos.y)].set_bg(cursor.color);
term.swap_buffers().unwrap();
}
}
}
|
#[doc = "Register `MPCBB1_VCTR16` reader"]
pub type R = crate::R<MPCBB1_VCTR16_SPEC>;
#[doc = "Register `MPCBB1_VCTR16` writer"]
pub type W = crate::W<MPCBB1_VCTR16_SPEC>;
#[doc = "Field `B512` reader - B512"]
pub type B512_R = crate::BitReader;
#[doc = "Field `B512` writer - B512"]
pub type B512_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B513` reader - B513"]
pub type B513_R = crate::BitReader;
#[doc = "Field `B513` writer - B513"]
pub type B513_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B514` reader - B514"]
pub type B514_R = crate::BitReader;
#[doc = "Field `B514` writer - B514"]
pub type B514_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B515` reader - B515"]
pub type B515_R = crate::BitReader;
#[doc = "Field `B515` writer - B515"]
pub type B515_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B516` reader - B516"]
pub type B516_R = crate::BitReader;
#[doc = "Field `B516` writer - B516"]
pub type B516_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B517` reader - B517"]
pub type B517_R = crate::BitReader;
#[doc = "Field `B517` writer - B517"]
pub type B517_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B518` reader - B518"]
pub type B518_R = crate::BitReader;
#[doc = "Field `B518` writer - B518"]
pub type B518_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B519` reader - B519"]
pub type B519_R = crate::BitReader;
#[doc = "Field `B519` writer - B519"]
pub type B519_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B520` reader - B520"]
pub type B520_R = crate::BitReader;
#[doc = "Field `B520` writer - B520"]
pub type B520_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B521` reader - B521"]
pub type B521_R = crate::BitReader;
#[doc = "Field `B521` writer - B521"]
pub type B521_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B522` reader - B522"]
pub type B522_R = crate::BitReader;
#[doc = "Field `B522` writer - B522"]
pub type B522_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B523` reader - B523"]
pub type B523_R = crate::BitReader;
#[doc = "Field `B523` writer - B523"]
pub type B523_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B524` reader - B524"]
pub type B524_R = crate::BitReader;
#[doc = "Field `B524` writer - B524"]
pub type B524_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B525` reader - B525"]
pub type B525_R = crate::BitReader;
#[doc = "Field `B525` writer - B525"]
pub type B525_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B526` reader - B526"]
pub type B526_R = crate::BitReader;
#[doc = "Field `B526` writer - B526"]
pub type B526_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B527` reader - B527"]
pub type B527_R = crate::BitReader;
#[doc = "Field `B527` writer - B527"]
pub type B527_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B528` reader - B528"]
pub type B528_R = crate::BitReader;
#[doc = "Field `B528` writer - B528"]
pub type B528_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B529` reader - B529"]
pub type B529_R = crate::BitReader;
#[doc = "Field `B529` writer - B529"]
pub type B529_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B530` reader - B530"]
pub type B530_R = crate::BitReader;
#[doc = "Field `B530` writer - B530"]
pub type B530_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B531` reader - B531"]
pub type B531_R = crate::BitReader;
#[doc = "Field `B531` writer - B531"]
pub type B531_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B532` reader - B532"]
pub type B532_R = crate::BitReader;
#[doc = "Field `B532` writer - B532"]
pub type B532_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B533` reader - B533"]
pub type B533_R = crate::BitReader;
#[doc = "Field `B533` writer - B533"]
pub type B533_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B534` reader - B534"]
pub type B534_R = crate::BitReader;
#[doc = "Field `B534` writer - B534"]
pub type B534_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B535` reader - B535"]
pub type B535_R = crate::BitReader;
#[doc = "Field `B535` writer - B535"]
pub type B535_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B536` reader - B536"]
pub type B536_R = crate::BitReader;
#[doc = "Field `B536` writer - B536"]
pub type B536_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B537` reader - B537"]
pub type B537_R = crate::BitReader;
#[doc = "Field `B537` writer - B537"]
pub type B537_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B538` reader - B538"]
pub type B538_R = crate::BitReader;
#[doc = "Field `B538` writer - B538"]
pub type B538_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B539` reader - B539"]
pub type B539_R = crate::BitReader;
#[doc = "Field `B539` writer - B539"]
pub type B539_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B540` reader - B540"]
pub type B540_R = crate::BitReader;
#[doc = "Field `B540` writer - B540"]
pub type B540_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B541` reader - B541"]
pub type B541_R = crate::BitReader;
#[doc = "Field `B541` writer - B541"]
pub type B541_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B542` reader - B542"]
pub type B542_R = crate::BitReader;
#[doc = "Field `B542` writer - B542"]
pub type B542_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B543` reader - B543"]
pub type B543_R = crate::BitReader;
#[doc = "Field `B543` writer - B543"]
pub type B543_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bit 0 - B512"]
#[inline(always)]
pub fn b512(&self) -> B512_R {
B512_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - B513"]
#[inline(always)]
pub fn b513(&self) -> B513_R {
B513_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 2 - B514"]
#[inline(always)]
pub fn b514(&self) -> B514_R {
B514_R::new(((self.bits >> 2) & 1) != 0)
}
#[doc = "Bit 3 - B515"]
#[inline(always)]
pub fn b515(&self) -> B515_R {
B515_R::new(((self.bits >> 3) & 1) != 0)
}
#[doc = "Bit 4 - B516"]
#[inline(always)]
pub fn b516(&self) -> B516_R {
B516_R::new(((self.bits >> 4) & 1) != 0)
}
#[doc = "Bit 5 - B517"]
#[inline(always)]
pub fn b517(&self) -> B517_R {
B517_R::new(((self.bits >> 5) & 1) != 0)
}
#[doc = "Bit 6 - B518"]
#[inline(always)]
pub fn b518(&self) -> B518_R {
B518_R::new(((self.bits >> 6) & 1) != 0)
}
#[doc = "Bit 7 - B519"]
#[inline(always)]
pub fn b519(&self) -> B519_R {
B519_R::new(((self.bits >> 7) & 1) != 0)
}
#[doc = "Bit 8 - B520"]
#[inline(always)]
pub fn b520(&self) -> B520_R {
B520_R::new(((self.bits >> 8) & 1) != 0)
}
#[doc = "Bit 9 - B521"]
#[inline(always)]
pub fn b521(&self) -> B521_R {
B521_R::new(((self.bits >> 9) & 1) != 0)
}
#[doc = "Bit 10 - B522"]
#[inline(always)]
pub fn b522(&self) -> B522_R {
B522_R::new(((self.bits >> 10) & 1) != 0)
}
#[doc = "Bit 11 - B523"]
#[inline(always)]
pub fn b523(&self) -> B523_R {
B523_R::new(((self.bits >> 11) & 1) != 0)
}
#[doc = "Bit 12 - B524"]
#[inline(always)]
pub fn b524(&self) -> B524_R {
B524_R::new(((self.bits >> 12) & 1) != 0)
}
#[doc = "Bit 13 - B525"]
#[inline(always)]
pub fn b525(&self) -> B525_R {
B525_R::new(((self.bits >> 13) & 1) != 0)
}
#[doc = "Bit 14 - B526"]
#[inline(always)]
pub fn b526(&self) -> B526_R {
B526_R::new(((self.bits >> 14) & 1) != 0)
}
#[doc = "Bit 15 - B527"]
#[inline(always)]
pub fn b527(&self) -> B527_R {
B527_R::new(((self.bits >> 15) & 1) != 0)
}
#[doc = "Bit 16 - B528"]
#[inline(always)]
pub fn b528(&self) -> B528_R {
B528_R::new(((self.bits >> 16) & 1) != 0)
}
#[doc = "Bit 17 - B529"]
#[inline(always)]
pub fn b529(&self) -> B529_R {
B529_R::new(((self.bits >> 17) & 1) != 0)
}
#[doc = "Bit 18 - B530"]
#[inline(always)]
pub fn b530(&self) -> B530_R {
B530_R::new(((self.bits >> 18) & 1) != 0)
}
#[doc = "Bit 19 - B531"]
#[inline(always)]
pub fn b531(&self) -> B531_R {
B531_R::new(((self.bits >> 19) & 1) != 0)
}
#[doc = "Bit 20 - B532"]
#[inline(always)]
pub fn b532(&self) -> B532_R {
B532_R::new(((self.bits >> 20) & 1) != 0)
}
#[doc = "Bit 21 - B533"]
#[inline(always)]
pub fn b533(&self) -> B533_R {
B533_R::new(((self.bits >> 21) & 1) != 0)
}
#[doc = "Bit 22 - B534"]
#[inline(always)]
pub fn b534(&self) -> B534_R {
B534_R::new(((self.bits >> 22) & 1) != 0)
}
#[doc = "Bit 23 - B535"]
#[inline(always)]
pub fn b535(&self) -> B535_R {
B535_R::new(((self.bits >> 23) & 1) != 0)
}
#[doc = "Bit 24 - B536"]
#[inline(always)]
pub fn b536(&self) -> B536_R {
B536_R::new(((self.bits >> 24) & 1) != 0)
}
#[doc = "Bit 25 - B537"]
#[inline(always)]
pub fn b537(&self) -> B537_R {
B537_R::new(((self.bits >> 25) & 1) != 0)
}
#[doc = "Bit 26 - B538"]
#[inline(always)]
pub fn b538(&self) -> B538_R {
B538_R::new(((self.bits >> 26) & 1) != 0)
}
#[doc = "Bit 27 - B539"]
#[inline(always)]
pub fn b539(&self) -> B539_R {
B539_R::new(((self.bits >> 27) & 1) != 0)
}
#[doc = "Bit 28 - B540"]
#[inline(always)]
pub fn b540(&self) -> B540_R {
B540_R::new(((self.bits >> 28) & 1) != 0)
}
#[doc = "Bit 29 - B541"]
#[inline(always)]
pub fn b541(&self) -> B541_R {
B541_R::new(((self.bits >> 29) & 1) != 0)
}
#[doc = "Bit 30 - B542"]
#[inline(always)]
pub fn b542(&self) -> B542_R {
B542_R::new(((self.bits >> 30) & 1) != 0)
}
#[doc = "Bit 31 - B543"]
#[inline(always)]
pub fn b543(&self) -> B543_R {
B543_R::new(((self.bits >> 31) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - B512"]
#[inline(always)]
#[must_use]
pub fn b512(&mut self) -> B512_W<MPCBB1_VCTR16_SPEC, 0> {
B512_W::new(self)
}
#[doc = "Bit 1 - B513"]
#[inline(always)]
#[must_use]
pub fn b513(&mut self) -> B513_W<MPCBB1_VCTR16_SPEC, 1> {
B513_W::new(self)
}
#[doc = "Bit 2 - B514"]
#[inline(always)]
#[must_use]
pub fn b514(&mut self) -> B514_W<MPCBB1_VCTR16_SPEC, 2> {
B514_W::new(self)
}
#[doc = "Bit 3 - B515"]
#[inline(always)]
#[must_use]
pub fn b515(&mut self) -> B515_W<MPCBB1_VCTR16_SPEC, 3> {
B515_W::new(self)
}
#[doc = "Bit 4 - B516"]
#[inline(always)]
#[must_use]
pub fn b516(&mut self) -> B516_W<MPCBB1_VCTR16_SPEC, 4> {
B516_W::new(self)
}
#[doc = "Bit 5 - B517"]
#[inline(always)]
#[must_use]
pub fn b517(&mut self) -> B517_W<MPCBB1_VCTR16_SPEC, 5> {
B517_W::new(self)
}
#[doc = "Bit 6 - B518"]
#[inline(always)]
#[must_use]
pub fn b518(&mut self) -> B518_W<MPCBB1_VCTR16_SPEC, 6> {
B518_W::new(self)
}
#[doc = "Bit 7 - B519"]
#[inline(always)]
#[must_use]
pub fn b519(&mut self) -> B519_W<MPCBB1_VCTR16_SPEC, 7> {
B519_W::new(self)
}
#[doc = "Bit 8 - B520"]
#[inline(always)]
#[must_use]
pub fn b520(&mut self) -> B520_W<MPCBB1_VCTR16_SPEC, 8> {
B520_W::new(self)
}
#[doc = "Bit 9 - B521"]
#[inline(always)]
#[must_use]
pub fn b521(&mut self) -> B521_W<MPCBB1_VCTR16_SPEC, 9> {
B521_W::new(self)
}
#[doc = "Bit 10 - B522"]
#[inline(always)]
#[must_use]
pub fn b522(&mut self) -> B522_W<MPCBB1_VCTR16_SPEC, 10> {
B522_W::new(self)
}
#[doc = "Bit 11 - B523"]
#[inline(always)]
#[must_use]
pub fn b523(&mut self) -> B523_W<MPCBB1_VCTR16_SPEC, 11> {
B523_W::new(self)
}
#[doc = "Bit 12 - B524"]
#[inline(always)]
#[must_use]
pub fn b524(&mut self) -> B524_W<MPCBB1_VCTR16_SPEC, 12> {
B524_W::new(self)
}
#[doc = "Bit 13 - B525"]
#[inline(always)]
#[must_use]
pub fn b525(&mut self) -> B525_W<MPCBB1_VCTR16_SPEC, 13> {
B525_W::new(self)
}
#[doc = "Bit 14 - B526"]
#[inline(always)]
#[must_use]
pub fn b526(&mut self) -> B526_W<MPCBB1_VCTR16_SPEC, 14> {
B526_W::new(self)
}
#[doc = "Bit 15 - B527"]
#[inline(always)]
#[must_use]
pub fn b527(&mut self) -> B527_W<MPCBB1_VCTR16_SPEC, 15> {
B527_W::new(self)
}
#[doc = "Bit 16 - B528"]
#[inline(always)]
#[must_use]
pub fn b528(&mut self) -> B528_W<MPCBB1_VCTR16_SPEC, 16> {
B528_W::new(self)
}
#[doc = "Bit 17 - B529"]
#[inline(always)]
#[must_use]
pub fn b529(&mut self) -> B529_W<MPCBB1_VCTR16_SPEC, 17> {
B529_W::new(self)
}
#[doc = "Bit 18 - B530"]
#[inline(always)]
#[must_use]
pub fn b530(&mut self) -> B530_W<MPCBB1_VCTR16_SPEC, 18> {
B530_W::new(self)
}
#[doc = "Bit 19 - B531"]
#[inline(always)]
#[must_use]
pub fn b531(&mut self) -> B531_W<MPCBB1_VCTR16_SPEC, 19> {
B531_W::new(self)
}
#[doc = "Bit 20 - B532"]
#[inline(always)]
#[must_use]
pub fn b532(&mut self) -> B532_W<MPCBB1_VCTR16_SPEC, 20> {
B532_W::new(self)
}
#[doc = "Bit 21 - B533"]
#[inline(always)]
#[must_use]
pub fn b533(&mut self) -> B533_W<MPCBB1_VCTR16_SPEC, 21> {
B533_W::new(self)
}
#[doc = "Bit 22 - B534"]
#[inline(always)]
#[must_use]
pub fn b534(&mut self) -> B534_W<MPCBB1_VCTR16_SPEC, 22> {
B534_W::new(self)
}
#[doc = "Bit 23 - B535"]
#[inline(always)]
#[must_use]
pub fn b535(&mut self) -> B535_W<MPCBB1_VCTR16_SPEC, 23> {
B535_W::new(self)
}
#[doc = "Bit 24 - B536"]
#[inline(always)]
#[must_use]
pub fn b536(&mut self) -> B536_W<MPCBB1_VCTR16_SPEC, 24> {
B536_W::new(self)
}
#[doc = "Bit 25 - B537"]
#[inline(always)]
#[must_use]
pub fn b537(&mut self) -> B537_W<MPCBB1_VCTR16_SPEC, 25> {
B537_W::new(self)
}
#[doc = "Bit 26 - B538"]
#[inline(always)]
#[must_use]
pub fn b538(&mut self) -> B538_W<MPCBB1_VCTR16_SPEC, 26> {
B538_W::new(self)
}
#[doc = "Bit 27 - B539"]
#[inline(always)]
#[must_use]
pub fn b539(&mut self) -> B539_W<MPCBB1_VCTR16_SPEC, 27> {
B539_W::new(self)
}
#[doc = "Bit 28 - B540"]
#[inline(always)]
#[must_use]
pub fn b540(&mut self) -> B540_W<MPCBB1_VCTR16_SPEC, 28> {
B540_W::new(self)
}
#[doc = "Bit 29 - B541"]
#[inline(always)]
#[must_use]
pub fn b541(&mut self) -> B541_W<MPCBB1_VCTR16_SPEC, 29> {
B541_W::new(self)
}
#[doc = "Bit 30 - B542"]
#[inline(always)]
#[must_use]
pub fn b542(&mut self) -> B542_W<MPCBB1_VCTR16_SPEC, 30> {
B542_W::new(self)
}
#[doc = "Bit 31 - B543"]
#[inline(always)]
#[must_use]
pub fn b543(&mut self) -> B543_W<MPCBB1_VCTR16_SPEC, 31> {
B543_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 [`mpcbb1_vctr16::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 [`mpcbb1_vctr16::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct MPCBB1_VCTR16_SPEC;
impl crate::RegisterSpec for MPCBB1_VCTR16_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`mpcbb1_vctr16::R`](R) reader structure"]
impl crate::Readable for MPCBB1_VCTR16_SPEC {}
#[doc = "`write(|w| ..)` method takes [`mpcbb1_vctr16::W`](W) writer structure"]
impl crate::Writable for MPCBB1_VCTR16_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets MPCBB1_VCTR16 to value 0"]
impl crate::Resettable for MPCBB1_VCTR16_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use super::*;
use crate::{
db::{builders::UserBuilder, ConnectionPool},
tests::DbSession,
};
#[actix_rt::test]
async fn find_by_user_id() {
let session = DbSession::new();
let user = session.create_user(UserBuilder::default());
let record = session.create_record2(user.id);
let result_record = find(record.id, user.id.into())
.await
.expect("Failed to find record");
assert_eq!(record.id, result_record.id);
}
#[actix_rt::test]
async fn does_not_return_record_of_other_user() {
let session = DbSession::new();
let owner = session.create_user(UserBuilder::default().username("foo"));
let other_user = session.create_user(UserBuilder::default().username("bar"));
let record = session.create_record2(other_user.id);
let error = find(record.id, owner.id.into())
.await
.expect_err("Is not expected to find anything");
assert_eq!(
"Failed to find record from table records_record",
error.to_string()
);
}
#[actix_rt::test]
async fn filters_by_id() {
let session = DbSession::new();
let owner = session.create_user(UserBuilder::default().username("foo"));
let record = session.create_record2(owner.id);
let error = find(record.id + 1, owner.id.into())
.await
.expect_err("Is not expected to find anything");
assert_eq!(
"Failed to find record from table records_record",
error.to_string()
);
}
async fn find(id: i32, user_id: UserId) -> DbResult<Record> {
let conn_pool = ConnectionPool::new();
let query = FindRecord::new(id, user_id);
conn_pool.execute(query).await
}
|
use darling::FromMeta;
#[cfg(feature = "mssql")]
use inflector::Inflector;
#[cfg(feature = "mssql")]
use proc_macro2::TokenStream;
#[cfg(feature = "mssql")]
use syn::{spanned::Spanned, Field};
#[allow(clippy::enum_variant_names)]
#[derive(Clone, Copy, Debug, Eq, FromMeta, PartialEq)]
pub(crate) enum RenameAll {
#[darling(rename = "camelCase")]
CamelCase,
#[darling(rename = "PascalCase")]
PascalCase,
#[darling(rename = "snake_case")]
SnakeCase,
}
impl RenameAll {
#[cfg(feature = "mssql")]
pub fn column(
this: Option<Self>,
column: &Option<String>,
field: &Field,
) -> Result<String, TokenStream> {
if let Some(c) = column.as_ref().filter(|c| !c.is_empty()) {
return Ok(c.clone());
}
let s = match field.ident.as_ref() {
Some(v) => v.to_string(),
None => {
return Err(
syn::Error::new(field.span(), "Only struct are supported").to_compile_error()
)
}
};
Ok(match this {
Some(r) => r.rename(s),
None => s,
})
}
#[cfg(feature = "mssql")]
fn rename(&self, s: String) -> String {
match self {
Self::CamelCase => s.to_camel_case(),
Self::PascalCase => s.to_pascal_case(),
Self::SnakeCase => s.to_snake_case(),
}
}
}
|
extern crate atty;
extern crate regex;
use std::path::Path;
use std::path::PathBuf;
use std::process::Command;
use std::env;
mod config;
mod mailcap;
mod mimetype;
use config::Config;
fn print_usage() {
println!("Usage: run-mailcap-rs [OPTION]... [MIME-TYPE:]FILE");
println!();
println!("Options:");
println!(" --action=<action>");
println!(" Specify the action performed on the file. Valid actions are:");
println!(" view, see (same as view), cat (same as view, but only handle");
println!(" entries with copiousoutput and don't use a pager), edit,");
println!(" change (same es edit), compose, create (same as compose)");
println!(" and print.");
println!(" --debug");
println!(" Print some debugging statements. Its more of a tool during");
println!(" development but may also help to determine whats wrong, when");
println!(" unexpected actions are performend.");
println!(" --nopager");
println!(" Ignore \"copiousoutput\" in mailcap files and call the corresponding");
println!(" command without invoking a pager");
println!(" --norun");
println!(" Do not execute the found command, but just print it. The \"test\"");
println!(" commands in the mailcap entries are still executed.");
}
fn main() {
let config = Config::parse(env::args(), env::vars());
if let Err(_err) = config {
print_usage();
return;
}
let mut config = config.unwrap();
if config.mimetype == "" {
let mut home = PathBuf::from(env::var("HOME").unwrap());
home.push(".mime.types");
let mime_paths: [&Path; 4] = [
&home.as_path(),
Path::new("/usr/share/etc/mime.types"),
Path::new("/usr/local/etc/mime.types"),
Path::new("/etc/mime.types"),
];
config.mimetype = match mimetype::get_type_by_extension(&mime_paths, &config.filename) {
Ok(mimetype) => {
config.mimetype_source = String::from("mime.types file");
mimetype
},
Err(_e) => String::from(""),
};
if config.mimetype.len() == 0 || config.mimetype == "application/octet-stream" {
config.mimetype = match mimetype::get_type_by_magic(&config.filename) {
Ok(mimetype) => {
config.mimetype_source = String::from("libmagic");
mimetype
},
Err(_e) => {
config.mimetype_source = String::from("none");
String::from("application/octet-stream")
},
};
}
if config.debug {
println!("Determined mime type: {}", config.mimetype);
println!("Detected by: {}", config.mimetype_source);
println!();
}
}
let mut home = PathBuf::from(env::var("HOME").unwrap());
home.push(".mailcap");
let mailcap_paths: [&Path; 5] = [
&home.as_path(),
Path::new("/etc/mailcap"),
Path::new("/usr/share/etc/mailcap"),
Path::new("/usr/local/etc/mailcap"),
Path::new("/usr/etc/mailcap"),
];
let mailcap_entries = mailcap::get_entries(&mailcap_paths, &config.mimetype).unwrap();
if config.debug {
println!("Mailcap entries:");
for entry in &mailcap_entries {
println!("view: {}", entry.view);
println!("edit: {}", entry.edit);
println!("compose: {}", entry.compose);
println!("print: {}", entry.print);
println!("test: {}", entry.test);
println!("needsterminal: {}", entry.needsterminal);
println!("copiousoutput: {}", entry.copiousoutput);
println!();
}
}
if let Some(command) = mailcap::get_final_command(&config, atty::is(atty::Stream::Stdout), &mailcap_entries) {
if config.norun {
println!("{}", command);
} else {
let _status = Command::new("sh")
.arg("-c")
.arg(command)
.status();
}
}
}
|
//! A multiset backed by a HashMap
use std::collections::HashMap;
use std::hash::Hash;
/// A multiset backed by a HashMap
#[derive(Clone, Eq, PartialEq, Debug)]
pub struct HashMultiSet<T: Hash + Eq> {
items: HashMap<T, usize>,
len: usize,
}
impl<T: Hash + Eq> HashMultiSet<T> {
/// Insert item into the multiset. see `https://doc.rust-lang.org/std/collections/struct.HashSet.html#method.insert`
pub fn insert(&mut self, value: T) {
*self.items.entry(value).or_default() += 1;
self.len += 1;
}
}
impl<T> Default for HashMultiSet<T>
where
T: Hash + Eq,
{
fn default() -> Self {
Self {
items: HashMap::default(),
len: 0,
}
}
}
impl<T> FromIterator<T> for HashMultiSet<T>
where
T: Hash + Eq,
{
fn from_iter<I>(iter: I) -> Self
where
I: IntoIterator<Item = T>,
{
let mut ret = HashMultiSet::default();
for item in iter {
ret.insert(item);
}
ret
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn basic() {
let mut x = HashMultiSet::default();
x.insert(1);
x.insert(2);
x.insert(2);
assert_eq!(x, HashMultiSet::from_iter([2, 1, 2]));
}
}
|
table! {
posts (id) {
id -> Uuid,
content -> Text,
id_users -> Uuid,
is_private -> Bool,
}
}
table! {
users (id) {
id -> Uuid,
screen_name -> Text,
created_at -> Timestamp,
}
}
joinable!(posts -> users (id_users));
allow_tables_to_appear_in_same_query!(
posts,
users,
);
|
extern crate playground;
use playground::collections::vector;
fn main() {
println!("{:?}", vector::get_properties(&vec![2, 1, 3, 2]));
println!("{:?}", vector::get_properties(&vec![]));
println!("{:?}", vector::get_properties(&vec![2, 1, 3, 3, 3]));
}
|
use serde::{Serialize, Deserialize};
use actix_web::{HttpResponse, HttpRequest, Responder, Error};
use futures::future::{ready, Ready};
use sqlx::{postgres::{PgPoolOptions, PgRow}, query_as};
use sqlx::{FromRow, Row, Pool, Postgres};
use anyhow::Result;
use crate::utils::get_unix_timestamp_ms;
#[derive(Deserialize, Serialize)]
pub struct BoardRequest {
short: String,
long: String,
description: Option<String>,
is_hidden: bool
}
#[derive(FromRow, Serialize)]
pub struct Board {
board_id: i32,
short: String,
long: String,
description: Option<String>,
created_at: i64,
is_hidden: bool,
max_posts: i32,
}
impl Responder for Board {
type Error = Error;
type Future = Ready<Result<HttpResponse, Error>>;
fn respond_to(self, req: &HttpRequest) -> Self::Future {
let body = serde_json::to_string(&self).unwrap();
ready(Ok(
HttpResponse::Ok()
.content_type("application/json")
.body(body)
))
}
}
impl Board {
pub async fn find_all_boards(pool: &Pool<Postgres>) -> Result<Vec<Board>> {
let mut boards: Vec<Board> = vec![];
let records = query_as::<_, Board>(
r#"
SELECT
board_id, short, long, description, created_at, is_hidden
FROM posts
ORDER BY created_at;
"#
).fetch_all(pool).await?;
for record in records {
boards.push(Board {
board_id: record.board_id,
short: record.short,
long: record.long,
description: Some(record.description.unwrap()),
created_at: record.created_at,
is_hidden: record.is_hidden,
max_posts: record.max_posts
});
}
Ok(boards)
}
pub async fn find_all_visible_boards(pool: &Pool<Postgres>) -> Result<Vec<Board>> {
let mut boards: Vec<Board> = vec![];
let records = query_as::<_, Board>(
r#"
SELECT
board_id, short, long, description, created_at, is_hidden, max_posts
FROM posts
WHERE (is_hidden = FALSE)
ORDER BY created_at;
"#
).fetch_all(pool).await?;
for record in records {
boards.push(Board {
board_id: record.board_id,
short: record.short,
long: record.long,
description: Some(record.description.unwrap()),
created_at: record.created_at,
is_hidden: record.is_hidden,
max_posts: record.max_posts,
});
}
Ok(boards)
}
pub async fn find_by_short(pool: &Pool<Postgres>, short: String) -> Result<Board, sqlx::Error> {
let mut tx = pool.begin().await?; // transaction
let board = sqlx::query_as::<_, Board>(
r#"
board_id, short, long, description, created_at, is_hidden, max_posts
FROM posts
WHERE (short = $1);
"#
).bind(&short).fetch_one(&mut tx).await?;
Ok(board)
}
pub async fn find_by_id(pool: &Pool<Postgres>, board_id: i64) -> Result<Board, sqlx::Error> {
let mut tx = pool.begin().await?; // transaction
let board = sqlx::query_as::<_, Board>(
r#"
board_id, short, long, description, created_at, is_hidden, max_posts
FROM posts
WHERE (board_id = $1);
"#
).bind(&board_id).fetch_one(&mut tx).await?;
Ok(board)
}
pub async fn max_posts(pool: &Pool<Postgres>, board_id: i64) -> Result<i64, sqlx::Error> {
let board = Self::find_by_id(pool, board_id).await?;
return Ok(board.max_posts.into())
}
} |
use fltk::{button::*, enums::*, frame::*, group::*, prelude::*, window::*};
use std::cell::RefCell;
use std::rc::Rc;
/*
Created:0.0.1
updated:0.0.1
description:
Contains Sidebar widgets and functionality
*/
pub fn create(wind: &mut DoubleWindow, at: i32) -> BarUi{
let frame = Frame::default()
.with_size(200, 400)
.center_of(wind);
let mut team_button = Button::new(0,0,100,100,"poggers");
let functionality = SidebarFunctionality::new(at);
team_button.set_callback({
let mut c = functionality.clone();
move |_| c.test()
});
//return a ui.
BarUi{
frame: frame.clone(),
team_button: team_button.clone(),
functionality: functionality.clone()
}
}
//struct to store the UI
pub struct BarUi{
frame: Frame,
team_button: Button,
functionality: SidebarFunctionality,
}
//The following code handles the functionality of the sidebar
#[derive(Clone)]
pub struct SidebarFunctionality {
account_type: Rc<RefCell<i32>>,
}
impl SidebarFunctionality{
pub fn new(at:i32) -> Self{
SidebarFunctionality{
account_type: Rc::from(RefCell::from(at))
}
}
pub fn test(&mut self){
let x = &self.account_type;
println!("{}",x.try_borrow().unwrap());
}
} |
use super::super::error::{Error, ErrorKind, Result};
/// Describes the shape of a tensor.
///
/// **note**: `From` conversion implementations are provided for low-rank shapes.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct TensorShape {
/// The number of components the associated tensor can store.
///
/// # Example
///
/// ```{.text}
/// // The following tensor has 9 components
///
/// [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
/// ```
pub capacity: usize,
/// A list of numbers with each representing the dimension at each index.
///
/// # Example
///
/// The following tensor has a shape of `[2, 1]`:
///
/// ```{.text}
/// [[a], [b]]
/// ```
pub dimsizes: Vec<usize>,
// /// The stride tells the tensor how to interpret its flattened representation.
// stride: Vec<usize>,
}
impl TensorShape {
/// Checks that the shape of the provided `data` is compatible.
pub fn check<T>(&self, data: &[T]) -> Result {
if self.capacity != data.len() {
let message = format!(
"TODO: incompatible shape. Capacity = {}, Length = {}",
self.capacity,
data.len());
let kind = ErrorKind::IncompatibleShape;
let e = Error::new(kind, message);
return Err(e);
}
Ok(())
}
/// Returns the `dimensions`.
pub fn dimensions(&self) -> &[usize] {
&self.dimsizes
}
/// Returns the number of elements the tensor can hold without reallocating.
pub fn capacity(&self) -> usize {
self.capacity
}
/// Returns the total number of indices required to identify each component uniquely (i.e, the
/// tensor's rank, degree, or order).
///
/// # Example
///
/// The following tensor has a rank of 2:
///
/// ```{.text}
/// [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
/// ```
pub fn rank(&self) -> usize {
self.dimsizes.len()
}
}
impl From<Vec<usize>> for TensorShape {
fn from(vector: Vec<usize>) -> TensorShape {
TensorShape {
capacity: vector.iter().fold(1, |acc, &dims| acc * dims),
dimsizes: vector,
}
}
}
impl<'slice> From<&'slice [usize]> for TensorShape {
fn from(slice: &[usize]) -> TensorShape {
TensorShape {
capacity: slice.iter().fold(1, |acc, &dims| acc * dims),
dimsizes: slice.to_owned(),
}
}
}
impl From<usize> for TensorShape {
fn from(dimensions: usize) -> TensorShape {
TensorShape {
capacity: dimensions,
dimsizes: vec![dimensions],
}
}
}
macro_rules! shape {
($($length:expr),*) => ($(impl From<[usize; $length]> for TensorShape {
fn from(array: [usize; $length]) -> TensorShape {
TensorShape {
capacity: array.iter().fold(1, |acc, &dims| acc * dims),
dimsizes: array.to_vec(),
}
}
})*)
}
shape!(0, 1, 2, 3, 4, 5, 6); |
use ast;
use name::*;
use ast::walker::*;
use arena::Arena;
use std::collections::hash_map;
use middle::*;
struct Collector<'a, 'ast: 'a> {
arena: &'a Arena<'a, 'ast>,
package: PackageRef<'a, 'ast>,
scope: Vec<Symbol>,
tydef: Option<TypeDefinitionRef<'a, 'ast>>,
}
impl<'a, 'ast> Walker<'ast> for Collector<'a, 'ast> {
fn walk_type_declaration(&mut self, ty_decl: &'ast ast::TypeDeclaration) {
let name = ty_decl.name();
let kind = match ty_decl.node {
ast::TypeDeclaration_::Class(..) => TypeKind::Class,
ast::TypeDeclaration_::Interface(..) => TypeKind::Interface,
};
self.scope.push(name.node);
let fq_type = Qualified(self.scope.iter()).to_string();
let tydef = self.arena.alloc(TypeDefinition::new(fq_type, kind, self.package, ty_decl));
// Insert `tydef` into the package
match self.package.contents.borrow_mut().entry(name.node) {
hash_map::Entry::Occupied(v) => {
match *v.get() {
PackageItem::Package(..) => {
type_package_conflict(&*tydef);
}
PackageItem::TypeDefinition(..) => {
span_error!(name.span,
"type `{}` already exists in package `{}`",
name, self.package.fq_name);
}
}
return
}
hash_map::Entry::Vacant(v) => {
v.insert(PackageItem::TypeDefinition(tydef));
}
}
self.tydef = Some(tydef);
self.scope.pop();
}
}
fn type_package_conflict(tydef: &TypeDefinition) {
span_error!(tydef.ast.name().span,
// Technically this is the name of the type, not the package,
// but the point is that they're the same...
"type name conflicts with package `{}`",
tydef.fq_name);
}
// Looks up a package by qualified identifier, creating it if necessary.
// If a name conflict occurs, this will create a dummy package.
fn resolve_create_package<'a, 'ast>(arena: &'a Arena<'a, 'ast>, toplevel: PackageRef<'a, 'ast>, id: &[Ident]) -> PackageRef<'a, 'ast> {
id.iter().enumerate().fold(toplevel, |package, (ix, ident)| {
let new = || arena.alloc(Package::new(Qualified(id[0..ix+1].iter()).to_string()));
match package.contents.borrow_mut().entry(ident.node) {
hash_map::Entry::Occupied(mut v) => {
let slot = v.get_mut();
match *slot {
PackageItem::Package(it) => return it, // Found it
PackageItem::TypeDefinition(ref tydef) => {
// There was a type instead!
type_package_conflict(&**tydef);
}
}
// Kick out the type and put a package instead.
// This prevents a spray of errors in case one type conflicts with a package with
// many compilation units
let next = new();
*slot = PackageItem::Package(next);
next
}
hash_map::Entry::Vacant(v) => {
let next = new();
v.insert(PackageItem::Package(next));
next
}
}
})
}
// Phase 1.
pub fn collect_types<'a, 'ast>(arena: &'a Arena<'a, 'ast>,
toplevel: PackageRef<'a, 'ast>,
default_package: PackageRef<'a, 'ast>,
asts: &'ast [ast::CompilationUnit])
-> Vec<(PackageRef<'a, 'ast>, &'ast ast::CompilationUnit, TypeDefinitionRef<'a, 'ast>)> {
let mut r = vec![];
for ast in asts.iter() {
let (package, scope) = if let Some(ref package_identifier) = ast.package {
(resolve_create_package(arena, toplevel, &*package_identifier.parts),
package_identifier.parts.iter().map(|x| x.node).collect())
} else {
(default_package, vec![Symbol::from_str("")])
};
let mut collector = Collector {
arena: arena,
package: package,
scope: scope,
tydef: None,
};
collector.walk_compilation_unit(ast);
if let Some(tydef) = collector.tydef {
r.push((package, ast, tydef));
}
}
r
}
|
/*
* Datadog API V1 Collection
*
* Collection of all Datadog Public endpoints.
*
* The version of the OpenAPI document: 1.0
* Contact: support@datadoghq.com
* Generated by: https://openapi-generator.tech
*/
/// HostMapWidgetDefinitionRequests : List of definitions.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct HostMapWidgetDefinitionRequests {
#[serde(rename = "fill", skip_serializing_if = "Option::is_none")]
pub fill: Option<Box<crate::models::HostMapRequest>>,
#[serde(rename = "size", skip_serializing_if = "Option::is_none")]
pub size: Option<Box<crate::models::HostMapRequest>>,
}
impl HostMapWidgetDefinitionRequests {
/// List of definitions.
pub fn new() -> HostMapWidgetDefinitionRequests {
HostMapWidgetDefinitionRequests {
fill: None,
size: None,
}
}
}
|
#[doc = "Register `AHB1SMENR` reader"]
pub type R = crate::R<AHB1SMENR_SPEC>;
#[doc = "Register `AHB1SMENR` writer"]
pub type W = crate::W<AHB1SMENR_SPEC>;
#[doc = "Field `DMA1SMEN` reader - CPU1 DMA1 clocks enable during Sleep and Stop modes"]
pub type DMA1SMEN_R = crate::BitReader;
#[doc = "Field `DMA1SMEN` writer - CPU1 DMA1 clocks enable during Sleep and Stop modes"]
pub type DMA1SMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `DMA2SMEN` reader - CPU1 DMA2 clocks enable during Sleep and Stop modes"]
pub type DMA2SMEN_R = crate::BitReader;
#[doc = "Field `DMA2SMEN` writer - CPU1 DMA2 clocks enable during Sleep and Stop modes"]
pub type DMA2SMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `DMAMUXSMEN` reader - CPU1 DMAMUX clocks enable during Sleep and Stop modes"]
pub type DMAMUXSMEN_R = crate::BitReader;
#[doc = "Field `DMAMUXSMEN` writer - CPU1 DMAMUX clocks enable during Sleep and Stop modes"]
pub type DMAMUXSMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `SRAM1SMEN` reader - CPU1 SRAM1 interface clocks enable during Sleep and Stop modes"]
pub type SRAM1SMEN_R = crate::BitReader;
#[doc = "Field `SRAM1SMEN` writer - CPU1 SRAM1 interface clocks enable during Sleep and Stop modes"]
pub type SRAM1SMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CRCSMEN` reader - CPU1 CRCSMEN"]
pub type CRCSMEN_R = crate::BitReader;
#[doc = "Field `CRCSMEN` writer - CPU1 CRCSMEN"]
pub type CRCSMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TSCSMEN` reader - CPU1 Touch Sensing Controller clocks enable during Sleep and Stop modes"]
pub type TSCSMEN_R = crate::BitReader;
#[doc = "Field `TSCSMEN` writer - CPU1 Touch Sensing Controller clocks enable during Sleep and Stop modes"]
pub type TSCSMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bit 0 - CPU1 DMA1 clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn dma1smen(&self) -> DMA1SMEN_R {
DMA1SMEN_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - CPU1 DMA2 clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn dma2smen(&self) -> DMA2SMEN_R {
DMA2SMEN_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 2 - CPU1 DMAMUX clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn dmamuxsmen(&self) -> DMAMUXSMEN_R {
DMAMUXSMEN_R::new(((self.bits >> 2) & 1) != 0)
}
#[doc = "Bit 9 - CPU1 SRAM1 interface clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn sram1smen(&self) -> SRAM1SMEN_R {
SRAM1SMEN_R::new(((self.bits >> 9) & 1) != 0)
}
#[doc = "Bit 12 - CPU1 CRCSMEN"]
#[inline(always)]
pub fn crcsmen(&self) -> CRCSMEN_R {
CRCSMEN_R::new(((self.bits >> 12) & 1) != 0)
}
#[doc = "Bit 16 - CPU1 Touch Sensing Controller clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn tscsmen(&self) -> TSCSMEN_R {
TSCSMEN_R::new(((self.bits >> 16) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - CPU1 DMA1 clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn dma1smen(&mut self) -> DMA1SMEN_W<AHB1SMENR_SPEC, 0> {
DMA1SMEN_W::new(self)
}
#[doc = "Bit 1 - CPU1 DMA2 clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn dma2smen(&mut self) -> DMA2SMEN_W<AHB1SMENR_SPEC, 1> {
DMA2SMEN_W::new(self)
}
#[doc = "Bit 2 - CPU1 DMAMUX clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn dmamuxsmen(&mut self) -> DMAMUXSMEN_W<AHB1SMENR_SPEC, 2> {
DMAMUXSMEN_W::new(self)
}
#[doc = "Bit 9 - CPU1 SRAM1 interface clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn sram1smen(&mut self) -> SRAM1SMEN_W<AHB1SMENR_SPEC, 9> {
SRAM1SMEN_W::new(self)
}
#[doc = "Bit 12 - CPU1 CRCSMEN"]
#[inline(always)]
#[must_use]
pub fn crcsmen(&mut self) -> CRCSMEN_W<AHB1SMENR_SPEC, 12> {
CRCSMEN_W::new(self)
}
#[doc = "Bit 16 - CPU1 Touch Sensing Controller clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn tscsmen(&mut self) -> TSCSMEN_W<AHB1SMENR_SPEC, 16> {
TSCSMEN_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 = "AHB1 peripheral clocks enable in Sleep and Stop modes register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ahb1smenr::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 [`ahb1smenr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct AHB1SMENR_SPEC;
impl crate::RegisterSpec for AHB1SMENR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`ahb1smenr::R`](R) reader structure"]
impl crate::Readable for AHB1SMENR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`ahb1smenr::W`](W) writer structure"]
impl crate::Writable for AHB1SMENR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets AHB1SMENR to value 0x0001_1207"]
impl crate::Resettable for AHB1SMENR_SPEC {
const RESET_VALUE: Self::Ux = 0x0001_1207;
}
|
//! Contains the types for read concerns and write concerns.
#[cfg(test)]
mod test;
use std::time::Duration;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use serde_with::skip_serializing_none;
use typed_builder::TypedBuilder;
use crate::{
bson::{doc, serde_helpers, Timestamp},
error::{ErrorKind, Result},
serde_util,
};
/// Specifies the consistency and isolation properties of read operations from replica sets and
/// replica set shards.
///
/// See the documentation [here](https://www.mongodb.com/docs/manual/reference/read-concern/) for more
/// information about read concerns.
#[skip_serializing_none]
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct ReadConcern {
/// The level of the read concern.
pub level: ReadConcernLevel,
}
impl ReadConcern {
/// A `ReadConcern` with level `ReadConcernLevel::Local`.
pub const LOCAL: ReadConcern = ReadConcern {
level: ReadConcernLevel::Local,
};
/// A `ReadConcern` with level `ReadConcernLevel::Majority`.
pub const MAJORITY: ReadConcern = ReadConcern {
level: ReadConcernLevel::Majority,
};
/// A `ReadConcern` with level `ReadConcernLevel::Linearizable`.
pub const LINEARIZABLE: ReadConcern = ReadConcern {
level: ReadConcernLevel::Linearizable,
};
/// A `ReadConcern` with level `ReadConcernLevel::Available`.
pub const AVAILABLE: ReadConcern = ReadConcern {
level: ReadConcernLevel::Available,
};
/// A `ReadConcern` with level `ReadConcernLevel::Snapshot`.
pub const SNAPSHOT: ReadConcern = ReadConcern {
level: ReadConcernLevel::Snapshot,
};
}
/// An internal-only read concern type that allows the omission of a "level" as well as
/// specification of "atClusterTime" and "afterClusterTime".
#[skip_serializing_none]
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
#[serde(rename = "readConcern")]
pub(crate) struct ReadConcernInternal {
/// The level of the read concern.
pub(crate) level: Option<ReadConcernLevel>,
/// The snapshot read timestamp.
pub(crate) at_cluster_time: Option<Timestamp>,
/// The time of most recent operation using this session.
/// Used for providing causal consistency.
pub(crate) after_cluster_time: Option<Timestamp>,
}
impl ReadConcern {
/// Creates a read concern with level "majority".
/// See the specific documentation for this read concern level [here](https://www.mongodb.com/docs/manual/reference/read-concern-majority/).
pub fn majority() -> Self {
ReadConcernLevel::Majority.into()
}
/// Creates a read concern with level "local".
/// See the specific documentation for this read concern level [here](https://www.mongodb.com/docs/manual/reference/read-concern-local/).
pub fn local() -> Self {
ReadConcernLevel::Local.into()
}
/// Creates a read concern with level "linearizable".
/// See the specific documentation for this read concern level [here](https://www.mongodb.com/docs/manual/reference/read-concern-linearizable/).
pub fn linearizable() -> Self {
ReadConcernLevel::Linearizable.into()
}
/// Creates a read concern with level "available".
/// See the specific documentation for this read concern level [here](https://www.mongodb.com/docs/manual/reference/read-concern-available/).
pub fn available() -> Self {
ReadConcernLevel::Available.into()
}
/// Creates a read concern with level "snapshot".
/// See the specific documentation for this read concern level [here](https://www.mongodb.com/docs/manual/reference/read-concern-snapshot/).
pub fn snapshot() -> Self {
ReadConcernLevel::Snapshot.into()
}
/// Creates a read concern with a custom read concern level. This is present to provide forwards
/// compatibility with any future read concerns which may be added to new versions of
/// MongoDB.
pub fn custom(level: String) -> Self {
ReadConcernLevel::from_str(level.as_str()).into()
}
#[cfg(test)]
pub(crate) fn serialize_for_client_options<S>(
read_concern: &Option<ReadConcern>,
serializer: S,
) -> std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
#[derive(Serialize)]
struct ReadConcernHelper<'a> {
readconcernlevel: &'a str,
}
let state = read_concern.as_ref().map(|concern| ReadConcernHelper {
readconcernlevel: concern.level.as_str(),
});
state.serialize(serializer)
}
}
impl From<ReadConcern> for ReadConcernInternal {
fn from(rc: ReadConcern) -> Self {
ReadConcernInternal {
level: Some(rc.level),
at_cluster_time: None,
after_cluster_time: None,
}
}
}
impl From<ReadConcernLevel> for ReadConcern {
fn from(level: ReadConcernLevel) -> Self {
Self { level }
}
}
/// Specifies the level consistency and isolation properties of a given `ReadCocnern`.
///
/// See the documentation [here](https://www.mongodb.com/docs/manual/reference/read-concern/) for more
/// information about read concerns.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum ReadConcernLevel {
/// See the specific documentation for this read concern level [here](https://www.mongodb.com/docs/manual/reference/read-concern-local/).
Local,
/// See the specific documentation for this read concern level [here](https://www.mongodb.com/docs/manual/reference/read-concern-majority/).
Majority,
/// See the specific documentation for this read concern level [here](https://www.mongodb.com/docs/manual/reference/read-concern-linearizable/).
Linearizable,
/// See the specific documentation for this read concern level [here](https://www.mongodb.com/docs/manual/reference/read-concern-available/).
Available,
/// See the specific documentation for this read concern level [here](https://www.mongodb.com/docs/manual/reference/read-concern-snapshot/).
Snapshot,
/// Specify a custom read concern level. This is present to provide forwards compatibility with
/// any future read concerns which may be added to new versions of MongoDB.
Custom(String),
}
impl ReadConcernLevel {
pub(crate) fn from_str(s: &str) -> Self {
match s {
"local" => ReadConcernLevel::Local,
"majority" => ReadConcernLevel::Majority,
"linearizable" => ReadConcernLevel::Linearizable,
"available" => ReadConcernLevel::Available,
"snapshot" => ReadConcernLevel::Snapshot,
s => ReadConcernLevel::Custom(s.to_string()),
}
}
/// Gets the string representation of the `ReadConcernLevel`.
pub(crate) fn as_str(&self) -> &str {
match self {
ReadConcernLevel::Local => "local",
ReadConcernLevel::Majority => "majority",
ReadConcernLevel::Linearizable => "linearizable",
ReadConcernLevel::Available => "available",
ReadConcernLevel::Snapshot => "snapshot",
ReadConcernLevel::Custom(ref s) => s,
}
}
}
impl<'de> Deserialize<'de> for ReadConcernLevel {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> std::result::Result<Self, D::Error> {
let s = String::deserialize(deserializer)?;
Ok(ReadConcernLevel::from_str(&s))
}
}
impl Serialize for ReadConcernLevel {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
self.as_str().serialize(serializer)
}
}
/// Specifies the level of acknowledgement requested from the server for write operations.
///
/// See the documentation [here](https://www.mongodb.com/docs/manual/reference/write-concern/) for more
/// information about write concerns.
#[skip_serializing_none]
#[derive(Clone, Debug, Default, PartialEq, TypedBuilder, Serialize, Deserialize)]
#[builder(field_defaults(default, setter(into)))]
#[non_exhaustive]
pub struct WriteConcern {
/// Requests acknowledgement that the operation has propagated to a specific number or variety
/// of servers.
pub w: Option<Acknowledgment>,
/// Specifies a time limit for the write concern. If an operation has not propagated to the
/// requested level within the time limit, an error will return.
///
/// Note that an error being returned due to a write concern error does not imply that the
/// write would not have finished propagating if allowed more time to finish, and the
/// server will not roll back the writes that occurred before the timeout was reached.
#[serde(rename = "wtimeout", alias = "wtimeoutMS")]
#[serde(serialize_with = "serde_util::serialize_duration_option_as_int_millis")]
#[serde(deserialize_with = "serde_util::deserialize_duration_option_from_u64_millis")]
#[serde(default)]
pub w_timeout: Option<Duration>,
/// Requests acknowledgement that the operation has propagated to the on-disk journal.
#[serde(rename = "j", alias = "journal")]
pub journal: Option<bool>,
}
impl WriteConcern {
// Can't use `Default::default()` in const contexts yet :(
const DEFAULT: WriteConcern = WriteConcern {
w: None,
w_timeout: None,
journal: None,
};
/// A `WriteConcern` requesting `Acknowledgment::Majority`.
pub const MAJORITY: WriteConcern = WriteConcern {
w: Some(Acknowledgment::Majority),
..WriteConcern::DEFAULT
};
}
/// The type of the `w` field in a [`WriteConcern`](struct.WriteConcern.html).
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum Acknowledgment {
/// Requires acknowledgement that the write has reached the specified number of nodes.
///
/// Note: specifying 0 here indicates that the write concern is unacknowledged, which is
/// currently unsupported and will result in an error during operation execution.
Nodes(u32),
/// Requires acknowledgement that the write has reached the majority of nodes.
Majority,
/// Requires acknowledgement according to the given custom write concern. See [here](https://www.mongodb.com/docs/manual/tutorial/configure-replica-set-tag-sets/#tag-sets-and-custom-write-concern-behavior)
/// for more information.
Custom(String),
}
impl Serialize for Acknowledgment {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
match self {
Acknowledgment::Majority => serializer.serialize_str("majority"),
Acknowledgment::Nodes(n) => serde_helpers::serialize_u32_as_i32(n, serializer),
Acknowledgment::Custom(name) => serializer.serialize_str(name),
}
}
}
impl<'de> Deserialize<'de> for Acknowledgment {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: Deserializer<'de>,
{
#[derive(Deserialize)]
#[serde(untagged)]
enum IntOrString {
Int(u32),
String(String),
}
match IntOrString::deserialize(deserializer)? {
IntOrString::String(s) => Ok(s.into()),
IntOrString::Int(i) => Ok(i.into()),
}
}
}
impl From<u32> for Acknowledgment {
fn from(i: u32) -> Self {
Acknowledgment::Nodes(i)
}
}
impl From<String> for Acknowledgment {
fn from(s: String) -> Self {
if s == "majority" {
Acknowledgment::Majority
} else {
Acknowledgment::Custom(s)
}
}
}
impl WriteConcern {
pub(crate) fn is_acknowledged(&self) -> bool {
self.w != Some(Acknowledgment::Nodes(0)) || self.journal == Some(true)
}
/// Whether the write concern was created with no values specified. If true, the write concern
/// should be considered the server's default.
pub(crate) fn is_empty(&self) -> bool {
self.w.is_none() && self.w_timeout.is_none() && self.journal.is_none()
}
/// Validates that the write concern. A write concern is invalid if both the `w` field is 0
/// and the `j` field is `true`.
pub(crate) fn validate(&self) -> Result<()> {
if self.w == Some(Acknowledgment::Nodes(0)) && self.journal == Some(true) {
return Err(ErrorKind::InvalidArgument {
message: "write concern cannot have w=0 and j=true".to_string(),
}
.into());
}
if let Some(w_timeout) = self.w_timeout {
if w_timeout < Duration::from_millis(0) {
return Err(ErrorKind::InvalidArgument {
message: "write concern `w_timeout` field cannot be negative".to_string(),
}
.into());
}
}
Ok(())
}
#[cfg(test)]
pub(crate) fn serialize_for_client_options<S>(
write_concern: &Option<WriteConcern>,
serializer: S,
) -> std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
#[derive(Serialize)]
struct WriteConcernHelper<'a> {
w: Option<&'a Acknowledgment>,
#[serde(serialize_with = "serde_util::serialize_duration_option_as_int_millis")]
wtimeoutms: Option<Duration>,
journal: Option<bool>,
}
let state = write_concern.as_ref().map(|concern| WriteConcernHelper {
w: concern.w.as_ref(),
wtimeoutms: concern.w_timeout,
journal: concern.journal,
});
state.serialize(serializer)
}
}
|
#![allow(unused_imports)]
#![allow(unused_variables)]
extern crate regex;
use std::collections::HashSet;
use glr_grammar;
use glr_grammar::Atom as Atom;
use glr_grammar::GrammarItem as GrammarItem;
use std::sync::Arc;
use self::regex::Regex;
#[derive(Debug,Clone,Hash,PartialEq,Eq,PartialOrd,Ord)]
pub struct Lex {
pub atom: Arc<Atom>,
pub value: Option<Arc<String>>
}
fn escape_re_string(raw: String) -> String {
let re = Regex::new(r"(?P<c>[\\\.\+\*\?\(\)\|\[\]\{\}\^\$])").unwrap();
re.replace_all(&raw, "\\$c")
}
fn gen_re(lex_re_string: String, grammar_strings: Vec<String>) -> (Vec<String>, String) {
let mut re_string: String = String::new();
let mut tokens: Vec<String> = Vec::new();
let test_w = Regex::new(r"^\w+$").unwrap();
let mut added_grammar: HashSet<String> = HashSet::new();
for item in grammar_strings.iter() {
if added_grammar.contains(item) {continue}
if re_string.len() > 0 { re_string.push('|'); }
re_string.push_str(item);
if test_w.is_match(item) {
re_string.push_str("\\b");
}
// re_string.push_str(&("(?:".to_string() + item + ")"));
// tokens.push(item.clone());
added_grammar.insert(item.clone());
}
for line in lex_re_string.split("\n") {
if line.trim().len() == 0 {continue}
let mut reg: String = String::new();
let mut index = 0u16;
for item in line.split("=") {
if index == 0 {
tokens.push(item.trim().to_string());
} else {
if index > 1 {reg.push_str("=")}
reg.push_str(item.trim());
}
index += 1;
}
re_string.push_str(&("|(".to_string() + ® + ")"));
}
// println!("{:?}", re_string);
(tokens, re_string)
}
pub fn gen_lex(program_raw: String, raw_lex_string: String, raw_grammar_string: String) -> (Vec<Arc<Lex>>, Vec<String>){
let mut ret: Vec<Arc<Lex>> = Vec::new();
let mut grammar_strings: Vec<String> = Vec::new();
let re = Regex::new("'[^']+'").unwrap();
for cap in re.captures_iter(&raw_grammar_string) {
for val in cap.iter() {
grammar_strings.push(escape_re_string(val.unwrap().to_string().replace("'", "")));
}
}
let (tokens, re_string) = gen_re(raw_lex_string, grammar_strings);
match Regex::new(&re_string) {
Err(e) => {panic!("Lex Creating Error...")},
Ok(ret_re) => {
for cap in ret_re.captures_iter(&program_raw) {
let mut index = 0u16;
let mut val: String = String::new();
for name in cap.iter() {
if index == 0 {index += 1; continue;}
if let Some(x) = name {
val = x.to_string();
break;
}
index += 1;
}
if index as usize == cap.len() {
ret.push(Arc::new(Lex {atom: Arc::new(Atom::Terminal(Arc::new(cap.at(0).unwrap().to_string()))), value: None}));
} else if let Some(token) = tokens.get(index as usize - 1) {
ret.push(Arc::new(Lex {atom: Arc::new(Atom::Terminal(Arc::new(token.clone()))), value: Some(Arc::new(val))}));
}
}
}
}
(ret, tokens)
} |
// 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.
//! Declaration of store trait and implementation on module structure.
use super::DeclStorageDefExt;
use proc_macro2::TokenStream;
use quote::quote;
pub fn decl_and_impl(def: &DeclStorageDefExt) -> TokenStream {
let decl_store_items = def.storage_lines.iter().map(|sline| &sline.name).fold(
TokenStream::new(),
|mut items, name| {
items.extend(quote!(type #name;));
items
},
);
let impl_store_items = def.storage_lines.iter().fold(TokenStream::new(), |mut items, line| {
let name = &line.name;
let storage_struct = &line.storage_struct;
items.extend(quote!(type #name = #storage_struct;));
items
});
let visibility = &def.visibility;
let store_trait = &def.store_trait;
let module_struct = &def.module_struct;
let module_impl = &def.module_impl;
let where_clause = &def.where_clause;
quote!(
#visibility trait #store_trait {
#decl_store_items
}
impl#module_impl #store_trait for #module_struct #where_clause {
#impl_store_items
}
)
}
|
use crate::component::{CompositeSurfaceCache, CompositeTilemap, CompositeTilemapAnimation};
use core::{
app::AppLifeCycle,
ecs::{Comp, Universe, WorldRef},
Scalar,
};
pub type CompositeTilemapAnimationSystemResources<'a> = (
WorldRef,
&'a AppLifeCycle,
Comp<&'a mut CompositeTilemap>,
Comp<&'a mut CompositeTilemapAnimation>,
Comp<&'a mut CompositeSurfaceCache>,
);
pub fn composite_tilemap_animation_system(universe: &mut Universe) {
let (world, lifecycle, ..) =
universe.query_resources::<CompositeTilemapAnimationSystemResources>();
let dt = lifecycle.delta_time_seconds() as Scalar;
for (_, (tilemap, animation, cache)) in world
.query::<(
&mut CompositeTilemap,
&mut CompositeTilemapAnimation,
Option<&mut CompositeSurfaceCache>,
)>()
.iter()
{
if animation.dirty {
animation.dirty = false;
if let Some((name, phase, _, _)) = &animation.current {
if let Some(anim) = animation.animations.get(name) {
if let Some(frame) = anim.frames.get(*phase as usize) {
tilemap.set_tileset(Some(anim.tileset.clone()));
tilemap.set_grid(frame.clone());
if let Some(cache) = cache {
cache.rebuild();
}
}
}
}
}
animation.process(dt);
}
}
|
//https://gist.github.com/horyu/566a5155db897a47b5d893e9307e1f93
pub fn make_permutation(n: usize) -> Vec<Vec<usize>> {
let mut vecs: Vec<Vec<usize>> = vec![Vec::new(); factorial(n)];
let nums: Vec<usize> = (0..n).collect();
let indexes: Vec<usize> = (0..factorial(n)).collect();
push_recusive(nums, indexes, &mut vecs);
vecs
}
fn push_recusive<T: Clone>(
nums: Vec<T>,
indexes: Vec<usize>,
vecs: &mut Vec<Vec<T>>,
) -> &mut Vec<Vec<T>> {
if nums.len() == 0 {
return vecs;
}
let block_size = factorial(nums.len() - 1);
for (block_index, num) in nums.iter().enumerate() {
for inner_index in 0..block_size {
let index = indexes[block_size * block_index + inner_index];
vecs[index].push(num.clone());
}
let new_nums = {
let mut tmp = nums.clone();
tmp.remove(block_index);
tmp
};
let new_indexes: Vec<usize> = {
let slice = &indexes[(block_size * block_index)..(block_size * (block_index + 1))];
slice.to_vec()
};
push_recusive(new_nums, new_indexes, vecs);
}
vecs
}
fn factorial(i: usize) -> usize {
if i <= 1 {
1
} else {
(2..=i).fold(1, |acc, x| acc * x)
}
}
|
use libriakv::RiaKV;
use std::fs::{File, OpenOptions};
use std::io;
use std::path::Path;
#[cfg(target_os = "windows")]
const USAGE: &str = "
CLI client for RiaKV key value store with persistent index.
Usage:
riakv_mem.exe STORAGE_FILE INDEX_FILE get KEY
riakv_mem.exe STORAGE_FILE INDEX_FILE delete KEY
riakv_mem.exe STORAGE_FILE INDEX_FILE insert KEY VALUE
riakv_mem.exe STORAGE_FILE INDEX_FILE update KEY VALUE
";
#[cfg(target_os = "linux")]
const USAGE: &str = "
CLI client for RiaKV key value store with persistent index.
Usage:
riakv_mem STORAGE_FILE INDEX_FILE get KEY
riakv_mem STORAGE_FILE INDEX_FILE delete KEY
riakv_mem STORAGE_FILE INDEX_FILE insert KEY VALUE
riakv_mem STORAGE_FILE INDEX_FILE update KEY VALUE
";
fn index_file_from_path(path: &Path) -> io::Result<File> {
OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(path)
}
fn main() {
let args: Vec<String> = std::env::args().collect();
let storage_fname = args.get(1).expect(&USAGE);
let index_fname = args.get(2).expect(&USAGE);
let action = args.get(3).expect(&USAGE).as_ref();
let key = args.get(4).expect(&USAGE).as_ref();
let maybe_value = args.get(5);
let storage_path = Path::new(storage_fname);
let mut store = RiaKV::open_from_file_at_path(storage_path).expect("unable to open file");
let index_path = Path::new(index_fname);
let mut index_file = index_file_from_path(index_path).expect("unable to open index file");
store
.load_index(&mut index_file)
.expect("unable to deserialize index");
match action {
"get" => match store.get(key).unwrap() {
None => eprintln!("{:?} not found", key),
Some(value) => println!("{:?}", value),
},
"delete" => store.delete(key).unwrap(),
"insert" => {
let value = maybe_value.expect(&USAGE).as_ref();
store.insert(key, value).unwrap()
}
"update" => {
let value = maybe_value.expect(&USAGE).as_ref();
store.update(key, value).unwrap()
}
_ => eprintln!("{}", &USAGE),
}
store
.persist_index(&mut index_file)
.expect("unable to serialize index");
}
|
#[doc = "Register `GICC_NSAPR0` reader"]
pub type R = crate::R<GICC_NSAPR0_SPEC>;
#[doc = "Register `GICC_NSAPR0` writer"]
pub type W = crate::W<GICC_NSAPR0_SPEC>;
#[doc = "Field `NSAPR0` reader - NSAPR0"]
pub type NSAPR0_R = crate::FieldReader<u32>;
#[doc = "Field `NSAPR0` writer - NSAPR0"]
pub type NSAPR0_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 32, O, u32>;
impl R {
#[doc = "Bits 0:31 - NSAPR0"]
#[inline(always)]
pub fn nsapr0(&self) -> NSAPR0_R {
NSAPR0_R::new(self.bits)
}
}
impl W {
#[doc = "Bits 0:31 - NSAPR0"]
#[inline(always)]
#[must_use]
pub fn nsapr0(&mut self) -> NSAPR0_W<GICC_NSAPR0_SPEC, 0> {
NSAPR0_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 = "GICC non-secure active priority register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`gicc_nsapr0::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 [`gicc_nsapr0::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct GICC_NSAPR0_SPEC;
impl crate::RegisterSpec for GICC_NSAPR0_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`gicc_nsapr0::R`](R) reader structure"]
impl crate::Readable for GICC_NSAPR0_SPEC {}
#[doc = "`write(|w| ..)` method takes [`gicc_nsapr0::W`](W) writer structure"]
impl crate::Writable for GICC_NSAPR0_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets GICC_NSAPR0 to value 0"]
impl crate::Resettable for GICC_NSAPR0_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
#[doc = "Register `I3C_CR_ALTERNATE` writer"]
pub type W = crate::W<I3C_CR_ALTERNATE_SPEC>;
#[doc = "Field `DCNT` writer - count of data to transfer during a read or write message, in bytes (when I3C is acting as controller) Linear encoding up to 64 Kbytes -1. ..."]
pub type DCNT_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 16, O, u16>;
#[doc = "Field `CCC` writer - 8-bit CCC code (when I3C is acting as controller) If Bit\\[23\\]=CCC\\[7\\]=1, this is the 1st part of an I3C SDR direct CCC command. If Bit\\[23\\]=CCC\\[7\\]=0, this is an I3C SDR broadcast CCC command (including ENTDAA and ENTHDR0)."]
pub type CCC_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 8, O>;
#[doc = "Field `MTYPE` writer - message type (when I3C is acting as controller) Bits\\[23:16\\]
(CCC\\[7:0\\]) is the emitted 8-bit CCC code If Bit\\[23\\]=CCC\\[7\\]=1: this is the 1st part of an I3C SDR direct CCC command The transferred direct CCC command message is: {S / S+7’h7E +RnW=0 / Sr+*} + (direct CCC + T) + (8-bit Data + T)* + Sr After a S (START), depending on I3C_CFGR.NOARBH, the arbitrable header (7’h7E+RnW=0) is inserted or not. Sr+*: after a Sr (Repeated Start), the hardware automatically inserts (7’h7E+R/W). If Bit\\[23\\]=CCC\\[7\\]=0: this is an I3C SDR broadcast CCC command (including ENTDAA and ENTHDR0) The transferred broadcast CCC command message is: {S / S+7’h7E +RnW=0 / Sr+*} + (broadcast CCC + T) + (8-bit Data + T)* + Sr/P After a S (START), depending on I3C_CFGR.NOARBH, the arbitrable header (7’h7E+RnW=0) is inserted or not. Sr+*: after a Sr (Repeated Start), the hardware automatically inserts (7’h7E+R/W). others: reserved"]
pub type MTYPE_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 4, O>;
#[doc = "Field `MEND` writer - message end type (when I3C is acting as controller)"]
pub type MEND_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl W {
#[doc = "Bits 0:15 - count of data to transfer during a read or write message, in bytes (when I3C is acting as controller) Linear encoding up to 64 Kbytes -1. ..."]
#[inline(always)]
#[must_use]
pub fn dcnt(&mut self) -> DCNT_W<I3C_CR_ALTERNATE_SPEC, 0> {
DCNT_W::new(self)
}
#[doc = "Bits 16:23 - 8-bit CCC code (when I3C is acting as controller) If Bit\\[23\\]=CCC\\[7\\]=1, this is the 1st part of an I3C SDR direct CCC command. If Bit\\[23\\]=CCC\\[7\\]=0, this is an I3C SDR broadcast CCC command (including ENTDAA and ENTHDR0)."]
#[inline(always)]
#[must_use]
pub fn ccc(&mut self) -> CCC_W<I3C_CR_ALTERNATE_SPEC, 16> {
CCC_W::new(self)
}
#[doc = "Bits 27:30 - message type (when I3C is acting as controller) Bits\\[23:16\\]
(CCC\\[7:0\\]) is the emitted 8-bit CCC code If Bit\\[23\\]=CCC\\[7\\]=1: this is the 1st part of an I3C SDR direct CCC command The transferred direct CCC command message is: {S / S+7’h7E +RnW=0 / Sr+*} + (direct CCC + T) + (8-bit Data + T)* + Sr After a S (START), depending on I3C_CFGR.NOARBH, the arbitrable header (7’h7E+RnW=0) is inserted or not. Sr+*: after a Sr (Repeated Start), the hardware automatically inserts (7’h7E+R/W). If Bit\\[23\\]=CCC\\[7\\]=0: this is an I3C SDR broadcast CCC command (including ENTDAA and ENTHDR0) The transferred broadcast CCC command message is: {S / S+7’h7E +RnW=0 / Sr+*} + (broadcast CCC + T) + (8-bit Data + T)* + Sr/P After a S (START), depending on I3C_CFGR.NOARBH, the arbitrable header (7’h7E+RnW=0) is inserted or not. Sr+*: after a Sr (Repeated Start), the hardware automatically inserts (7’h7E+R/W). others: reserved"]
#[inline(always)]
#[must_use]
pub fn mtype(&mut self) -> MTYPE_W<I3C_CR_ALTERNATE_SPEC, 27> {
MTYPE_W::new(self)
}
#[doc = "Bit 31 - message end type (when I3C is acting as controller)"]
#[inline(always)]
#[must_use]
pub fn mend(&mut self) -> MEND_W<I3C_CR_ALTERNATE_SPEC, 31> {
MEND_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 = "I3C message control register alternate\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 [`i3c_cr_alternate::W`](W). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct I3C_CR_ALTERNATE_SPEC;
impl crate::RegisterSpec for I3C_CR_ALTERNATE_SPEC {
type Ux = u32;
}
#[doc = "`write(|w| ..)` method takes [`i3c_cr_alternate::W`](W) writer structure"]
impl crate::Writable for I3C_CR_ALTERNATE_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets I3C_CR_ALTERNATE to value 0"]
impl crate::Resettable for I3C_CR_ALTERNATE_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
mod constraint_solver;
mod typed_constraint;
mod hinge_constraint;
pub use self::constraint_solver::*;
pub use self::typed_constraint::TypedConstraint;
pub use self::hinge_constraint::*;
|
use math::*;
use theme::*;
use render::*;
#[derive(Clone, Copy)]
pub struct Grid {
pub visible: bool,
pub size: Vector2<i16>,
pub offset: Vector2<i16>,
}
impl Grid {
pub fn paint(&self, ctx: &mut Canvas, zoom: i16, rect: Rect<i32>) {
if !self.visible {
return;
}
let (pos, size) = {
let min = rect.min;
let pos = Point2::new(min.x as i16, min.y as i16);
let size = Vector2::new(rect.dx() as i16, rect.dy() as i16);
(pos, size)
};
let grid_color = GRID_COLOR.to_be();
let corner_color = CORNER_COLOR.to_be();
let (ox, oy) = (pos.x, pos.y);
let (x1, x2) = (ox, ox + size.x * zoom);
let (y1, y2) = (oy, oy + size.y * zoom);
let ex = size.x / self.size.x;
let ey = size.y / self.size.y;
let ox = ox + (self.offset.x % self.size.x) * zoom;
let oy = oy + (self.offset.y % self.size.y) * zoom;
let zx = self.size.x * zoom;
let zy = self.size.y * zoom;
//ctx.clip(Rect::from_min_dim(pos, size * zoom));
for x in 1..ex + 1 {
let x = ox + x * zx;
ctx.vline(x - 1, y1, y2, grid_color);
}
for y in 1..ey + 1 {
let y = oy + y * zy;
ctx.hline(x1, x2, y - 1, grid_color);
}
//ctx.unclip();
// canvas border
ctx.hline(x1-1, x2, y1-1, corner_color);
ctx.hline(x1-1, x2, y2+0, corner_color);
ctx.vline(x1-1, y1-1, y2, corner_color);
ctx.vline(x2+0, y1-1, y2, corner_color);
}
}
|
use std::{mem, ptr};
struct SpscQueue<V: Send + Sync> {
buffer: *mut V,
capacity: usize,
capacity_mask: usize,
// We implement it at the queue level as it's a common requirement and so that V doesn't have to
// be a heavier enum with an end message variant.
ended: bool,
read_next: usize,
write_next: usize,
}
unsafe impl<V: Send + Sync> Send for SpscQueue<V> {}
unsafe impl<V: Send + Sync> Sync for SpscQueue<V> {}
impl<V: Send + Sync> Drop for SpscQueue<V> {
fn drop(&mut self) {
unsafe {
let _ = Vec::from_raw_parts(self.buffer, 0, self.capacity);
};
}
}
impl<V: Send + Sync> SpscQueue<V> {
pub fn new(capacity_exponent: usize) -> SpscQueue<V> {
assert!(capacity_exponent < mem::size_of::<usize>() * 8);
let capacity = 1 << capacity_exponent;
let mut vec = Vec::with_capacity(capacity);
let ptr = vec.as_mut_ptr();
mem::forget(vec);
SpscQueue {
buffer: ptr,
capacity,
capacity_mask: capacity - 1,
ended: false,
read_next: 0,
write_next: 0,
}
}
}
// Producer owns the underlying queue and drops it when itself is released.
pub struct SpscQueueProducer<V: Send + Sync> {
queue: *mut SpscQueue<V>,
}
unsafe impl<V: Send + Sync> Send for SpscQueueProducer<V> {}
unsafe impl<V: Send + Sync> Sync for SpscQueueProducer<V> {}
impl<V: Send + Sync> Drop for SpscQueueProducer<V> {
fn drop(&mut self) {
unsafe {
let _ = Box::from_raw(self.queue);
};
}
}
impl<V: Send + Sync> SpscQueueProducer<V> {
pub fn enqueue(&mut self, value: V) -> () {
let queue = unsafe { &mut *self.queue };
while queue.write_next >= queue.read_next + queue.capacity {
// Wait for consumer to catch up.
};
unsafe { ptr::write(queue.buffer.offset((queue.write_next & queue.capacity_mask) as isize), value) };
// Increment after setting buffer element.
queue.write_next += 1;
}
pub fn finish(&mut self) -> () {
let queue = unsafe { &mut *self.queue };
queue.ended = true;
}
}
pub enum MaybeDequeued<V> {
Ended,
None,
Some(V),
}
pub struct SpscQueueConsumer<V: Send + Sync> {
queue: *mut SpscQueue<V>,
}
unsafe impl<V: Send + Sync> Send for SpscQueueConsumer<V> {}
unsafe impl<V: Send + Sync> Sync for SpscQueueConsumer<V> {}
impl<V: Send + Sync> SpscQueueConsumer<V> {
#[inline(always)]
fn queue(&self) -> &SpscQueue<V> {
unsafe { &*self.queue }
}
#[inline(always)]
fn queue_mut(&self) -> &mut SpscQueue<V> {
unsafe { &mut *self.queue }
}
#[inline(always)]
pub fn is_empty(&self) -> bool {
let queue = self.queue();
queue.read_next >= queue.write_next
}
pub fn maybe_dequeue(&mut self) -> MaybeDequeued<V> {
if self.is_empty() {
if self.queue().ended {
return MaybeDequeued::Ended;
};
return MaybeDequeued::None;
};
let queue = self.queue_mut();
let value = unsafe { ptr::read(queue.buffer.offset((queue.read_next & queue.capacity_mask) as isize)) };
queue.read_next += 1;
MaybeDequeued::Some(value)
}
pub fn dequeue(&mut self) -> Option<V> {
loop {
match self.maybe_dequeue() {
// Wait for producer to provide values.
MaybeDequeued::None => {}
// We've caught up to the end.
MaybeDequeued::Ended => return None,
MaybeDequeued::Some(v) => return Some(v),
};
};
}
}
pub fn create_spsc_queue<V: Send + Sync>(capacity_exponent: usize) -> (SpscQueueProducer<V>, SpscQueueConsumer<V>) {
let queue = Box::into_raw(Box::new(SpscQueue::<V>::new(capacity_exponent)));
(SpscQueueProducer { queue }, SpscQueueConsumer { queue })
}
|
#[doc = "Reader of register SRSS_INTR_CFG"]
pub type R = crate::R<u32, super::SRSS_INTR_CFG>;
#[doc = "Writer for register SRSS_INTR_CFG"]
pub type W = crate::W<u32, super::SRSS_INTR_CFG>;
#[doc = "Register SRSS_INTR_CFG `reset()`'s with value 0"]
impl crate::ResetValue for super::SRSS_INTR_CFG {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Sets which edge(s) will trigger an IRQ for HVLVD1\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum HVLVD1_EDGE_SEL_A {
#[doc = "0: Disabled"]
DISABLE,
#[doc = "1: Rising edge"]
RISING,
#[doc = "2: Falling edge"]
FALLING,
#[doc = "3: Both rising and falling edges"]
BOTH,
}
impl From<HVLVD1_EDGE_SEL_A> for u8 {
#[inline(always)]
fn from(variant: HVLVD1_EDGE_SEL_A) -> Self {
match variant {
HVLVD1_EDGE_SEL_A::DISABLE => 0,
HVLVD1_EDGE_SEL_A::RISING => 1,
HVLVD1_EDGE_SEL_A::FALLING => 2,
HVLVD1_EDGE_SEL_A::BOTH => 3,
}
}
}
#[doc = "Reader of field `HVLVD1_EDGE_SEL`"]
pub type HVLVD1_EDGE_SEL_R = crate::R<u8, HVLVD1_EDGE_SEL_A>;
impl HVLVD1_EDGE_SEL_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> HVLVD1_EDGE_SEL_A {
match self.bits {
0 => HVLVD1_EDGE_SEL_A::DISABLE,
1 => HVLVD1_EDGE_SEL_A::RISING,
2 => HVLVD1_EDGE_SEL_A::FALLING,
3 => HVLVD1_EDGE_SEL_A::BOTH,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `DISABLE`"]
#[inline(always)]
pub fn is_disable(&self) -> bool {
*self == HVLVD1_EDGE_SEL_A::DISABLE
}
#[doc = "Checks if the value of the field is `RISING`"]
#[inline(always)]
pub fn is_rising(&self) -> bool {
*self == HVLVD1_EDGE_SEL_A::RISING
}
#[doc = "Checks if the value of the field is `FALLING`"]
#[inline(always)]
pub fn is_falling(&self) -> bool {
*self == HVLVD1_EDGE_SEL_A::FALLING
}
#[doc = "Checks if the value of the field is `BOTH`"]
#[inline(always)]
pub fn is_both(&self) -> bool {
*self == HVLVD1_EDGE_SEL_A::BOTH
}
}
#[doc = "Write proxy for field `HVLVD1_EDGE_SEL`"]
pub struct HVLVD1_EDGE_SEL_W<'a> {
w: &'a mut W,
}
impl<'a> HVLVD1_EDGE_SEL_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: HVLVD1_EDGE_SEL_A) -> &'a mut W {
{
self.bits(variant.into())
}
}
#[doc = "Disabled"]
#[inline(always)]
pub fn disable(self) -> &'a mut W {
self.variant(HVLVD1_EDGE_SEL_A::DISABLE)
}
#[doc = "Rising edge"]
#[inline(always)]
pub fn rising(self) -> &'a mut W {
self.variant(HVLVD1_EDGE_SEL_A::RISING)
}
#[doc = "Falling edge"]
#[inline(always)]
pub fn falling(self) -> &'a mut W {
self.variant(HVLVD1_EDGE_SEL_A::FALLING)
}
#[doc = "Both rising and falling edges"]
#[inline(always)]
pub fn both(self) -> &'a mut W {
self.variant(HVLVD1_EDGE_SEL_A::BOTH)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !0x03) | ((value as u32) & 0x03);
self.w
}
}
impl R {
#[doc = "Bits 0:1 - Sets which edge(s) will trigger an IRQ for HVLVD1"]
#[inline(always)]
pub fn hvlvd1_edge_sel(&self) -> HVLVD1_EDGE_SEL_R {
HVLVD1_EDGE_SEL_R::new((self.bits & 0x03) as u8)
}
}
impl W {
#[doc = "Bits 0:1 - Sets which edge(s) will trigger an IRQ for HVLVD1"]
#[inline(always)]
pub fn hvlvd1_edge_sel(&mut self) -> HVLVD1_EDGE_SEL_W {
HVLVD1_EDGE_SEL_W { w: self }
}
}
|
use crate::transactions::{NotFound, Registration};
#[derive(Debug, Clone)]
pub struct Dialog {
pub computed_id: String,
pub call_id: String,
pub from_tag: String,
pub to_tag: String,
pub flow: DialogFlow,
}
#[derive(Debug, Clone)]
pub enum DialogFlow {
Registration(Registration),
Invite(NotFound),
Publish(NotFound),
}
|
// file: max.rs
//
// Copyright 2015-2017 The RsGenetic Developers
//
// 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.
#![allow(deprecated)]
use pheno::{Fitness, Phenotype};
use super::*;
/// Selects best performing phenotypes from the population.
#[derive(Clone, Copy, Debug)]
#[deprecated(note="The `MaximizeSelector` has bad performance due to sorting. For better performance with potentially different results, \
use the `UnstableMaximizeSelector`.",
since="1.7.7")]
pub struct MaximizeSelector {
count: usize,
}
impl MaximizeSelector {
/// Create and return a maximizing selector.
///
/// Such a selector selects only the `count` best performing phenotypes
/// as parents.
///
/// * `count`: must be larger than zero, a multiple of two and less than the population size.
pub fn new(count: usize) -> MaximizeSelector {
MaximizeSelector { count: count }
}
}
impl<T, F> Selector<T, F> for MaximizeSelector
where
T: Phenotype<F>,
F: Fitness,
{
fn select<'a>(&self, population: &'a [T]) -> Result<Parents<&'a T>, String> {
if self.count == 0 || self.count % 2 != 0 || self.count * 2 >= population.len() {
return Err(format!(
"Invalid parameter `count`: {}. Should be larger than zero, a \
multiple of two and less than half the population size.",
self.count
));
}
let mut borrowed: Vec<&T> = population.iter().collect();
borrowed.sort_by(|x, y| y.fitness().cmp(&x.fitness()));
let mut index = 0;
let mut result: Parents<&T> = Vec::new();
while index < self.count {
result.push((borrowed[index], borrowed[index + 1]));
index += 2;
}
Ok(result)
}
}
#[cfg(test)]
mod tests {
use sim::select::*;
use pheno::*;
use test::Test;
#[test]
fn test_count_zero() {
let selector = MaximizeSelector::new(0);
let population: Vec<Test> = (0..100).map(|i| Test { f: i }).collect();
assert!(selector.select(&population).is_err());
}
#[test]
fn test_count_odd() {
let selector = MaximizeSelector::new(5);
let population: Vec<Test> = (0..100).map(|i| Test { f: i }).collect();
assert!(selector.select(&population).is_err());
}
#[test]
fn test_count_too_large() {
let selector = MaximizeSelector::new(100);
let population: Vec<Test> = (0..100).map(|i| Test { f: i }).collect();
assert!(selector.select(&population).is_err());
}
#[test]
fn test_result_size() {
let selector = MaximizeSelector::new(20);
let population: Vec<Test> = (0..100).map(|i| Test { f: i }).collect();
assert_eq!(20, selector.select(&population).unwrap().len() * 2);
}
#[test]
fn test_result_ok() {
let selector = MaximizeSelector::new(20);
let population: Vec<Test> = (0..100).map(|i| Test { f: i }).collect();
// The greatest fitness should be 99.
assert_eq!(selector.select(&population).unwrap()[0].0.fitness().f, 99);
}
#[test]
fn test_contains_best() {
let selector = MaximizeSelector::new(2);
let population: Vec<Test> = (0..100).map(|i| Test { f: i }).collect();
let parents = selector.select(&population).unwrap()[0];
assert_eq!(
parents.0.fitness(),
population
.iter()
.max_by_key(|x| x.fitness())
.unwrap()
.fitness()
);
}
}
|
use actix::Running;
use actix::StreamHandler;
use actix::{Actor, ActorContext, Addr, AsyncContext};
use actix_web_actors::ws;
use std::time::Instant;
use actix::prelude::*;
use crate::game_folder::game::Game;
use crate::participants::director_folder::director_structs::{
self, DirectorClientMsg, DirectorClientType, DirectorServerMsg, DirectorServerType,
};
use crate::participants::director_folder::director_to_game;
use crate::participants::participant_to_game;
use crate::game_folder::game_to_director;
use crate::game_folder::game_to_participant;
use super::director_structs::ParticipantType;
use serde_cbor::{from_slice, to_vec};
use crate::participants::heartbeat::{CLIENT_TERMINATE, CLIENT_TIMEOUT, HEARTBEAT_INTERVAL};
pub struct DirectorState {
pub is_responsive: bool,
pub addr: Option<Addr<Director>>,
pub id: String,
}
impl DirectorState {
pub fn new(id: String) -> DirectorState {
DirectorState {
is_responsive: true,
addr: None,
id,
}
}
}
/// Define HTTP actor
pub struct Director {
pub name: String,
pub game_id: String,
pub game_addr: Addr<Game>,
hb: Instant,
is_unresponsive: bool,
}
impl Actor for Director {
type Context = ws::WebsocketContext<Self>;
//* giving the game the address
fn started(&mut self, ctx: &mut Self::Context) {
self.game_addr
.do_send(director_to_game::RegisterAddressGetInfo {
name: self.name.clone(),
addr: ctx.address(),
});
self.hb(ctx);
}
fn stopping(&mut self, ctx: &mut Self::Context) -> Running {
println!(
"Stopping a director actor: {} and {}",
self.game_id, self.name
);
self.game_addr.do_send(participant_to_game::Disconnected {
name: self.name.clone(),
participant_type: "director".to_owned(),
});
ctx.terminate();
Running::Stop
}
}
impl Director {
pub fn new(name: String, game_id: String, game_addr: Addr<Game>) -> Director {
Director {
name,
game_id,
game_addr,
hb: Instant::now(),
is_unresponsive: false,
}
}
fn hb(&self, ctx: &mut ws::WebsocketContext<Self>) {
ctx.run_interval(HEARTBEAT_INTERVAL, |act, ctx| {
// * check client heartbeats
if Instant::now().duration_since(act.hb) > CLIENT_TIMEOUT {
// * heartbeat timed out
// * notify game
act.game_addr.do_send(participant_to_game::Unresponsive {
name: act.name.clone(),
participant_type: "director".to_owned(),
});
if Instant::now().duration_since(act.hb) > CLIENT_TERMINATE {
ctx.binary(
to_vec(&DirectorServerMsg {
msg_type: DirectorServerType::ServerKicked,
})
.unwrap(),
);
act.game_addr.do_send(participant_to_game::Disconnected {
name: act.name.clone(),
participant_type: "director".to_owned(),
});
ctx.stop();
}
act.is_unresponsive = true;
}
let ping = to_vec(&DirectorServerMsg {
msg_type: DirectorServerType::Ping,
})
.unwrap();
ctx.binary(ping);
});
}
fn reset_hb(&mut self) {
self.hb = Instant::now();
if self.is_unresponsive {
self.game_addr.do_send(participant_to_game::Responsive {
name: self.name.clone(),
participant_type: "director".to_string(),
});
self.is_unresponsive = false;
}
}
}
/// Handler for ws::Message message
impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for Director {
fn handle(&mut self, msg: Result<ws::Message, ws::ProtocolError>, _ctx: &mut Self::Context) {
if let Ok(ws::Message::Binary(bin)) = msg {
if let Ok(message) = from_slice::<DirectorClientMsg>(&bin.to_vec()) {
match message.msg_type {
DirectorClientType::EndGame => {
self.game_addr.do_send(director_to_game::EndGame {});
}
DirectorClientType::OpenGame => {
self.game_addr.do_send(director_to_game::OpenGame {});
}
DirectorClientType::CloseGame => {
self.game_addr.do_send(director_to_game::CloseGame {});
}
DirectorClientType::Pong => {}
DirectorClientType::Kick(target) => {
self.game_addr
.do_send(director_to_game::KickParticipant { name: target });
}
DirectorClientType::NewOffsets(offsets) => {
let offsets = offsets;
self.game_addr.do_send(director_to_game::SetOffsets {
subsidies: offsets.subsidies,
supply_shock: offsets.supply_shock,
trending: offsets.trending,
})
}
DirectorClientType::NextTurn => {
self.game_addr.do_send(director_to_game::ForceTurn {});
}
}
} else {
println!("Invalid structure received");
}
self.reset_hb();
}
}
}
impl Handler<game_to_director::Info> for Director {
type Result = ();
fn handle(&mut self, msg: game_to_director::Info, ctx: &mut Self::Context) -> Self::Result {
ctx.binary(
to_vec(&DirectorServerMsg {
msg_type: DirectorServerType::Info(msg.info),
})
.unwrap(),
)
}
}
impl Handler<game_to_director::Unresponsive> for Director {
type Result = ();
fn handle(
&mut self,
msg: game_to_director::Unresponsive,
ctx: &mut Self::Context,
) -> Self::Result {
ctx.binary(
to_vec(&DirectorServerMsg {
msg_type: DirectorServerType::UnresponsivePlayer(msg.name, msg.participant_type),
})
.unwrap(),
);
}
}
impl Handler<game_to_director::Disconnected> for Director {
type Result = ();
fn handle(
&mut self,
msg: game_to_director::Disconnected,
ctx: &mut Self::Context,
) -> Self::Result {
ctx.binary(
to_vec(&DirectorServerMsg {
msg_type: DirectorServerType::DisconnectedPlayer(msg.name, msg.participant_type),
})
.unwrap(),
);
}
}
impl Handler<game_to_director::Connected> for Director {
type Result = ();
fn handle(
&mut self,
msg: game_to_director::Connected,
ctx: &mut Self::Context,
) -> Self::Result {
ctx.binary(
to_vec(&DirectorServerMsg {
msg_type: DirectorServerType::ConnectedPlayer(msg.name, msg.participant_type),
})
.unwrap(),
);
}
}
impl Handler<game_to_director::TurnTaken> for Director {
type Result = ();
fn handle(
&mut self,
msg: game_to_director::TurnTaken,
ctx: &mut Self::Context,
) -> Self::Result {
ctx.binary(
to_vec(&DirectorServerMsg {
msg_type: DirectorServerType::TurnTaken(msg.name, msg.participant_type),
})
.unwrap(),
);
}
}
impl Handler<game_to_director::NewParticipant> for Director {
type Result = ();
fn handle(
&mut self,
msg: game_to_director::NewParticipant,
ctx: &mut Self::Context,
) -> Self::Result {
match msg.participant_type {
ParticipantType::Director => ctx.binary(
to_vec(&DirectorServerMsg {
msg_type: DirectorServerType::NewDirector(msg.id, msg.name),
})
.unwrap(),
),
ParticipantType::Producer => ctx.binary(
to_vec(&DirectorServerMsg {
msg_type: DirectorServerType::NewProducer(msg.id, msg.name),
})
.unwrap(),
),
ParticipantType::Consumer => ctx.binary(
to_vec(&DirectorServerMsg {
msg_type: DirectorServerType::NewConsumer(msg.id, msg.name),
})
.unwrap(),
),
ParticipantType::Viewer => ctx.binary(
to_vec(&DirectorServerMsg {
msg_type: DirectorServerType::NewViewer(msg.id, msg.name),
})
.unwrap(),
),
}
}
}
impl Handler<game_to_director::KickedParticipant> for Director {
type Result = ();
fn handle(
&mut self,
msg: game_to_director::KickedParticipant,
ctx: &mut Self::Context,
) -> Self::Result {
ctx.binary(
to_vec(&DirectorServerMsg {
msg_type: DirectorServerType::ParticipantKicked(msg.name),
})
.unwrap(),
);
}
}
impl Handler<game_to_director::GameOpened> for Director {
type Result = ();
fn handle(
&mut self,
_msg: game_to_director::GameOpened,
ctx: &mut Self::Context,
) -> Self::Result {
ctx.binary(
to_vec(&DirectorServerMsg {
msg_type: DirectorServerType::GameOpened,
})
.unwrap(),
);
}
}
impl Handler<game_to_director::GameClosed> for Director {
type Result = ();
fn handle(
&mut self,
_msg: game_to_director::GameClosed,
ctx: &mut Self::Context,
) -> Self::Result {
ctx.binary(
to_vec(&DirectorServerMsg {
msg_type: DirectorServerType::GameClosed,
})
.unwrap(),
);
}
}
impl Handler<game_to_director::Winners> for Director {
type Result = ();
fn handle(&mut self, msg: game_to_director::Winners, ctx: &mut Self::Context) -> Self::Result {
ctx.binary(
to_vec(&DirectorServerMsg {
msg_type: DirectorServerType::Winners(msg.array),
})
.unwrap(),
);
}
}
impl Handler<game_to_participant::EndedGame> for Director {
type Result = ();
fn handle(
&mut self,
_msg: game_to_participant::EndedGame,
ctx: &mut Self::Context,
) -> Self::Result {
ctx.binary(
to_vec(&DirectorServerMsg {
msg_type: DirectorServerType::GameEnded,
})
.unwrap(),
);
ctx.stop()
}
}
impl Handler<game_to_participant::NewOffsets> for Director {
type Result = ();
fn handle(&mut self, msg: game_to_participant::NewOffsets, ctx: &mut Self::Context) {
ctx.binary(
to_vec(&DirectorServerMsg {
msg_type: DirectorServerType::NewOffsets(director_structs::Offsets {
subsidies: msg.subsidies,
supply_shock: msg.supply_shock,
trending: msg.trending,
}),
})
.unwrap(),
);
}
}
impl Handler<game_to_participant::TurnAdvanced> for Director {
type Result = ();
fn handle(&mut self, _: game_to_participant::TurnAdvanced, ctx: &mut Self::Context) {
ctx.binary(
to_vec(&DirectorServerMsg {
msg_type: DirectorServerType::TurnAdvanced,
})
.unwrap(),
);
}
}
impl Handler<game_to_participant::Kicked> for Director {
type Result = ();
fn handle(
&mut self,
_msg: game_to_participant::Kicked,
ctx: &mut Self::Context,
) -> Self::Result {
ctx.binary(
to_vec(&DirectorServerMsg {
msg_type: DirectorServerType::ServerKicked,
})
.unwrap(),
);
ctx.terminate();
}
}
|
#![no_std]
#![no_main]
#![feature(asm)]
#![feature(const_slice_len)]
#![feature(slice_patterns)]
#![feature(optin_builtin_traits)]
#![feature(core_intrinsics)]
extern crate alloc;
#[macro_use]
extern crate log;
extern crate uefi;
extern crate uefi_exts;
extern crate uefi_macros;
use alloc::fmt::format;
use core::fmt;
use core::convert::TryFrom;
use core::intrinsics::type_name;
use crate::alloc::vec::Vec;
use uefi_exts::BootServicesExt;
use uefi::prelude::*;
use uefi_services::init;
// XXX: Can't figure out how to import `Protocol` otherwise.
use uefi::proto::*;
use uefi::*;
// XXX: Requires removing `pub(crate)` in uefi-rs.
use uefi::data_types::{Guid, unsafe_guid, Identify};
// XXX: Work around `_fltused` being undefined:
// https://github.com/rust-lang/rust/issues/62785
#[used]
#[no_mangle]
pub static _fltused: i32 = 0;
pub const BLOCK_IO_PROTOCOL_REVISION2: u64 = 0x20001;
pub const BLOCK_IO_PROTOCOL_REVISION3: u64 = (2 << 16) | 31;
// XXX: Why doesn't uefi-rs use `repr` for `Protocol`s?
#[repr(C)]
#[unsafe_guid("964e5b21-6459-11d2-8e39-00a0c969723b")]
#[derive(Protocol)]
pub struct BlockIO<'boot> {
pub revision: u64,
pub media: &'boot BlockIOMedia,
pub reset: extern "win64" fn(
/* in */ this: &mut BlockIO,
/* in */ extended_verification: bool,
) -> Status,
pub read_blocks: extern "win64" fn(
/* in */ this: &mut BlockIO,
/* in */ media_id: u32,
/* in */ lba: LBA,
/* in */ buffer_size: usize, // bytes
/* out */ buffer: *mut u8,
) -> Status,
pub write_blocks: extern "win64" fn(
/* in */ this: &mut BlockIO,
/* in */ media_id: u32,
/* in */ lba: LBA,
/* in */ buffer_size: usize, // bytes
/* in */ buffer: *mut u8,
) -> Status,
pub flush_blocks: extern "win64" fn(
/* in */ this: &mut BlockIO,
) -> Status,
}
#[repr(C)]
pub struct BlockIOMedia {
pub media_id: u32,
pub removable_media: bool,
pub media_present: bool,
pub logical_partition: bool,
pub read_only: bool,
pub write_caching: bool,
pub block_size: u32,
pub io_align: u32,
pub last_block: LBA,
pub lowest_aligned_lba: LBA, // added in Revision 2
pub logical_blocks_per_physical_block: u32, // added in Revision 2
pub optimal_transfer_length_granularity: u32, // added in Revision 3
}
type LBA = u64;
// Data is stored after this structure, so this needs to be `packed`.
// XXX: `packed` can cause undefined behavior:
// https://github.com/rust-lang/rust/issues/27060
#[repr(C)]
#[repr(packed)]
#[unsafe_guid("09576e91-6d3f-11d2-8e39-00a0c969723b")]
#[derive(Protocol)]
pub struct DevicePath {
pub r#type: u8,
pub sub_type: u8,
pub length: [u8; 2],
}
impl DevicePath {
pub extern "C" fn len(&self) -> u16 {
(self.length[0] as u16) | ((self.length[1] as u16) << 8)
}
}
#[repr(C)]
#[unsafe_guid("8b843e20-8132-4852-90cc-551a4e4a7f1c")]
#[derive(Protocol)]
pub struct DevicePathToText {
pub convert_device_node_to_text: extern "win64" fn(
/* in */ device_node: *const DevicePath,
/* in */ display_only: bool,
/* in */ allow_shortcuts: bool,
) -> *mut Char16,
pub convert_device_path_to_text: extern "win64" fn(
/* in */ device_path: *const DevicePath,
/* in */ display_only: bool,
/* in */ allow_shortcuts: bool,
) -> *mut Char16,
}
// XXX: `Display` is not defined for `CStr16`.
struct DCStr16(*mut Char16);
impl fmt::Display for DCStr16 {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let s = unsafe { CStr16::from_ptr(self.0) };
for x in s.to_u16_slice() {
if let Ok(c) = Char16::try_from(*x) {
write!(fmt, "{}", c)?;
}
}
Ok(())
}
}
pub extern "C" fn find_handles<Protocol>(
boot_services: &BootServices,
) -> Vec<Handle>
where Protocol: uefi::proto::Protocol
{
let type_name = type_name::<Protocol>();
let err = format(format_args!(
"Failed to retrieve list of {} handles", type_name));
boot_services
.find_handles::<Protocol>()
.expect_success(err.as_str())
}
pub extern "C" fn handle_protocol<'a, Protocol>(
boot_services: &BootServices,
handle: &'a Handle,
) -> &'a Protocol
where Protocol: uefi::proto::Protocol
{
let type_name = type_name::<Protocol>();
let err = format(format_args!("Failed to handle {} protocol", type_name));
let protocol = boot_services
.handle_protocol::<Protocol>(*handle)
.expect_success(err.as_str());
unsafe { &mut *protocol.get() }
}
#[no_mangle]
pub extern "C" fn efi_main(
_image: uefi::Handle,
system_table: SystemTable<Boot>,
) -> Status {
// Initialize utilities (such as logging and memory allocation).
init(&system_table).expect_success("Failed to initialize utilities");
let boot_services = system_table.boot_services();
// DevicePathToText.
let dptt_handles: Vec<Handle> =
find_handles::<DevicePathToText>(boot_services);
assert_eq!(dptt_handles.len(), 1);
let dptt_handle = dptt_handles[0];
let device_path_to_text =
handle_protocol::<DevicePathToText>(boot_services, &dptt_handle);
// BlockIO.
let io_handles: Vec<Handle> = find_handles::<BlockIO>(boot_services);
for io_handle in &io_handles {
let block_io = handle_protocol::<BlockIO>(boot_services, io_handle);
let device_path = handle_protocol::<DevicePath>(boot_services, io_handle);
let text =
(device_path_to_text.convert_device_path_to_text)(
device_path, true, true);
if block_io.media.removable_media {
info!("removable: {}", DCStr16(text));
} else {
info!("non-removable: {}", DCStr16(text));
}
}
Status::SUCCESS
}
|
use num_bigint::BigUint;
use ropey::Rope;
use sp_ipld::Ipld;
use std::fmt;
use crate::{
ipld_error::IpldError,
literal::Literal,
term::Term,
yatima,
};
use core::convert::{
TryFrom,
TryInto,
};
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
pub enum TextOp {
Cons,
LenChars,
LenLines,
LenBytes,
Append,
Insert,
Remove,
Take,
Drop,
Eql,
Lte,
Lth,
Gte,
Gth,
Char,
Byte,
Line,
CharAtByte,
ByteAtChar,
LineAtByte,
LineAtChar,
LineStartChar,
LineStartByte,
ToBytes,
}
impl TextOp {
pub fn symbol(self) -> String {
match self {
Self::Cons => "cons".to_owned(),
Self::Append => "append".to_owned(),
Self::Insert => "insert".to_owned(),
Self::Remove => "remove".to_owned(),
Self::Take => "take".to_owned(),
Self::Drop => "drop".to_owned(),
Self::Eql => "eql".to_owned(),
Self::Lte => "lte".to_owned(),
Self::Lth => "lth".to_owned(),
Self::Gte => "gte".to_owned(),
Self::Gth => "gth".to_owned(),
Self::LenChars => "len_chars".to_owned(),
Self::LenBytes => "len_bytes".to_owned(),
Self::LenLines => "len_lines".to_owned(),
Self::Char => "char".to_owned(),
Self::Byte => "byte".to_owned(),
Self::Line => "line".to_owned(),
Self::CharAtByte => "char_at_byte".to_owned(),
Self::ByteAtChar => "byte_at_char".to_owned(),
Self::LineAtByte => "line_at_byte".to_owned(),
Self::LineAtChar => "line_at_char".to_owned(),
Self::LineStartByte => "line_start_byte".to_owned(),
Self::LineStartChar => "line_start_char".to_owned(),
Self::ToBytes => "to_bytes".to_owned(),
}
}
pub fn from_symbol(x: &str) -> Option<Self> {
match x {
"cons" => Some(Self::Cons),
"append" => Some(Self::Append),
"insert" => Some(Self::Insert),
"remove" => Some(Self::Remove),
"take" => Some(Self::Take),
"drop" => Some(Self::Drop),
"eql" => Some(Self::Eql),
"lte" => Some(Self::Lte),
"lth" => Some(Self::Lth),
"gte" => Some(Self::Gte),
"gth" => Some(Self::Gth),
"len_chars" => Some(Self::LenChars),
"len_bytes" => Some(Self::LenBytes),
"len_lines" => Some(Self::LenLines),
"char" => Some(Self::Char),
"byte" => Some(Self::Byte),
"line" => Some(Self::Line),
"char_at_byte" => Some(Self::CharAtByte),
"byte_at_char" => Some(Self::ByteAtChar),
"line_at_byte" => Some(Self::LineAtByte),
"line_at_char" => Some(Self::LineAtChar),
"line_start_byte" => Some(Self::LineStartByte),
"line_start_char" => Some(Self::LineStartChar),
"to_bytes" => Some(Self::ToBytes),
_ => None,
}
}
pub fn type_of(self) -> Term {
match self {
Self::Cons => yatima!("∀ #Char #Text -> #Text"),
Self::LenChars => yatima!("∀ #Text -> #Nat"),
Self::LenLines => yatima!("∀ #Text -> #Nat"),
Self::LenBytes => yatima!("∀ #Text -> #Nat"),
Self::Append => yatima!("∀ #Text #Text -> #Text"),
Self::Insert => yatima!("∀ #Nat #Text #Text -> #Text"),
Self::Remove => yatima!("∀ #Nat #Nat #Text -> #Text"),
Self::Take => yatima!("∀ #Nat #Text -> #Text"),
Self::Drop => yatima!("∀ #Nat #Text -> #Text"),
Self::Eql => yatima!("∀ #Text #Text -> #Bool"),
Self::Lte => yatima!("∀ #Text #Text -> #Bool"),
Self::Lth => yatima!("∀ #Text #Text -> #Bool"),
Self::Gte => yatima!("∀ #Text #Text -> #Bool"),
Self::Gth => yatima!("∀ #Text #Text -> #Bool"),
Self::Char => yatima!("∀ #Nat #Text -> #Char"),
Self::Byte => yatima!("∀ #Nat #Text -> #U8"),
Self::Line => yatima!("∀ #Nat #Text -> #Text"),
Self::CharAtByte => yatima!("∀ #Nat #Text -> #Nat"),
Self::ByteAtChar => yatima!("∀ #Nat #Text -> #Nat"),
Self::LineAtByte => yatima!("∀ #Nat #Text -> #Nat"),
Self::LineAtChar => yatima!("∀ #Nat #Text -> #Nat"),
Self::LineStartChar => yatima!("∀ #Nat #Text -> #Nat"),
Self::LineStartByte => yatima!("∀ #Nat #Text -> #Nat"),
Self::ToBytes => yatima!("∀ #Text -> #Bytes"),
}
}
pub fn to_ipld(self) -> Ipld {
match self {
Self::Cons => Ipld::Integer(0),
Self::LenChars => Ipld::Integer(1),
Self::LenLines => Ipld::Integer(2),
Self::LenBytes => Ipld::Integer(3),
Self::Append => Ipld::Integer(4),
Self::Insert => Ipld::Integer(5),
Self::Remove => Ipld::Integer(6),
Self::Take => Ipld::Integer(7),
Self::Drop => Ipld::Integer(8),
Self::Eql => Ipld::Integer(9),
Self::Lte => Ipld::Integer(10),
Self::Lth => Ipld::Integer(11),
Self::Gte => Ipld::Integer(12),
Self::Gth => Ipld::Integer(13),
Self::Char => Ipld::Integer(14),
Self::Byte => Ipld::Integer(15),
Self::Line => Ipld::Integer(16),
Self::CharAtByte => Ipld::Integer(17),
Self::ByteAtChar => Ipld::Integer(18),
Self::LineAtByte => Ipld::Integer(19),
Self::LineAtChar => Ipld::Integer(20),
Self::LineStartChar => Ipld::Integer(21),
Self::LineStartByte => Ipld::Integer(22),
Self::ToBytes => Ipld::Integer(23),
}
}
pub fn from_ipld(ipld: &Ipld) -> Result<Self, IpldError> {
match ipld {
Ipld::Integer(0) => Ok(Self::Cons),
Ipld::Integer(1) => Ok(Self::LenChars),
Ipld::Integer(2) => Ok(Self::LenLines),
Ipld::Integer(3) => Ok(Self::LenBytes),
Ipld::Integer(4) => Ok(Self::Append),
Ipld::Integer(5) => Ok(Self::Insert),
Ipld::Integer(6) => Ok(Self::Remove),
Ipld::Integer(7) => Ok(Self::Take),
Ipld::Integer(8) => Ok(Self::Drop),
Ipld::Integer(9) => Ok(Self::Eql),
Ipld::Integer(10) => Ok(Self::Lte),
Ipld::Integer(11) => Ok(Self::Lth),
Ipld::Integer(12) => Ok(Self::Gte),
Ipld::Integer(13) => Ok(Self::Gth),
Ipld::Integer(14) => Ok(Self::Char),
Ipld::Integer(15) => Ok(Self::Byte),
Ipld::Integer(16) => Ok(Self::Line),
Ipld::Integer(17) => Ok(Self::CharAtByte),
Ipld::Integer(18) => Ok(Self::ByteAtChar),
Ipld::Integer(19) => Ok(Self::LineAtByte),
Ipld::Integer(20) => Ok(Self::LineAtChar),
Ipld::Integer(21) => Ok(Self::LineStartChar),
Ipld::Integer(22) => Ok(Self::LineStartByte),
Ipld::Integer(23) => Ok(Self::ToBytes),
xs => Err(IpldError::TextOp(xs.to_owned())),
}
}
pub fn arity(self) -> u64 {
match self {
Self::Cons => 2,
Self::LenChars => 1,
Self::LenLines => 1,
Self::LenBytes => 1,
Self::Append => 2,
Self::Insert => 3,
Self::Remove => 3,
Self::Take => 2,
Self::Drop => 2,
Self::Eql => 2,
Self::Lte => 2,
Self::Lth => 2,
Self::Gte => 2,
Self::Gth => 2,
Self::Char => 2,
Self::Byte => 2,
Self::Line => 2,
Self::CharAtByte => 2,
Self::ByteAtChar => 2,
Self::LineAtByte => 2,
Self::LineAtChar => 2,
Self::LineStartChar => 2,
Self::LineStartByte => 2,
Self::ToBytes => 1,
}
}
pub fn apply1(self, x: &Literal) -> Option<Literal> {
use Literal::*;
match (self, x) {
(Self::LenChars, Text(xs)) => Some(Nat(xs.len_chars().into())),
(Self::LenBytes, Text(xs)) => Some(Nat(xs.len_bytes().into())),
(Self::LenLines, Text(xs)) => Some(Nat(xs.len_lines().into())),
_ => None,
}
}
pub fn apply2(self, x: &Literal, y: &Literal) -> Option<Literal> {
use Literal::*;
match (self, x, y) {
(Self::Cons, Char(c), Text(cs)) => {
let mut cs = cs.clone();
cs.insert_char(0, *c);
Some(Text(cs))
}
(Self::Append, Text(xs), Text(ys)) => {
let mut xs = xs.clone();
xs.append(ys.clone());
Some(Text(xs))
}
(Self::Take, Nat(x), Text(xs)) => {
let (xs, _) = safe_split(x, xs.clone());
Some(Text(xs))
}
(Self::Drop, Nat(x), Text(xs)) => {
let (_, ys) = safe_split(x, xs.clone());
Some(Text(ys))
}
(Self::Eql, Text(xs), Text(ys)) => Some(Bool(xs == ys)),
(Self::Lte, Text(xs), Text(ys)) => Some(Bool(xs <= ys)),
(Self::Lth, Text(xs), Text(ys)) => Some(Bool(xs < ys)),
(Self::Gte, Text(xs), Text(ys)) => Some(Bool(xs >= ys)),
(Self::Gth, Text(xs), Text(ys)) => Some(Bool(xs > ys)),
(Self::Char, Nat(idx), Text(ys)) => {
let idx: usize = idx.clone().try_into().ok()?;
if idx < ys.len_chars() { Some(Char(ys.char(idx))) } else { None }
}
(Self::Byte, Nat(idx), Text(ys)) => {
let idx: usize = idx.clone().try_into().ok()?;
if idx < ys.len_chars() { Some(U8(ys.byte(idx))) } else { None }
}
(Self::Line, Nat(idx), Text(ys)) => {
let idx: usize = idx.clone().try_into().ok()?;
if idx < ys.len_chars() {
Some(Text(ys.line(idx).into()))
}
else {
None
}
}
(Self::CharAtByte, Nat(idx), Text(ys)) => {
let idx: usize = idx.clone().try_into().ok()?;
if idx < ys.len_bytes() {
Some(Nat(ys.byte_to_char(idx).into()))
}
else {
None
}
}
(Self::ByteAtChar, Nat(idx), Text(ys)) => {
let idx: usize = idx.clone().try_into().ok()?;
if idx < ys.len_chars() {
Some(Nat(ys.char_to_byte(idx).into()))
}
else {
None
}
}
(Self::LineAtChar, Nat(idx), Text(ys)) => {
let idx: usize = idx.clone().try_into().ok()?;
if idx < ys.len_chars() {
Some(Nat(ys.char_to_line(idx).into()))
}
else {
None
}
}
(Self::LineAtByte, Nat(idx), Text(ys)) => {
let idx: usize = idx.clone().try_into().ok()?;
if idx < ys.len_bytes() {
Some(Nat(ys.byte_to_line(idx).into()))
}
else {
None
}
}
(Self::LineStartChar, Nat(idx), Text(ys)) => {
let idx: usize = idx.clone().try_into().ok()?;
if idx < ys.len_lines() {
Some(Nat(ys.line_to_char(idx).into()))
}
else {
None
}
}
(Self::LineStartByte, Nat(idx), Text(ys)) => {
let idx: usize = idx.clone().try_into().ok()?;
if idx < ys.len_lines() {
Some(Nat(ys.line_to_byte(idx).into()))
}
else {
None
}
}
_ => None,
}
}
pub fn apply3(
self,
x: &Literal,
y: &Literal,
z: &Literal,
) -> Option<Literal> {
use Literal::*;
match (self, x, y, z) {
(Self::Insert, Nat(x), Text(y), Text(xs)) => {
Some(Text(safe_insert(x, y.clone(), xs.clone())))
}
(Self::Remove, Nat(x), Nat(y), Text(xs)) => {
Some(Text(safe_remove(x, y, xs.clone())))
}
_ => None,
}
}
}
impl fmt::Display for TextOp {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.symbol())
}
}
pub fn safe_insert(idx: &BigUint, ys: Rope, mut xs: Rope) -> Rope {
let idx = usize::try_from(idx);
match idx {
Ok(idx) if idx <= xs.len_chars() => {
xs.insert(idx, &ys.to_string());
xs
}
_ => xs,
}
}
pub fn safe_remove(from: &BigUint, upto: &BigUint, mut xs: Rope) -> Rope {
let from = usize::try_from(from);
let upto = usize::try_from(upto);
let len = xs.len_chars();
match (from, upto) {
(Ok(from), Ok(upto)) if (from <= len) && (upto <= len) => {
xs.remove(from..upto);
xs
}
_ => xs,
}
}
pub fn safe_head(mut x: Rope) -> Option<(char, Rope)> {
if x.len_chars() == 0 {
None
}
else {
let tail = x.split_off(1);
Some((x.char(0), tail))
}
}
pub fn safe_split(idx: &BigUint, mut xs: Rope) -> (Rope, Rope) {
let idx = usize::try_from(idx);
match idx {
Ok(idx) if idx <= xs.len_chars() => {
let ys = xs.split_off(idx);
(xs, ys)
}
_ => (xs, Rope::from_str("")),
}
}
pub fn safe_line(idx: BigUint, xs: Rope) -> Rope {
if let Ok(i) = usize::try_from(idx) {
if i > xs.len_chars() { Rope::from_str("") } else { Rope::from(xs.line(i)) }
}
else {
Rope::from_str("")
}
}
#[cfg(test)]
pub mod tests {
use super::*;
use quickcheck::{
Arbitrary,
Gen,
};
use rand::Rng;
impl Arbitrary for TextOp {
fn arbitrary(_g: &mut Gen) -> Self {
let mut rng = rand::thread_rng();
let gen: u32 = rng.gen_range(0..11);
match gen {
0 => Self::Cons,
1 => Self::LenChars,
2 => Self::LenLines,
3 => Self::LenBytes,
4 => Self::Append,
5 => Self::Insert,
6 => Self::Remove,
7 => Self::Take,
8 => Self::Drop,
9 => Self::Eql,
10 => Self::Lte,
11 => Self::Lth,
12 => Self::Gte,
13 => Self::Gth,
14 => Self::Char,
15 => Self::Byte,
16 => Self::Line,
17 => Self::CharAtByte,
18 => Self::LineAtByte,
19 => Self::LineAtChar,
20 => Self::LineStartChar,
21 => Self::LineStartByte,
_ => Self::ToBytes,
}
}
}
#[quickcheck]
fn text_op_ipld(x: TextOp) -> bool {
match TextOp::from_ipld(&x.to_ipld()) {
Ok(y) => x == y,
_ => false,
}
}
#[test]
fn test_safe_head() {
let rope: Rope = Rope::from_str("foo");
let res = safe_head(rope);
assert_eq!(res, Some(('f', Rope::from_str("oo"))));
}
#[test]
fn test_safe_split() {
let rope: Rope = Rope::from_str("foo");
let res = safe_split(&0u64.into(), rope.clone());
assert_eq!(res, (Rope::from_str(""), Rope::from_str("foo")));
let res = safe_split(&1u64.into(), rope.clone());
assert_eq!(res, (Rope::from_str("f"), Rope::from_str("oo")));
let res = safe_split(&4u64.into(), rope.clone());
assert_eq!(res, (Rope::from_str("foo"), Rope::from_str("")));
let res = safe_split(&u128::MAX.into(), rope.clone());
assert_eq!(res, (Rope::from_str("foo"), Rope::from_str("")));
}
}
|
use clap::ArgMatches;
use colored::*;
use failure::Error;
use git2::{Repository, StatusEntry, StatusOptions, Statuses};
use regex::Regex;
use std::collections::{HashMap, HashSet};
use std::fs::File;
use std::io::prelude::*;
use std::io::{self, Error as IOError, Write};
use std::process::Command;
#[derive(Fail, Debug)]
#[fail(display = "Hooks failed: {}", _0)]
struct HookError(String);
#[derive(Fail, Debug)]
#[fail(display = "Hook '{}' failed with error '{}'", _0, _1)]
struct CommandError(String, IOError);
#[derive(Fail, Debug)]
#[fail(display = "Invalid hook yaml file '{}'", _0)]
struct YamlSerializeError(String);
const FILE_ARG: &str = "<filename>";
#[derive(Deserialize, Debug, Clone)]
struct HookCommand {
command: String,
#[serde(default)]
arguments: Vec<String>,
}
#[derive(Deserialize, Debug, Clone)]
struct Hook {
commands: Vec<HookCommand>,
regex: String,
#[serde(default)]
run_once: bool,
#[serde(default)]
description: Option<String>,
}
#[derive(Deserialize, Debug)]
struct Hooks {
#[serde(rename = "pre-commit")]
pre_commit: Option<HashMap<String, Hook>>,
}
impl Hooks {
fn get(&self, hook_type: &str) -> Option<HashMap<String, Hook>> {
match hook_type {
"pre-commit" => self.pre_commit.clone(),
_ => {
println!("Unimplemented hook type of {}", hook_type);
None
}
}
}
}
fn load_hooks(matches: &ArgMatches) -> Result<Hooks, Error> {
let hooks_file_path = matches.values_of("hooks").unwrap().next().unwrap();
let mut hooks_file = String::new();
File::open(hooks_file_path)?.read_to_string(&mut hooks_file)?;
Ok(
serde_yaml::from_str(&hooks_file)
.map_err(|_| YamlSerializeError(hooks_file_path.to_string()))?,
)
}
fn get_staged_files(repo: &Repository) -> Result<Statuses, Error> {
let mut status_options = StatusOptions::new();
status_options.include_ignored(false);
status_options.include_unmodified(false);
let statuses = repo.statuses(Some(&mut status_options))?;
Ok(statuses)
}
fn create_command(h_command: &HookCommand, entry: &StatusEntry) -> Command {
let mut command = Command::new(&h_command.command);
for arg in &h_command.arguments {
if arg == FILE_ARG {
command.arg(entry.path().unwrap());
} else {
command.arg(arg);
}
}
command
}
fn print_hook_output(hook_name: &str, hook_failed: bool) {
if !hook_failed {
println!("{} {} : {}", "✓".green(), hook_name, "passed".green());
} else {
println!("{} {} : {}", "✗".red(), hook_name, "failed".red());
}
}
pub fn execute(matches: &ArgMatches) -> Result<(), Error> {
let skip_hooks: HashSet<_> = matches
.values_of("skip")
.map(|v| v.collect())
.unwrap_or_else(HashSet::new);
let hook_type = matches.values_of("hook_type").unwrap().next().unwrap();
let hook_config = load_hooks(matches)?;
let repo = Repository::init("./")?;
// SKIP Merge Commits.
if let Ok(_v) = repo.revparse("MERGE_HEAD") {
println!(
"{}",
"Skipping precommit because this is a merge commit".blue()
);
return Ok(());
}
let statuses = get_staged_files(&repo)?;
let mut hooks_failed = vec![];
if let Some(hooks) = hook_config.get(hook_type) {
for hook_name in hooks.keys().filter(|h| skip_hooks.get::<str>(h).is_none()) {
let hook = &hooks[hook_name];
let regex = Regex::new(&hook.regex).unwrap();
let mut hook_failed = false;
let mut hook_ran = false;
for entry in statuses
.iter()
.filter(|e| !(e.status().is_wt_deleted() || e.status().is_index_deleted()))
{
if hook.run_once & hook_ran {
break;
}
let file_path = entry.path().unwrap();
if regex.is_match(file_path) {
hook_ran = true;
for command in &hook.commands {
let output = create_command(&command, &entry)
.output()
.map_err(|e| CommandError(hook_name.clone(), e))?;
io::stdout().write_all(&output.stdout)?;
io::stderr().write_all(&output.stderr)?;
hook_failed = hook_failed || !output.status.success();
}
}
}
if hook_ran {
print_hook_output(hook_name, hook_failed);
}
if hook_failed {
hooks_failed.push(hook_name.clone());
}
}
}
if !hooks_failed.is_empty() {
Err(HookError(hooks_failed.join(",")))?
} else {
Ok(())
}
}
|
#[macro_use]
extern crate dotenv_codegen;
mod dbTest;
mod integrationTest {
use actix_http::HttpService;
use actix_http_test::{ TestServer, TestServerRuntime };
use actix_web::http::header;
use actix_web::{http, App, web};
use actix_http::httpmessage::HttpMessage;
use serde_json::json;
use std::str;
use std::time::Duration as std_duration;
use crate::dbTest::db_connection::establish_connection;
use std::cell::{ RefCell, RefMut };
use ::post::model::{ Post, NewPost, UpdatePost };
use uuid::Uuid;
#[test]
fn test() {
let srv = RefCell::new(TestServer::new(move ||
HttpService::new(
App::new()
.data(establish_connection())
.service(
web::resource("/")
.route(web::get()
.to(::post::handlers::index))
.route(web::post()
.to(::post::handlers::create))
)
.service(
web::resource("/{id}")
.route(web::get()
.to(::post::handlers::show))
.route(web::delete()
.to(::post::handlers::destroy))
.route(web::patch()
.to(::post::handlers::update))
)
)
));
clear_post();
let whisky = NewPost {
author: Uuid::new_v4(),
description: "whisky",
photo: ""
};
let rhum = NewPost {
author: Uuid::new_v4(),
description: "rhum",
photo: ""
};
let wine = NewPost {
author: Uuid::new_v4(),
description: "wine",
photo: ""
};
let whisky_db = create_a_post(srv.borrow_mut(), &whisky);
let rhum_db = create_a_post(srv.borrow_mut(), &rhum);
let wine_db = create_a_post(srv.borrow_mut(), &wine);
show_a_post(srv.borrow_mut(), &rhum_db.id, &rhum_db);
let updated_rhum = UpdatePost {
description: "rhum vide"
};
update_a_post(srv.borrow_mut(),
&rhum_db.id,
&updated_rhum);
destroy_a_post(srv.borrow_mut(),
&wine_db.id);
posts_index(srv.borrposts_indexow_mut(),
vec![whisky, updated_rhum]);
}
fn clear_post() {
use diesel::RunQueryDsl;
use ::mystore_lib::schema::products;
let connection = establish_connection();
let pg_pool = connection.get().unwrap();
diesel::delete(post::table).execute(&pg_pool).unwrap();
}
fn create_a_post(mut srv: RefMut<TestServerRuntime>,
post: &NewPost) -> Post {
let request = srv
.post("/")
.header(header::CONTENT_TYPE, "application/json")
.timeout(std_duration::from_secs(600));
let mut response =
srv
.block_on(request.send_body(json!(post).to_string()))
.unwrap();
assert!(response.status().is_success());
let bytes = srv.block_on(response.body()).unwrap();
let body = str::from_utf8(&bytes).unwrap();
serde_json::from_str(body).unwrap()
}
fn show_a_post(mut srv: RefMut<TestServerRuntime>,
id: Uuid,
expected_post: &Post) {
let request = srv
.get(format!("/{}", id));
let mut response = srv.block_on(request.send()).unwrap();
assert!(response.status().is_success());
assert_eq!(
response.headers().get(http::header::CONTENT_TYPE).unwrap(),
"application/json"
);
let bytes = srv.block_on(response.body()).unwrap();
let body = str::from_utf8(&bytes).unwrap();
let response_post: Post = serde_json::from_str(body).unwrap();
assert_eq!(&response_post, expected_post);
}
fn update_a_post(mut srv: RefMut<TestServerRuntime>,
id: Uuid,
changes_to_post: &UpdatePost) {
let request = srv
.request(http::Method::PUT, srv.url(&format!("/{}", id)))
.header(header::CONTENT_TYPE, "application/json")
.timeout(std_duration::from_secs(600));
let response =
srv
.block_on(request.send_body(json!(changes_to_post).to_string()))
.unwrap();
assert!(response.status().is_success());
}
fn destroy_a_post(mut srv: RefMut<TestServerRuntime>,
id: Uuid) {
let request = srv
.request(http::Method::DELETE, srv.url(&format!("/{}", id)))
.header(header::CONTENT_TYPE, "application/json")
.timeout(std_duration::from_secs(600));
let response =
srv
.block_on(request.send())
.unwrap();
assert!(response.status().is_success());
}
fn posts_index(mut srv: RefMut<TestServerRuntime>,
mut data_to_compare: Vec<NewPost>) {
let request = srv
.get("/")
let mut response = srv.block_on(request.send()).unwrap();
assert!(response.status().is_success());
assert_eq!(
response.headers().get(http::header::CONTENT_TYPE).unwrap(),
"application/json"
);
let bytes = srv.block_on(response.body()).unwrap();
let body = str::from_utf8(&bytes).unwrap();
let mut response_posts: Vec<Post> = serde_json::from_str(body).unwrap();
data_to_compare.sort_by_key(|post| post.description.clone());
response_posts.sort_by_key(|post| post.description.clone());
assert_eq!(data_to_compare, response_posts);
}
} |
extern crate cty;
#[allow(dead_code)]
mod bindings;
pub use self::bindings::{osKernelInitialize, osKernelStart, osThreadCreate, osPriority};
pub type RawOSArg = *const cty::c_void;
pub type RawOSArgMut = *mut cty::c_void;
pub type OsPThread = unsafe extern "C" fn(RawOSArg);
pub trait OptPtr<T> {
fn as_ptr<'a>(o: Option<T>) -> *const cty::c_void;
// fn as_mut_ptr<'a>(o: Option<&'a T>) -> *mut cty::c_void;
}
impl<T> OptPtr<T> for Option<T> {
fn as_ptr<'a>(o: Option<T>) -> *const cty::c_void {
match o {
Some(p) => &p as *const _ as *const cty::c_void,
None => 0 as *const cty::c_void,
}
}
}
pub struct OsThreadDef {
pthread: OsPThread,
priority: bindings::osPriority,
stack_size: u32,
name: &'static str,
}
impl OsThreadDef {
pub fn new(
thread_func: OsPThread,
prio: bindings::osPriority,
stack_size: u32,
name: &'static str,
) -> Self {
OsThreadDef {
pthread: thread_func,
priority: prio,
stack_size: stack_size,
name: name,
}
}
}
impl From<OsThreadDef> for bindings::osThreadDef_t {
fn from(t: OsThreadDef) -> Self {
bindings::osThreadDef_t {
pthread: Some(t.pthread),
tpriority: t.priority,
stacksize: t.stack_size,
name: t.name as *const _ as *const cty::c_char,
}
}
}
|
/*
* Fast discrete cosine transform algorithms (Rust)
*
* Copyright (c) 2020 Project Nayuki. (MIT License)
* https://www.nayuki.io/page/fast-discrete-cosine-transform-algorithms
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
* - The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* - The Software is provided "as is", without warranty of any kind, express or
* implied, including but not limited to the warranties of merchantability,
* fitness for a particular purpose and noninfringement. In no event shall the
* authors or copyright holders be liable for any claim, damages or other
* liability, whether in an action of contract, tort or otherwise, arising from,
* out of or in connection with the Software or the use or other dealings in the
* Software.
*/
use std;
/*
* Computes the scaled DCT type II on the given length-8 array in place.
* The inverse of this function is inverse_transform(), except for rounding errors.
*/
pub fn transform(vector: &mut [f64; 8]) {
// Algorithm by Arai, Agui, Nakajima, 1988. For details, see:
// https://web.stanford.edu/class/ee398a/handouts/lectures/07-TransformCoding.pdf#page=30
let v0 = vector[0] + vector[7];
let v1 = vector[1] + vector[6];
let v2 = vector[2] + vector[5];
let v3 = vector[3] + vector[4];
let v4 = vector[3] - vector[4];
let v5 = vector[2] - vector[5];
let v6 = vector[1] - vector[6];
let v7 = vector[0] - vector[7];
let v8 = v0 + v3;
let v9 = v1 + v2;
let v10 = v1 - v2;
let v11 = v0 - v3;
let v12 = -v4 - v5;
let v13 = (v5 + v6) * A[3];
let v14 = v6 + v7;
let v15 = v8 + v9;
let v16 = v8 - v9;
let v17 = (v10 + v11) * A[1];
let v18 = (v12 + v14) * A[5];
let v19 = -v12 * A[2] - v18;
let v20 = v14 * A[4] - v18;
let v21 = v17 + v11;
let v22 = v11 - v17;
let v23 = v13 + v7;
let v24 = v7 - v13;
let v25 = v19 + v24;
let v26 = v23 + v20;
let v27 = v23 - v20;
let v28 = v24 - v19;
vector[0] = S[0] * v15;
vector[1] = S[1] * v26;
vector[2] = S[2] * v21;
vector[3] = S[3] * v28;
vector[4] = S[4] * v16;
vector[5] = S[5] * v25;
vector[6] = S[6] * v22;
vector[7] = S[7] * v27;
}
/*
* Computes the scaled DCT type III on the given length-8 array in place.
* The inverse of this function is transform(), except for rounding errors.
*/
pub fn inverse_transform(vector: &mut [f64; 8]) {
// A straightforward inverse of the forward algorithm
let v15 = vector[0] / S[0];
let v26 = vector[1] / S[1];
let v21 = vector[2] / S[2];
let v28 = vector[3] / S[3];
let v16 = vector[4] / S[4];
let v25 = vector[5] / S[5];
let v22 = vector[6] / S[6];
let v27 = vector[7] / S[7];
let v19 = (v25 - v28) / 2.0;
let v20 = (v26 - v27) / 2.0;
let v23 = (v26 + v27) / 2.0;
let v24 = (v25 + v28) / 2.0;
let v7 = (v23 + v24) / 2.0;
let v11 = (v21 + v22) / 2.0;
let v13 = (v23 - v24) / 2.0;
let v17 = (v21 - v22) / 2.0;
let v8 = (v15 + v16) / 2.0;
let v9 = (v15 - v16) / 2.0;
let v18 = (v19 - v20) * A[5]; // Different from original
let v12 = (v19 * A[4] - v18) / (A[2] * A[5] - A[2] * A[4] - A[4] * A[5]);
let v14 = (v18 - v20 * A[2]) / (A[2] * A[5] - A[2] * A[4] - A[4] * A[5]);
let v6 = v14 - v7;
let v5 = v13 / A[3] - v6;
let v4 = -v5 - v12;
let v10 = v17 / A[1] - v11;
let v0 = (v8 + v11) / 2.0;
let v1 = (v9 + v10) / 2.0;
let v2 = (v9 - v10) / 2.0;
let v3 = (v8 - v11) / 2.0;
vector[0] = (v0 + v7) / 2.0;
vector[1] = (v1 + v6) / 2.0;
vector[2] = (v2 + v5) / 2.0;
vector[3] = (v3 + v4) / 2.0;
vector[4] = (v3 - v4) / 2.0;
vector[5] = (v2 - v5) / 2.0;
vector[6] = (v1 - v6) / 2.0;
vector[7] = (v0 - v7) / 2.0;
}
/*---- Tables of constants ----*/
const S: [f64; 8] = [
0.353553390593273762200422,
0.254897789552079584470970,
0.270598050073098492199862,
0.300672443467522640271861,
0.353553390593273762200422,
0.449988111568207852319255,
0.653281482438188263928322,
1.281457723870753089398043,
];
const A: [f64; 6] = [
std::f64::NAN,
0.707106781186547524400844,
0.541196100146196984399723,
0.707106781186547524400844,
1.306562964876376527856643,
0.382683432365089771728460,
];
|
fn main() {
let meshes = pgeom::obj::load("models/gun/Handgun_obj.obj").unwrap();
//let (v, i) = meshes[2].render_data(|v| v.uv);
meshes.iter().for_each(|m| {
println!("{:#?}", m.name);
});
//println!("{:#?}", v);
}
|
struct UnionFind {
par: Vec<usize>,
siz: Vec<usize>,
}
impl UnionFind {
fn new(n: usize) -> Self {
UnionFind {
par: (0..n).collect(),
siz: vec![1; n],
}
}
fn root(&mut self, x: usize) -> usize {
if self.par[x] == x {
x
} else {
self.par[x] = self.root(self.par[x]);
self.par[x]
}
}
fn unite(&mut self, x: usize, y: usize) {
let mut x = self.root(x);
let mut y = self.root(y);
if x == y {
return;
}
if self.siz[x] < self.siz[y] {
std::mem::swap(&mut x, &mut y);
}
self.siz[x] += self.siz[y];
self.par[y] = x;
}
fn same(&mut self, x: usize, y: usize) -> bool {
self.root(x) == self.root(y)
}
fn size(&mut self, x: usize) -> usize {
let root = self.root(x);
self.siz[root]
}
} |
#![allow(dead_code)]
pub fn options_test(x: f32, y: f32) {
let result = if y != 0.0 { Some(x/y) } else { None };
match result {
Some(value) => println!("result = {} !!", value),
None => println!("Never divide by zero !!!")
}
}
|
#[macro_use]
extern crate diesel;
#[macro_use]
extern crate serde;
pub mod db;
pub mod r#move; |
use std::{fs::File, io::{BufRead, BufReader}, collections::BTreeMap};
fn main() {
let file = File::open("inputs/input-10.txt").unwrap();
let lines: Vec<usize> = BufReader::new(file).lines().map(|l| l.unwrap().parse().unwrap()).collect();
part_one(&lines);
let mut cache: BTreeMap<usize, usize> = BTreeMap::new();
let mut sorted = lines.clone();
sorted.push(0);
sorted.push(3 + *lines.iter().max().unwrap());
sorted.sort();
println!("combinations {:?}", rec_find(0, &sorted, &mut cache));
}
fn rec_find(current: usize, graph: &Vec<usize>, cache: &mut BTreeMap<usize, usize>) -> usize {
if cache.contains_key(¤t) {
return *cache.get(¤t).unwrap();
};
if current == graph.len() - 1 {
return 1;
};
let mut result = 0;
for x in (current + 1)..=(current + 3) {
if x < graph.len() && graph[x] - graph[current] <= 3 {
result += rec_find(x, &graph, cache);
}
}
cache.insert(current, result);
return result
}
fn part_one(lines: &Vec<usize>) {
let mut ones = 0;
let mut _twos = 0;
let mut threes = 0;
let mut value = 0;
for _ in 0..=lines.len() {
let mut one = false;
let mut two = false;
let mut three = false;
if lines.contains(&(value + 1)) {
one = true;
}
if lines.contains(&(value + 2)) {
two = true;
}
if lines.contains(&(value + 3)) {
three = true;
}
if one && two && three {
value += 1;
ones += 1;
} else if one && two {
value += 1;
ones += 1;
} else if one && three {
value += 1;
ones += 1;
} else if two && three {
value += 2;
_twos += 1;
} else if one {
value += 1;
ones += 1;
} else if two {
value += 2;
_twos += 1;
} else if three {
value += 3;
threes += 1;
}
}
println!("ones {:?}", ones);
println!("threes {:?}", threes + 1);
}
|
use ability_scores::AbilityScore;
use ability_scores::Charisma;
use ability_scores::Constitution;
use ability_scores::Dexterity;
use ability_scores::Intelligence;
use ability_scores::Strength;
use ability_scores::Wisdom;
use ability_scores;
pub trait Character {
fn get_level(&self) -> &u8;
fn set_level(&mut self, u8) -> &mut Self where Self: Sized;
fn get_strength(&mut self) -> &mut AbilityScore;
fn get_dexterity(&mut self) -> &mut AbilityScore;
fn get_constitution(&mut self) -> &mut AbilityScore;
fn get_intelligence(&mut self) -> &mut AbilityScore;
fn get_wisdom(&mut self) -> &mut AbilityScore;
fn get_charisma(&mut self) -> &mut AbilityScore;
}
pub struct Humanoid {
level: u8,
strength: ability_scores::Strength,
dexterity: ability_scores::Dexterity,
constitution: ability_scores::Constitution,
intelligence: ability_scores::Intelligence,
wisdom: ability_scores::Wisdom,
charisma: ability_scores::Charisma,
}
impl Humanoid {
pub fn new() -> Humanoid {
Humanoid {
level: 1,
strength: Strength::default(),
dexterity: Dexterity::default(),
constitution: Constitution::default(),
intelligence: Intelligence::default(),
wisdom: Wisdom::default(),
charisma: Charisma::default(),
}
}
}
impl Character for Humanoid {
/// Returns this character's level.
/// Expected return values are 1-20 (inclusive).
fn get_level(&self) -> &u8 {
return &self.level;
}
/// Sets this character's level.
/// Expected values are 1-20 (inclusive).
fn set_level(&mut self, level: u8) -> &mut Humanoid {
self.level = level;
return self;
}
/// Returns this character's Strength ability score.
fn get_strength(&mut self) -> &mut AbilityScore {
&mut self.strength
}
/// Returns this character's Dexterity ability score.
fn get_dexterity(&mut self) -> &mut AbilityScore {
&mut self.dexterity
}
/// Returns this character's Constitution ability score.
fn get_constitution(&mut self) -> &mut AbilityScore {
&mut self.constitution
}
/// Returns this character's Intelligence ability score.
fn get_intelligence(&mut self) -> &mut AbilityScore {
&mut self.intelligence
}
/// Returns this character's Wisdom ability score.
fn get_wisdom(&mut self) -> &mut AbilityScore {
&mut self.wisdom
}
/// Returns this character's Charisma ability score.
fn get_charisma(&mut self) -> &mut AbilityScore {
&mut self.charisma
}
} |
use bytes::{Buf, BufMut};
use codec::{BufLen, Codec, VarLen};
use {QuicError, QuicResult};
// On the wire:
// len: VarLen
// ptype: u8
// flags: u8
// payload: [u8]
#[derive(Debug, PartialEq)]
enum HttpFrame {
Settings(SettingsFrame),
}
impl Codec for HttpFrame {
fn encode<T: BufMut>(&self, buf: &mut T) {
match self {
HttpFrame::Settings(f) => {
f.len().encode(buf);
buf.put_u8(0x4);
f.encode(buf);
}
}
}
fn decode<T: Buf>(buf: &mut T) -> QuicResult<Self> {
let len = VarLen::decode(buf)?.0 as usize;
match buf.get_u8() {
0x4 => Ok(HttpFrame::Settings(SettingsFrame::decode(
&mut buf.take(1 + len),
)?)),
v => Err(QuicError::DecodeError(format!(
"unsupported HTTP frame type {}",
v
))),
}
}
}
#[derive(Debug, PartialEq)]
struct SettingsFrame(Settings);
impl Codec for SettingsFrame {
fn encode<T: BufMut>(&self, buf: &mut T) {
buf.put_u8(0);
buf.put_u16_be(0x1);
let encoded = VarLen(u64::from(self.0.header_table_size));
let encoded_len = encoded.buf_len();
debug_assert!(encoded_len < 64);
VarLen(encoded_len as u64).encode(buf);
encoded.encode(buf);
buf.put_u16_be(0x6);
let encoded = VarLen(u64::from(self.0.max_header_list_size));
let encoded_len = encoded.buf_len();
debug_assert!(encoded_len < 64);
VarLen(encoded_len as u64).encode(buf);
encoded.encode(buf);
}
fn decode<T: Buf>(buf: &mut T) -> QuicResult<SettingsFrame> {
if buf.get_u8() != 0 {
return Err(QuicError::DecodeError("unsupported flags".into()));
}
let mut settings = Settings::default();
while buf.has_remaining() {
let tag = buf.get_u16_be();
if tag != 0x1 && tag != 0x6 {
return Err(QuicError::DecodeError("unsupported tag".into()));
}
VarLen::decode(buf)?;
let val = VarLen::decode(buf)?;
if tag == 0x1 {
settings.header_table_size = val.0 as u32;
} else if tag == 0x6 {
settings.max_header_list_size = val.0 as u32;
}
}
Ok(SettingsFrame(settings))
}
}
impl FrameHeader for SettingsFrame {
fn len(&self) -> VarLen {
VarLen(
(6 + VarLen(u64::from(self.0.header_table_size)).buf_len()
+ VarLen(u64::from(self.0.max_header_list_size)).buf_len()) as u64,
)
}
fn flags(&self) -> u8 {
0
}
fn ftype(&self) -> u8 {
0x4
}
}
impl<T> BufLen for T
where
T: FrameHeader,
{
fn buf_len(&self) -> usize {
let len = self.len();
2 + VarLen(len.0).buf_len() + (len.0 as usize)
}
}
pub trait FrameHeader {
fn len(&self) -> VarLen;
fn flags(&self) -> u8;
fn ftype(&self) -> u8;
fn encode_header<T: BufMut>(&self, buf: &mut T) {
self.len().encode(buf);
buf.put_u8(self.ftype());
buf.put_u8(self.flags());
}
}
#[derive(Debug, PartialEq)]
pub struct Settings {
header_table_size: u32,
max_header_list_size: u32,
}
impl Default for Settings {
fn default() -> Settings {
Settings {
header_table_size: 65536,
max_header_list_size: 65536,
}
}
}
#[cfg(test)]
mod tests {
use codec::Codec;
use std::io::Cursor;
#[test]
fn test_settings_frame() {
let settings = super::Settings {
header_table_size: 131072,
max_header_list_size: 65536,
};
let frame = super::HttpFrame::Settings(super::SettingsFrame(settings));
let mut buf = Vec::new();
frame.encode(&mut buf);
assert_eq!(
&buf,
&[14, 4, 0, 0, 1, 4, 128, 2, 0, 0, 0, 6, 4, 128, 1, 0, 0]
);
let mut read = Cursor::new(&buf);
let decoded = super::HttpFrame::decode(&mut read).unwrap();
assert_eq!(decoded, frame);
}
}
|
/*
Copyright ⓒ 2016 rust-custom-derive contributors.
Licensed under the MIT license (see LICENSE or <http://opensource.org
/licenses/MIT>) or the Apache License, Version 2.0 (see LICENSE of
<http://www.apache.org/licenses/LICENSE-2.0>), at your option. All
files in the project carrying such notice may not be copied, modified,
or distributed except according to those terms.
*/
extern crate rustc_version;
use rustc_version::{version_meta, Channel};
fn main() {
// Set cfg flags depending on release channel
let channel = match version_meta().channel {
Channel::Stable => "stable",
Channel::Beta => "beta",
Channel::Nightly | Channel::Dev => "nightly",
};
println!("cargo:rustc-cfg=channel={:?}", channel);
}
|
use async_std;
use applications::web;
fn main() -> std::result::Result<(), std::io::Error> {
async_std::task::block_on(web::main())
}
|
/*
First, let’s take a look at the ownership rules. Keep these rules in mind
as we work through the examples that illustrate them:
Each value in Rust has a variable that’s called its owner.
There can only be one owner at a time.
When the owner goes out of scope, the value will be dropped.
*/
fn main() {
println!("Hello, world!");
// variable scope
// let one_s = "hello"; // non mutable
// let mut another_s = String::from("hello"); // mutable
// let x = 5;
// let y = x; // totally ok
let s1 = String::from("hello");
let s2 = s1; // s1 no longer available
println!("s2: {}", s2);
/*
declaring s1 creates 3 parts:
S1
name | value index value
ptr | address -> 0 h
len | 5 1 e
capacity | 5 2 l
length is how much memory (Bytes) the content of s1 is using (hello = 5 bytes)
capacity is the total amount of memory
doing let s2 = s1 is actually copying the ptr from s1 to s2 resulting in having
two vars pointing at the same address. What the compiler does is invalidates s1,
so it's no longer usable. Now the var s2 is valid.
*/
/*
the code below will make another table like above but with a different address, pointing
at a block which has the same values as s1
*/
let s3 = s2.clone();
println!("s3: {}", s3);
// === OWNERSHIP and FUNCTIONS === //
let s = String::from("hello"); // s comes into scope
takes_ownership(s); // s's value move into the function...
// s is no longer valid
// println!("s after taken: {}", s); // s is no longer valid
let x = 5; // x comes into scope
makes_copy(x); // x moves into function, but i32 is Copy
// x still usable
println!("integer still usable: {}", 5);
let s1 = gives_ownership(); // moves return value into s1
println!("gives fn: {}", s1);
let s2 = String::from("hello"); // s2 comes into scope
let s3 = takes_and_gives_ownership(s2); // s2 moved into fn and gives it to s3
// s2 no longer valid
//println!("gave ownership: {}", s2); // s2 value was dropped
println!("took ownership: {}", s3);
// another take and give using tuple return //
let s1 = String::from("hello");
let (s2, len) = calculate_length(s1);
println!("length of {}, is {}", s2, len);
// println!("{}", s1); // no longer valid
}
fn takes_ownership(some_string: String) {
println!("takes fn: {}", some_string);
}
fn makes_copy(some_integer: i32) {
println!("copies fn: {}", some_integer);
}
fn gives_ownership() -> String {
let some_string = String::from("hello");
some_string // return value
}
fn takes_and_gives_ownership(a_string: String) -> String {
a_string // return
}
fn calculate_length(s: String) -> (String, usize) {
let lenght = s.len();
(s, lenght) // return a tuple
}
|
use std::env;
use std::process;
extern crate log_highlight;
use log_highlight::config::Config;
use log_highlight::highlighter::{Highlighter};
use log_highlight::rule::Rules;
fn main() {
// NOTE: 戻り値がある場合はunwrap_or_else
let config = Config::new(env::args()).unwrap_or_else(|err| {
if ! err.to_string().is_empty() {
eprintln!("error: create Config: {}", err);
}
usage();
process::exit(1);
});
if config.show_help {
usage();
process::exit(0);
}
if config.show_rules {
Rules::show();
process::exit(0);
}
let highlighter = Highlighter::new(config.rules).unwrap_or_else(|err| {
eprintln!("error: create Highlighter: {}", err);
process::exit(1);
});
// NOTE: 戻り値がない場合は if let Err(e)
if let Err(e) = highlighter.highlight(config.files) {
eprintln!("error: highlight failed: {}", e);
process::exit(1);
}
}
fn usage() {
println!("Usage: {} [OPTION]... [FILE]...", env!("CARGO_PKG_NAME"));
println!("highlight each FILE to standard output based on rules.");
println!("With no FILE, or when FILE is -, read standard input.");
println!("");
println!(" -c, --config=FILE load highlight rules from FILE");
}
|
use std::cell::Cell;
use nalgebra::Vector2;
#[derive (Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct SerialNumber (pub u64);
impl Default for SerialNumber {
fn default()->Self {
thread_local! {static NEXT_SERIAL_NUMBER: Cell<u64> = Cell::new (0);}
NEXT_SERIAL_NUMBER.with (| next | {
let this = next.get();
next.set (this + 1);
SerialNumber (this)
})
}
}
pub fn min (first: f64, second: f64)->f64 {if first < second {first} else {second}}
pub fn max (first: f64, second: f64)->f64 {if first > second {first} else {second}}
pub fn abs (first: f64)->f64 {if first < 0.0 {-first} else {first}}
pub type Vector = Vector2 <f64>;
|
extern crate simple_excel_writer as excel;
use excel::*;
fn main() {
let mut wb = Workbook::create("./tmp/b.xlsx");
let mut sheet = wb.create_sheet("SheetName");
// set column width
sheet.add_column(Column { width: 30.0 });
sheet.add_column(Column { width: 30.0 });
sheet.add_column(Column { width: 80.0 });
sheet.add_column(Column { width: 60.0 });
wb.write_sheet(&mut sheet, |sheet_writer| {
let sw = sheet_writer;
sw.append_row(row!["Name", "Title", "Success", "XML Remark"])?;
sw.append_row(row![
"Amy",
(),
true,
"<xml><tag>\"Hello\" & 'World'</tag></xml>"
])?;
sw.append_blank_rows(2);
sw.append_row(row!["Tony", blank!(720), "retired"]) // A5: Tony , AAT5 : retired
})
.expect("write excel error!");
let mut sheet = wb.create_sheet("Sheet2");
wb.write_sheet(&mut sheet, |sheet_writer| {
let sw = sheet_writer;
sw.append_row(row!["Name", "Title", "Success", "Remark"])?;
sw.append_row(row!["Amy", "Manager", true])?;
sw.append_row(row![1.0, 2.0, 3.0, 4.1, "=sum(a3:d3)"])
})
.expect("write excel error!");
let euro_fmt_idx = wb.add_cust_number_format("\"€\"#,##0.00".to_string());
let weight_fmt_idx = wb.add_cust_number_format("#,##0.0\" KG\"".to_string());
let mut sheet_num_fmt = wb.create_sheet("SheetNumFormatted");
sheet_num_fmt.add_column(Column { width: 30.0 });
sheet_num_fmt.add_column(Column { width: 30.0 });
wb.write_sheet(&mut sheet_num_fmt, |sheet_writer| {
let sw = sheet_writer;
sw.append_row(row!["Weight", "Price"])?;
sw.append_row(row![(700.5, weight_fmt_idx), (12045.99, euro_fmt_idx)])?;
sw.append_row(row![(1525.0, weight_fmt_idx), (25999.00, euro_fmt_idx)])
}).expect("write excel error!");
wb.close().expect("close excel error!");
}
|
use crate::error::HttpEndpointError;
use crate::sink::{Sink, SinkError, SinkTarget};
use actix_web::HttpResponse;
use anyhow::Context;
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use cloudevents::{event::Data, Event, EventBuilder, EventBuilderV10};
use drogue_client::registry;
use drogue_cloud_service_api::EXT_INSTANCE;
use drogue_cloud_service_common::{Id, IdInjector};
use percent_encoding::{utf8_percent_encode, NON_ALPHANUMERIC};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::{collections::HashMap, future::Future};
const DEFAULT_TYPE_EVENT: &str = "io.drogue.event.v1";
#[derive(Clone, Debug)]
pub struct Publish<'a> {
pub application: &'a registry::v1::Application,
pub device_id: String,
pub channel: String,
pub options: PublishOptions,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct PublishOptions {
pub time: Option<DateTime<Utc>>,
pub topic: Option<String>,
pub data_schema: Option<String>,
pub content_type: Option<String>,
pub extensions: HashMap<String, String>,
}
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
pub enum PublishOutcome {
/// Message accepted
Accepted,
/// Invalid message format
Rejected,
/// Input queue full
QueueFull,
}
/// A sender delivering events upstream, from the cloud to the device.
#[derive(Debug, Clone)]
pub struct UpstreamSender<S>
where
S: Sink,
{
sink: S,
instance: String,
}
impl<S> UpstreamSender<S>
where
S: Sink,
{
pub fn new(sink: S) -> anyhow::Result<Self> {
let instance = std::env::var("INSTANCE").context("Missing variable 'INSTANCE'")?;
Ok(Self { sink, instance })
}
}
/// A sender delivering events downstream, from the device to the cloud.
#[derive(Debug, Clone)]
pub struct DownstreamSender<S>
where
S: Sink,
{
sink: S,
instance: String,
}
impl<S> DownstreamSender<S>
where
S: Sink,
{
pub fn new(sink: S) -> anyhow::Result<Self> {
let instance = std::env::var("INSTANCE").context("Missing variable 'INSTANCE'")?;
Ok(Self { sink, instance })
}
}
#[async_trait]
impl<S> Publisher<S> for DownstreamSender<S>
where
S: Sink,
{
fn instance(&self) -> String {
self.instance.clone()
}
async fn send(
&self,
app: ®istry::v1::Application,
event: Event,
) -> Result<PublishOutcome, SinkError<S::Error>> {
self.sink.publish(SinkTarget::Events(app), event).await
}
}
#[async_trait]
impl<S> Publisher<S> for UpstreamSender<S>
where
S: Sink,
{
fn instance(&self) -> String {
self.instance.clone()
}
async fn send(
&self,
app: ®istry::v1::Application,
event: Event,
) -> Result<PublishOutcome, SinkError<S::Error>> {
self.sink.publish(SinkTarget::Commands(app), event).await
}
}
#[async_trait]
pub trait Publisher<S>
where
S: Sink,
{
fn instance(&self) -> String;
async fn send(
&self,
app: ®istry::v1::Application,
event: Event,
) -> Result<PublishOutcome, SinkError<S::Error>>;
#[allow(clippy::needless_lifetimes)]
async fn publish<'a, B>(
&self,
publish: Publish<'a>,
body: B,
) -> Result<PublishOutcome, SinkError<S::Error>>
where
B: AsRef<[u8]> + Send + Sync,
{
let app_id = publish.application.metadata.name.clone();
let app_enc = utf8_percent_encode(&app_id, NON_ALPHANUMERIC);
let device_enc = utf8_percent_encode(&publish.device_id, NON_ALPHANUMERIC);
let source = format!("{}/{}", app_enc, device_enc);
let mut event = EventBuilderV10::new()
.id(uuid::Uuid::new_v4().to_string())
.ty(DEFAULT_TYPE_EVENT)
// we need an "absolute" URL for the moment: until 0.4 is released
// see: https://github.com/cloudevents/sdk-rust/issues/106
.source(format!("drogue://{}", source))
.inject(Id::new(app_id, publish.device_id))
.subject(&publish.channel)
.time(Utc::now());
event = event.extension(crate::EXT_PARTITIONKEY, source);
event = event.extension(EXT_INSTANCE, self.instance());
if let Some(data_schema) = publish.options.data_schema {
event = event.extension("dataschema", data_schema);
}
for (k, v) in publish.options.extensions {
event = event.extension(&k, v);
}
log::debug!("Content-Type: {:?}", publish.options.content_type);
log::debug!("Payload size: {} bytes", body.as_ref().len());
let event = match publish.options.content_type {
// pass through content type
Some(t) => event.data(t, Vec::from(body.as_ref())),
// no content type, try JSON, then fall back to "bytes"
None => {
// try decoding as JSON
match serde_json::from_slice::<Value>(body.as_ref()) {
Ok(v) => event.data(mime::APPLICATION_JSON.to_string(), Data::Json(v)),
Err(_) => event.data(
mime::APPLICATION_OCTET_STREAM.to_string(),
Vec::from(body.as_ref()),
),
}
}
};
// build event
self.send(&publish.application, event.build()?).await
}
#[allow(clippy::needless_lifetimes)]
async fn publish_http<'a, B, H, F>(
&self,
publish: Publish<'a>,
body: B,
f: H,
) -> Result<HttpResponse, HttpEndpointError>
where
B: AsRef<[u8]> + Send + Sync,
H: FnOnce(PublishOutcome) -> F + Send + Sync,
F: Future<Output = Result<HttpResponse, HttpEndpointError>> + Send + Sync,
{
match self.publish(publish, body).await {
// ok
Ok(outcome) => f(outcome).await,
// internal error
Err(err) => Ok(HttpResponse::InternalServerError()
.content_type("text/plain")
.body(err.to_string())),
}
}
#[allow(clippy::needless_lifetimes)]
async fn publish_http_default<'a, B>(
&self,
publish: Publish<'a>,
body: B,
) -> Result<HttpResponse, HttpEndpointError>
where
B: AsRef<[u8]> + Send + Sync,
{
self.publish_http(publish, body, |outcome| async move {
match outcome {
PublishOutcome::Accepted => Ok(HttpResponse::Accepted().finish()),
PublishOutcome::Rejected => Ok(HttpResponse::NotAcceptable().finish()),
PublishOutcome::QueueFull => Ok(HttpResponse::ServiceUnavailable().finish()),
}
})
.await
}
}
|
use nmstate::NmstateError;
pub(crate) struct CliError {
pub(crate) msg: String,
}
impl std::fmt::Display for CliError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.msg)
}
}
impl From<std::io::Error> for CliError {
fn from(e: std::io::Error) -> Self {
Self {
msg: format!("std::io::Error: {}", e),
}
}
}
impl From<NmstateError> for CliError {
fn from(e: NmstateError) -> Self {
Self {
msg: format!("NmstateError: {}", e),
}
}
}
impl From<serde_yaml::Error> for CliError {
fn from(e: serde_yaml::Error) -> Self {
Self {
msg: format!("serde_yaml::Error: {}", e),
}
}
}
|
use super::primes;
use clap::Clap;
/// Largest prime factor
///
/// The prime factors of 13195 are 5, 7, 13 and 29.
/// What is the largest prime factor of the number 600851475143 ?
///
#[derive(Clap)]
pub struct Solution {
#[clap(short, long, default_value = "600851475143")]
number: usize,
}
impl Solution {
pub fn run(&self) -> usize {
primes::factors(self.number).last().unwrap_or(0)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_run() {
let s = Solution { number: 13195 };
assert_eq!(s.run(), 29);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.