text stringlengths 8 4.13M |
|---|
//! common tools for tree manipulation
pub use super::diagnosis::{TraversalType, TreeBuilder, TreeHandle, T};
pub use super::raw_def::TreeNode;
pub use super::shortcuts;
pub use super::template;
|
use std::io;
use async_std::channel::{unbounded, Receiver, Sender};
use futures::{
executor::ThreadPool,
future::{Future, FutureExt},
pin_mut, select,
};
const INTERNAL_CHANNEL: &str = "Control channel closed, this should never happen.";
/// Added functionality for the `futures::executor::ThreadPool` futures executor.
///
/// Futures will be spawned to and executed by the internal and exchangeable `ThreadPool` instance, but in such a way that *all* spawned futures are asked to stop on user request or in case any of them returns an error.
///
/// A notable difference to `futures:executor::ThreadPool` is that the user spawns futures of type `Output<Result(),T>` here instead of type `Output<()>`.
///
/// Caveats: If you do not call `observe().await` once all desired futures are spawned or if you spawn additional futures after the first `observe().await` the stopping mechanism won't work. In other words, instances cannot be "reused" after they were being observed for the first time.
/// For now no measures are in place to prevent a user from doing this (maybe in a future version).
///
/// Also note that spawned tasks *can not* be cancelled instantly. They will stop executing the next time they yield to the executor.
pub struct StoppableThreadPool<PoolError>
where
PoolError: Send + Sync + 'static,
{
pool: ThreadPool,
control_sender: Sender<Result<(), PoolError>>,
control_receiver: Receiver<Result<(), PoolError>>,
stop_senders: Vec<Sender<()>>,
}
impl<PoolError> StoppableThreadPool<PoolError>
where
PoolError: Send + Sync + 'static,
{
/// Create a new `StoppableThreadPool` instance using a default futures `ThreadPool` executor instance.
pub fn new() -> Result<StoppableThreadPool<PoolError>, io::Error> {
Ok(StoppableThreadPool::new_with_pool(ThreadPool::new()?))
}
/// Create a new `StoppableThreadPool` instance using a user supplied futures `ThreadPool` executor instance.
pub fn new_with_pool(pool: ThreadPool) -> StoppableThreadPool<PoolError> {
let (control_sender, control_receiver) = unbounded::<Result<(), PoolError>>();
StoppableThreadPool::<PoolError> {
pool,
control_sender,
control_receiver,
stop_senders: Vec::new(),
}
}
/// Change the underlying futures `ThreadPool` executor instance.
pub fn with_pool(&mut self, pool: ThreadPool) -> &mut Self {
self.pool = pool;
self
}
/// Start executing a future right away.
pub fn spawn<Fut>(&mut self, future: Fut) -> &mut Self
where
Fut: Future<Output = Result<(), PoolError>> + Send + 'static,
{
let (tx, rx) = unbounded::<()>();
self.stop_senders.push(tx);
let control = self.control_sender.clone();
self.pool.spawn_ok(async move {
let future = future.fuse();
let stopped = rx.recv().fuse();
pin_mut!(future, stopped);
let _ = select! {
output = future => control.send(output).await,
_ = stopped => control.send(Ok(())).await
};
});
self
}
/// Ensure that all spawned tasks are canceled on individual task error or any ` stop()` request issued by the user.
/// Call this function once all tasks are spawned.
/// A task that fails before a call to `observe()` is being awaited will still trigger a stop as soon as you actually start awaiting here.
pub async fn observe(&self) -> Result<(), PoolError> {
let mut completed: usize = 0;
while let Ok(output) = self.control_receiver.recv().await {
completed += 1;
if output.is_err() {
for tx in self.stop_senders.iter() {
if tx.send(()).await.is_err() {
eprintln!("Task already finished")
}
}
return output;
}
if completed == self.stop_senders.len() {
break;
}
}
Ok(())
}
/// Stop the execution of all spawned tasks.
pub async fn stop(&self, why: PoolError) {
self.control_sender
.send(Err(why))
.await
.expect(INTERNAL_CHANNEL)
}
}
#[cfg(test)]
mod tests {
use futures::{executor::block_on, executor::ThreadPool, join};
use crate::StoppableThreadPool;
async fn ok() -> Result<(), String> {
Ok(())
}
async fn forever() -> Result<(), String> {
loop {}
}
async fn fail(msg: String) -> Result<(), String> {
Err(msg)
}
#[test]
fn observe_ok() {
let mut pool = StoppableThreadPool::new().unwrap();
for _ in 0..1000 {
pool.spawn(ok());
}
block_on(async { assert_eq!(pool.observe().await.unwrap(), (),) });
}
#[test]
fn observe_err() {
let mut pool = StoppableThreadPool::new().unwrap();
let err = "fail_function_called".to_string();
pool.spawn(fail(err.clone()));
pool.spawn(forever());
block_on(async { assert_eq!(pool.observe().await.unwrap_err(), err) });
}
#[test]
fn user_stopped() {
let mut pool = StoppableThreadPool::new().unwrap();
pool.spawn(forever()).spawn(forever());
let stop_reason = "stopped by user".to_string();
block_on(async {
join!(
async { assert_eq!(pool.observe().await.unwrap_err(), stop_reason.clone()) },
pool.stop(stop_reason.clone())
)
});
}
#[test]
fn change_pool() {
let mut pool = StoppableThreadPool::new().unwrap();
pool.spawn(forever());
pool.with_pool(ThreadPool::new().unwrap());
pool.spawn(fail("fail function called".to_string()));
block_on(async {
assert_eq!(
pool.observe().await.unwrap_err(),
"fail function called".to_string(),
)
})
}
}
|
#[allow(dead_code)]
use criterion::Criterion;
mod hashes;
fn main() {
let crit = &mut Criterion::default().configure_from_args();
hashes::group(crit);
crit.final_summary();
}
|
use crate::grid::config::Entity;
/// A trait which is responsible for configuration of a [`Table`].
///
/// [`Table`]: crate::Table
pub trait TableOption<R, D, C> {
/// The function allows modification of records and a grid configuration.
fn change(self, records: &mut R, cfg: &mut C, dimension: &mut D);
/// A hint whether an [`TableOption`] is going to change table layout.
///
/// Return [`None`] if no changes are being done.
/// Otherwise return:
///
/// - [Entity::Global] - a grand layout changed. (a change which MIGHT require height/width update)
/// - [Entity::Row] - a certain row was changed. (a change which MIGHT require height update)
/// - [Entity::Column] - a certain column was changed. (a change which MIGHT require width update)
/// - [Entity::Cell] - a certain cell was changed. (a local change, no width/height update)
///
/// By default it's considered to be a grand change.
///
/// This methods primarily is used as an optimization,
/// to not make unnessary calculations if they're not needed, after using the [`TableOption`].
fn hint_change(&self) -> Option<Entity> {
Some(Entity::Global)
}
}
// todo: probably we could add one more hint but it likely require Vec<Entity>,
// so, as I am not sure about exact interface it's better be commented.
// /// A hint which layout part a [`TableOption`] is going to change.
// ///
// /// Return [`None`] if no part are being changed.
// /// Otherwise return:
// ///
// /// - [Entity::Global] - a total layout affection.
// /// - [Entity::Row] - a certain row affection.
// /// - [Entity::Column] - a certain column affection.
// /// - [Entity::Cell] - a certain cell affection.
// ///
// /// By default it's considered to be a grand change.
// ///
// /// This methods primarily is used as an optimization,
// /// to not make unnessary calculations if they're not needed, after using the [`TableOption`].
// fn hint_target(&self, records: &R) -> Option<Vec<Entity>> {
// let _ = records;
// Some(vec![Entity::Global])
// }
impl<T, R, D, C> TableOption<R, D, C> for &[T]
where
for<'a> &'a T: TableOption<R, D, C>,
{
fn change(self, records: &mut R, cfg: &mut C, dimension: &mut D) {
for opt in self {
opt.change(records, cfg, dimension)
}
}
}
#[cfg(feature = "std")]
impl<T, R, D, C> TableOption<R, D, C> for Vec<T>
where
T: TableOption<R, D, C>,
{
fn change(self, records: &mut R, cfg: &mut C, dimension: &mut D) {
for opt in self {
opt.change(records, cfg, dimension)
}
}
}
|
use std::ops::Bound;
use anyhow::Context;
use chrono::Utc;
use tracing::error;
use uuid::Uuid;
use crate::app::api::v1::AppError;
use crate::app::error::ErrorExt;
use crate::app::error::ErrorKind as AppErrorKind;
use crate::app::AppContext;
use crate::clients::event::LockedTypes;
use crate::clients::{
conference::RoomUpdate as ConfRoomUpdate, event::RoomUpdate as EventRoomUpdate,
};
use crate::db::class::{BoundedDateTimeTuple, RtcSharingPolicy};
pub async fn update_classroom_id(
state: &dyn AppContext,
classroom_id: Uuid,
event_id: Uuid,
conference_id: Uuid,
) -> anyhow::Result<()> {
let event_fut = state.event_client().update_room(
event_id,
EventRoomUpdate {
time: None,
classroom_id: Some(classroom_id),
},
);
let conference_fut = state.conference_client().update_room(
conference_id,
ConfRoomUpdate {
time: None,
reserve: None,
classroom_id: Some(classroom_id),
host: None,
},
);
let result = tokio::try_join!(event_fut, conference_fut).map(|_| ());
result.context("Services requests updating classroom_id failed")
}
pub async fn create_event_room(
state: &dyn AppContext,
webinar: &impl Creatable,
) -> Result<Uuid, AppError> {
state
.event_client()
.create_room(
(Bound::Included(Utc::now()), Bound::Unbounded),
webinar.audience().to_owned(),
Some(true),
webinar.tags().map(ToOwned::to_owned),
Some(webinar.id()),
)
.await
.context("Request to event")
.error(AppErrorKind::MqttRequestFailed)
}
pub async fn create_conference_room(
state: &dyn AppContext,
webinar: &impl Creatable,
time: &BoundedDateTimeTuple,
) -> Result<Uuid, AppError> {
let conference_time = match time.0 {
Bound::Included(t) | Bound::Excluded(t) => (Bound::Included(t), Bound::Unbounded),
Bound::Unbounded => (Bound::Included(Utc::now()), Bound::Unbounded),
};
let policy = webinar
.rtc_sharing_policy()
.as_ref()
.map(ToString::to_string);
state
.conference_client()
.create_room(
conference_time,
webinar.audience().to_owned(),
policy,
webinar.reserve(),
webinar.tags().map(ToOwned::to_owned),
Some(webinar.id()),
)
.await
.context("Request to conference")
.error(AppErrorKind::MqttRequestFailed)
}
pub async fn create_event_and_conference_rooms(
state: &dyn AppContext,
webinar: &impl Creatable,
time: &BoundedDateTimeTuple,
) -> Result<(Uuid, Uuid), AppError> {
let event_room_id = create_event_room(state, webinar).await?;
let conference_room_id = create_conference_room(state, webinar, time).await?;
Ok((event_room_id, conference_room_id))
}
pub trait Creatable {
fn id(&self) -> Uuid;
fn audience(&self) -> &str;
fn reserve(&self) -> Option<i32>;
fn tags(&self) -> Option<&serde_json::Value>;
fn rtc_sharing_policy(&self) -> Option<RtcSharingPolicy>;
}
pub async fn lock_interaction(state: &dyn AppContext, event_room_id: Uuid, types: LockedTypes) {
if let Err(e) = state
.event_client()
.update_locked_types(event_room_id, types)
.await
{
error!(
%event_room_id,
"Failed to lock interaction in event room, err = {:?}", e
);
}
}
|
use crypto::buffer::{self, BufferResult, ReadBuffer, WriteBuffer};
use lazy_static::lazy_static;
use rand::Rng;
lazy_static! {
static ref KEY: [u8; 16] = rand::thread_rng().gen();
}
fn main() {
let (block_size, total_size) = detect_block();
let result = detect_bytes(block_size, total_size);
println!("{}", String::from_utf8(result).unwrap());
}
fn detect_block() -> (usize, usize) {
let base_size = encryption_oracle(&[]).len();
for i in 1..512 {
let test_vec = vec![b'A'; i];
let test_size = encryption_oracle(&test_vec).len();
if test_size > base_size {
return (test_size - base_size, base_size);
}
}
panic!("Unable to find block size");
}
fn detect_bytes(block_size: usize, total_size: usize) -> Vec<u8> {
// A = filler character 'A'
// X = character to iterate over to guess
// K = known secret character we can placein our input
// U = unknown secret character, beginning of secret blocks automatically appended by encryption_oracle
// In the first run we determine `encrypt([A, A, A, A, ... A, U | <secret block>...])`
// And we test possible X values `encrypt([A, A, A, A, ... A, X | <secret block> | <secret block>...])`
// Until we find X = U
// We shrink our padding to find `encrypt([A, A, A, ... A, U, U | <secret block> | <secret block>...])`
// The first letter is K, so try `encrypt([A, A, A, ... A, K, X | <secret block> | <secret block>...])`
// Until we find X to be the second U.
// Repeat for the entire block.
// We find the whole first block `encrypt([K, K, K, ..block.. K | <secret block> | <secret block> ...])`
//
// To find the second block, we repeat and use the first block for padding again
// We fill the second block with what we know [A, A, A, A, ... K | K, K, ..block.. K, U | <secret block> | <secret block> ...]
// We compare this, just like the first round [A, A, A, A, ... K | K, K, ..block.. K, X | <secret block> | <secret block> ...]
let mut known = vec![];
for i in 1..=total_size {
let padding_prefix = vec![b'A'; block_size - (i % block_size)];
let target = encryption_oracle(&padding_prefix);
for test_char in 0..=u8::MAX {
let test_vec = [&padding_prefix[..], &known[..], &[test_char]].concat();
let oracle_output = encryption_oracle(&test_vec);
// round up to next block
let block_len = ((i + block_size) / block_size) * block_size;
// If the block is the same between our guessed character and the "target" without the
// guess, we are all set for that character.
if oracle_output[0..block_len] == target[0..block_len] {
if test_char != 0 {
known.push(test_char);
}
break;
}
}
}
known
}
fn encryption_oracle(input: &[u8]) -> Vec<u8> {
const APPEND: &[u8] = b"Um9sbGluJyBpbiBteSA1LjAKV2l0aCBteSByYWctdG9wIGRvd24gc28gbXkg\
aGFpciBjYW4gYmxvdwpUaGUgZ2lybGllcyBvbiBzdGFuZGJ5IHdhdmluZyBq\
dXN0IHRvIHNheSBoaQpEaWQgeW91IHN0b3A/IE5vLCBJIGp1c3QgZHJvdmUg\
YnkK";
let decoded = &base64::decode(APPEND).unwrap();
let final_input = [input, decoded].concat();
let encryptor = crypto::aes::ecb_encryptor(
crypto::aes::KeySize::KeySize128,
&*KEY,
crypto::blockmodes::PkcsPadding,
);
encrypt(&final_input, encryptor)
}
fn encrypt(
plaintext: &[u8],
mut encryptor: Box<dyn crypto::symmetriccipher::Encryptor>,
) -> Vec<u8> {
let mut final_result = Vec::<u8>::new();
let mut input = buffer::RefReadBuffer::new(plaintext);
let mut buffer = [0; 4096];
let mut output = buffer::RefWriteBuffer::new(&mut buffer);
loop {
let result = encryptor.encrypt(&mut input, &mut output, true).unwrap();
final_result.extend(
output
.take_read_buffer()
.take_remaining()
.iter()
.map(|&i| i),
);
if let BufferResult::BufferUnderflow = result {
break;
}
}
return final_result;
}
|
use crate::{
FieldResultExtra,
FileInfo,
FieldInfo,
Result,
MulterError,
Handler,
};
use actix_web::{
http::header::ContentDisposition,
web::block,
};
use futures::future::{LocalBoxFuture, FutureExt, TryFutureExt, try_join};
use log::error;
use rand::{Rng, thread_rng, distributions::Alphanumeric};
use std::{
ffi::OsString,
io::Write,
iter,
path::Path,
};
use tokio::stream::StreamExt;
pub struct FileResultInfo {
info: FileInfo,
accepted: bool,
}
impl FieldResultExtra for FileResultInfo {
fn content(&self) -> Option<&[u8]> {
None
}
fn file(&self) -> Option<&FileInfo> {
Some(&self.info)
}
fn size(&self) -> usize {
self.info.size
}
fn accept(&mut self) {
self.accepted = true;
}
}
impl Drop for FileResultInfo {
fn drop(&mut self) {
if !self.accepted {
if let Err(e) = std::fs::remove_file(&self.info.path) {
error!("failed to remove file {:?}", e);
}
}
}
}
pub type PathGenerator = Box<dyn for<'a> Fn(&'a FieldInfo, Option<ContentDisposition>)
-> LocalBoxFuture<'a, Result<OsString>>>;
pub struct FileStorageBuilder {
max_size: Option<usize>,
destination: Option<PathGenerator>,
filename: Option<PathGenerator>,
make_dirs: bool,
}
impl Default for FileStorageBuilder {
fn default() -> Self {
Self {
max_size: None,
destination: None,
filename: None,
make_dirs: false,
}
}
}
impl FileStorageBuilder {
pub fn max_size(mut self, size: usize) -> Self {
self.max_size = Some(size);
self
}
pub fn destination(
mut self,
destination: PathGenerator,
) -> Self {
self.destination = Some(destination);
self
}
pub fn constant_destination(
mut self,
destination: OsString,
) -> Self {
self.destination = Some(Box::new(move |_, _| {
let destination = destination.clone();
async move {
Ok(destination.clone())
}.boxed_local()
}));
self
}
pub fn filename(
mut self,
filename: PathGenerator
) -> Self {
self.filename = Some(filename);
self
}
pub fn origin_filename(mut self) -> Self {
self.filename = Some(Box::new(|info, content_disposition| async move {
let content_disposition = content_disposition
.ok_or_else(|| MulterError::MissingContentDisposition)?;
let filename = content_disposition.get_filename()
.ok_or_else(|| MulterError::ExpectedFileField {
field: info.name.clone().into(),
})?;
Ok(sanitize_filename::sanitize(filename).into())
}.boxed_local()));
self
}
pub fn random_filename(mut self, length: usize) -> Self {
self.filename = Some(Box::new(move |info, content_disposition| async move {
let content_disposition = content_disposition
.ok_or_else(|| MulterError::MissingContentDisposition)?;
let extension = Path::new(content_disposition.get_filename()
.ok_or_else(|| MulterError::ExpectedFileField {
field: info.name.clone().into(),
})?)
.extension()
.map(|ext| ext.to_str()
.ok_or_else(|| MulterError::InvalidEncoding {
field: info.name.clone().into(),
}))
.transpose()?;
let mut rng = thread_rng();
let mut filename: OsString = iter::repeat(())
.map(|_| rng.sample(Alphanumeric))
.take(length)
.collect::<String>().into();
if let Some(extension) = extension {
filename.push(".");
filename.push(sanitize_filename::sanitize(extension));
}
Ok(filename)
}.boxed_local()));
self
}
pub fn make_dirs(mut self) -> Self {
self.make_dirs = true;
self
}
pub fn build(self) -> Handler {
let filename_generator = self.filename.expect("must have filename generator");
let destination_generator = self.destination.expect("must have destination generator");
let max_size = self.max_size;
let make_dirs = self.make_dirs;
Box::new(move |info, field| {
try_join(filename_generator(info, field.content_disposition()),
destination_generator(info, field.content_disposition()))
.and_then(move |(filename, destination)| async move {
let destination_copy = destination.clone();
if make_dirs {
block(move || std::fs::create_dir_all(destination_copy))
.await
.map_err(MulterError::from)?;
}
let filepath = Path::new(&destination).join(&filename);
let path = OsString::from(filepath.clone());
let mut file = block(move || std::fs::File::create(filepath))
.await
.map_err(MulterError::from)?;
let mut size: usize = 0;
while let Some(chunk) = field.next().await {
let data = chunk
.map_err(MulterError::from)?;
size += data.len();
if let Some(max_size) = max_size {
if size > max_size {
if let Err(e) = std::fs::remove_file(&path) {
error!("failed to remove file {}", e);
}
return Err(MulterError::MaxFieldContentLengthReached {
field: info.name.clone().into(),
});
}
}
file = block(move || file.write_all(&data).map(|_| file))
.await
.map_err(|e| {
if let Err(e) = std::fs::remove_file(&path) {
error!("failed to remove file {}", e);
}
MulterError::from(e)
})?;
}
drop(file);
Ok(Box::new(FileResultInfo {
info: FileInfo {
destination,
filename,
path,
size,
},
accepted: false,
}) as Box<dyn FieldResultExtra + std::marker::Send>)
})
}.boxed_local())
}
}
|
use crate::{
scene::{
node::NodeKind,
Scene
},
gui::UserInterface,
math::vec2::Vec2,
resource::{
Resource,
ResourceKind,
model::Model,
ttf::Font,
texture::Texture
},
utils::{
pool::{
Pool,
Handle
},
visitor::{
Visitor,
VisitResult,
Visit,
},
},
renderer::render::{
Renderer,
Statistics
},
};
use std::{
collections::VecDeque,
time::Duration,
cell::RefCell,
rc::Rc,
any::TypeId,
path::{
PathBuf,
Path
}
};
pub struct ResourceManager {
resources: Vec<Rc<RefCell<Resource>>>,
/// Path to textures, extensively used for resource files
/// which stores path in weird format (either relative or absolute) which
/// is obviously not good for engine.
textures_path: PathBuf,
}
impl ResourceManager {
pub fn new() -> ResourceManager {
Self {
resources: Vec::new(),
textures_path: PathBuf::from("data/textures/"),
}
}
#[inline]
pub fn for_each_texture_mut<Func>(&self, mut func: Func) where Func: FnMut(&mut Texture) {
for resource in self.resources.iter() {
if let ResourceKind::Texture(texture) = resource.borrow_mut().borrow_kind_mut() {
func(texture);
}
}
}
#[inline]
fn add_resource(&mut self, resource: Rc<RefCell<Resource>>) {
self.resources.push(resource)
}
/// Searches for a resource of specified path, if found - returns handle to resource
/// and increases reference count of resource.
#[inline]
fn find_resource(&mut self, path: &Path) -> Option<Rc<RefCell<Resource>>> {
for resource in self.resources.iter() {
if resource.borrow().get_path() == path {
return Some(resource.clone());
}
}
None
}
#[inline]
pub fn get_textures_path(&self) -> &Path {
self.textures_path.as_path()
}
pub fn update(&mut self) {
self.resources.retain(|resource| {
Rc::strong_count(resource) > 1
})
}
}
impl Visit for ResourceManager {
fn visit(&mut self, name: &str, visitor: &mut Visitor) -> VisitResult {
visitor.enter_region(name)?;
self.resources.visit("Resources", visitor)?;
visitor.leave_region()
}
}
pub struct State {
scenes: Pool<Scene>,
resource_manager: ResourceManager,
}
impl State {
#[inline]
pub fn new() -> Self {
State {
scenes: Pool::new(),
resource_manager: ResourceManager::new(),
}
}
pub fn request_resource(&mut self, path: &Path) -> Option<Rc<RefCell<Resource>>> {
match self.resource_manager.find_resource(path) {
Some(resource) => Some(resource),
None => {
// No such resource, try to load it.
let extension = path.extension().
and_then(|os| os.to_str()).
map_or(String::from(""), |s| s.to_ascii_lowercase());
match extension.as_str() {
"jpg" | "jpeg" | "png" | "tif" | "tiff" | "tga" | "bmp" => match Texture::load(path) {
Ok(texture) => {
let resource = Rc::new(RefCell::new(Resource::new(path, ResourceKind::Texture(texture))));
self.resource_manager.add_resource(resource.clone());
println!("Texture {} is loaded!", path.display());
Some(resource)
}
Err(e) => {
println!("Unable to load texture {}! Reason {}", path.display(), e);
None
}
}
"fbx" => match Model::load(path, self) {
Ok(model) => {
let resource = Rc::new(RefCell::new(Resource::new(path, ResourceKind::Model(model))));
self.resource_manager.add_resource(resource.clone());
println!("Model {} is loaded!", path.display());
Some(resource)
}
Err(e) => {
println!("Unable to load model from {}! Reason {}", path.display(), e);
None
}
},
_ => {
println!("Unknown resource type {}!", path.display());
None
}
}
}
}
}
fn clear(&mut self) {
for i in 0..self.scenes.get_capacity() {
if let Some(mut scene) = self.scenes.take_at(i) {
self.destroy_scene_internal(&mut scene);
}
}
}
fn resolve(&mut self) {
let resources_to_reload = self.resource_manager.resources.clone();
for resource in resources_to_reload {
let path = PathBuf::from(resource.borrow().get_path());
let id = resource.borrow().get_kind_id();
if id == TypeId::of::<Model>() {
let new_model = match Model::load(path.as_path(), self) {
Ok(new_model) => new_model,
Err(e) => {
println!("Unable to reload {:?} model! Reason: {}", path, e);
continue;
}
};
if let ResourceKind::Model(model) = resource.borrow_mut().borrow_kind_mut() {
*model = new_model;
}
} else if id == TypeId::of::<Texture>() {
let new_texture = match Texture::load(path.as_path()) {
Ok(texture) => texture,
Err(e) => {
println!("Unable to reload {:?} texture! Reason: {}", path, e);
continue;
}
};
if let ResourceKind::Texture(texture) = resource.borrow_mut().borrow_kind_mut() {
*texture = new_texture;
}
}
}
for scene in self.scenes.iter_mut() {
for node in scene.get_nodes_mut().iter_mut() {
let node_name = String::from(node.get_name());
if let Some(resource) = node.get_resource() {
if let NodeKind::Mesh(mesh) = node.borrow_kind_mut() {
if let ResourceKind::Model(model) = resource.borrow().borrow_kind() {
let resource_node_handle = model.find_node_by_name(node_name.as_str());
if let Some(resource_node) = model.get_scene().get_node(resource_node_handle) {
if let NodeKind::Mesh(resource_mesh) = resource_node.borrow_kind() {
let surfaces = mesh.get_surfaces_mut();
surfaces.clear();
for resource_surface in resource_mesh.get_surfaces() {
surfaces.push(resource_surface.make_copy());
}
}
}
}
}
}
}
}
}
#[inline]
pub fn get_scenes(&self) -> &Pool<Scene> {
&self.scenes
}
#[inline]
pub fn get_scenes_mut(&mut self) -> &mut Pool<Scene> {
&mut self.scenes
}
#[inline]
pub fn get_resource_manager_mut(&mut self) -> &mut ResourceManager {
&mut self.resource_manager
}
#[inline]
pub fn get_resource_manager(&self) -> &ResourceManager {
&self.resource_manager
}
#[inline]
pub fn add_scene(&mut self, scene: Scene) -> Handle<Scene> {
self.scenes.spawn(scene)
}
#[inline]
pub fn get_scene(&self, handle: Handle<Scene>) -> Option<&Scene> {
if let Some(scene) = self.scenes.borrow(handle) {
return Some(scene);
}
None
}
#[inline]
pub fn get_scene_mut(&mut self, handle: Handle<Scene>) -> Option<&mut Scene> {
if let Some(scene) = self.scenes.borrow_mut(handle) {
return Some(scene);
}
None
}
#[inline]
fn destroy_scene_internal(&mut self, scene: &mut Scene) {
scene.remove_node(scene.get_root(), self);
}
#[inline]
pub fn destroy_scene(&mut self, handle: Handle<Scene>) {
if let Some(mut scene) = self.scenes.take(handle) {
self.destroy_scene_internal(&mut scene);
}
}
}
impl Visit for State {
fn visit(&mut self, name: &str, visitor: &mut Visitor) -> VisitResult {
visitor.enter_region(name)?;
self.resource_manager.visit("ResourceManager", visitor)?;
self.scenes.visit("Scenes", visitor)?;
visitor.leave_region()
}
}
pub struct Engine {
renderer: Renderer,
pub state: State,
events: VecDeque<glutin::Event>,
running: bool,
font_cache: Pool<Font>,
default_font: Handle<Font>,
user_interface: UserInterface,
}
impl Engine {
#[inline]
pub fn new() -> Engine {
let mut font_cache = Pool::new();
let default_font = font_cache.spawn(Font::load(
Path::new("data/fonts/font.ttf"),
20.0,
(0..255).collect()).unwrap());
let mut renderer = Renderer::new();
renderer.upload_font_cache(&mut font_cache);
Engine {
state: State::new(),
renderer,
events: VecDeque::new(),
running: true,
user_interface: UserInterface::new(default_font),
default_font,
font_cache,
}
}
#[inline]
pub fn get_state(&self) -> &State {
&self.state
}
#[inline]
pub fn get_state_mut(&mut self) -> &mut State {
&mut self.state
}
#[inline]
pub fn is_running(&self) -> bool {
self.running
}
pub fn update(&mut self, dt: f64) {
let client_size = self.renderer.context.window().get_inner_size().unwrap();
let aspect_ratio = (client_size.width / client_size.height) as f32;
self.state.resource_manager.update();
for scene in self.state.scenes.iter_mut() {
scene.update(aspect_ratio, dt);
}
self.user_interface.update(Vec2::make(client_size.width as f32, client_size.height as f32));
}
pub fn poll_events(&mut self) {
// Gather events
let events = &mut self.events;
events.clear();
self.renderer.events_loop.poll_events(|event| {
events.push_back(event);
});
}
#[inline]
pub fn get_font(&self, font_handle: Handle<Font>) -> Option<&Font> {
self.font_cache.borrow(font_handle)
}
#[inline]
pub fn get_default_font(&self) -> Handle<Font> {
self.default_font
}
#[inline]
pub fn get_ui(&self) -> &UserInterface {
&self.user_interface
}
#[inline]
pub fn get_ui_mut(&mut self) -> &mut UserInterface {
&mut self.user_interface
}
#[inline]
pub fn get_rendering_statisting(&self) -> &Statistics {
self.renderer.get_statistics()
}
#[inline]
pub fn set_frame_size(&mut self, new_size: Vec2) {
self.renderer.set_frame_size(new_size)
}
#[inline]
pub fn get_frame_size(&self) -> Vec2 {
self.renderer.get_frame_size()
}
pub fn render(&mut self) {
self.renderer.upload_font_cache(&mut self.font_cache);
self.renderer.upload_resources(&mut self.state);
self.user_interface.draw(&self.font_cache);
self.renderer.render(&self.state, &self.user_interface.get_drawing_context());
}
#[inline]
pub fn stop(&mut self) {
self.running = false;
}
#[inline]
pub fn pop_event(&mut self) -> Option<glutin::Event> {
self.events.pop_front()
}
}
impl Visit for Engine {
fn visit(&mut self, name: &str, visitor: &mut Visitor) -> VisitResult {
visitor.enter_region(name)?;
// Make sure to delete unused resources.
if visitor.is_reading() {
self.state.resource_manager.update();
self.state.scenes.clear();
}
self.state.visit("State", visitor)?;
if visitor.is_reading() {
self.state.resolve();
}
visitor.leave_region()
}
}
pub fn duration_to_seconds_f64(duration: Duration) -> f64 {
duration.as_secs() as f64 + f64::from(duration.subsec_nanos()) / 1_000_000_000.0
}
pub fn duration_to_seconds_f32(duration: Duration) -> f32 {
duration_to_seconds_f64(duration) as f32
}
|
//! # AuthN and authZ for site
//!
//! We are not getting fancy here...yet. We are using Google's single sign on OAuth for
//! authentication but we still need a way to protect some endpoints.
//!
//! ## Signing in
//!
//! When the user clicks the Sign in with Google button, the google api.js library will reach out
//! and provide a confirmation window. When the user accepts, the user's profile information will
//! be returned, including user_id and email along with the real User name.
//!
//! ### User types
//!
//! Currently, there will only be one user type. In the future, there may other user types. For
//! example, there may be a free tier and a premium tier. To make a distinction between these
//! types, we will need something additional to mark the user as being of a different kind.
//! Eventually we can use Firestore or rethinkdb to hold this extra information.
//!
//! ## AuthZ tokens
//!
//! Once authenticated, a JWT will be created. This token will expire in 15 minutes. All requests
//! from the agent (the user is using) will pass this JWT token around. The token will only be
//! stored in memory and not in a cookie to reduce the chance that a token can be hijacked from the
//! user's system.
use crate::{data::User,
jwt::jwt::{create_jwt, JWTResponse},
pgdb::{pgdb,
models}};
use tokio_postgres::{Client};
use chrono::{Utc, Duration};
use serde::{Deserialize,
Serialize};
use std::convert::Infallible;
use warp::{filters::BoxedFilter,
http::{Response,
StatusCode},
Filter,
Reply};
use log::{info, error};
use lazy_static::lazy_static;
use crate::config::Settings;
lazy_static! {
pub static ref CONFIG: Settings = Settings::new().expect("Unable to get config settings");
}
#[derive(Debug, Serialize, Deserialize)]
struct Claims {
sub: String,
user: String,
exp: usize,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct LoginParams {
uname: String,
first: String,
last: String,
email: String,
token: String,
}
#[derive(Deserialize, Serialize, Debug)]
pub struct RegisterParams {
uname: String,
psw: String,
email: String,
}
#[derive(Debug, Serialize, Deserialize)]
struct AuthPost {
token: String
}
/// FIXME: This method is now deprecated, but might return once we have a freemium/premium model
/*
pub fn register() -> BoxedFilter<(impl Reply,)> {
let route = warp::post()
.and(warp::path("register"))
.and(warp::body::json())
.map(|reg_params: RegisterParams| {
println!("{:#?}", reg_params);
let builder = Response::builder();
let reply = match get_user("khadga", ®_params.uname) {
Some((_, users)) if users.len() >= 1 => {
error!("More than one user with name of {}", reg_params.uname);
builder
.status(StatusCode::from_u16(409).unwrap())
.body("User already exists")
}
Some((coll, users)) if users.is_empty() => {
// FIXME: This code will change for Firestore or rethinkdb
let user = User::new(reg_params.uname, reg_params.psw, reg_params.email);
match add_user(&coll, user) {
Err(_) => builder.status(StatusCode::from_u16(500).unwrap()).body(""),
_ => builder.status(StatusCode::OK).body("Added user"),
}
}
_ => {
builder
.status(StatusCode::from_u16(500).unwrap())
.body("Unable to retrieve data from database")
}
};
reply
});
route.boxed()
}
*/
pub fn build_cookie(
key: &str,
val: &str,
expires: Option<Duration>,
flags: &[&str]
) -> String {
let mut cookie = format!("{}={};", key, val);
if let Some(dur) = expires {
let expires_at = Utc::now() + dur;
cookie = cookie + &format!(" expires={}", expires_at.to_rfc2822())
}
let final_cookie = flags.into_iter()
.fold(cookie.clone(), |mut acc, next| {
acc = acc + "; " + &next;
return acc
});
final_cookie
}
/// Will perform a verification request from the mimir service
///
/// Note: If you try to make this return Result<impl Reply, warp::http::Error> you will get an error
/// from the type that some traits are not accepted. By making this infallible, and only ever
/// returning a Reply (which itself holds the error) we can make this work
pub async fn make_verify_request(
args: (LoginParams, User)
) -> Result<impl Reply, Infallible> {
let (params, user) = args;
// Get the mimir host and port from the kube env vars
let mimir_host = match std::env::var("MIMIR_NODE_IP_SERVICE_SERVICE_HOST") {
Ok(val) => val, // If it exists, we're running under kubernetes
Err(_) => String::from("mimir") // assume we're running from docker stack
};
let mimir_port = match std::env::var("MIMIR_NODE_IP_SERVICE_SERVICE_PORT") {
Ok(val) => val,
Err(_) => "80".into()
};
let mimir = format!("http://{}:{}/auth", mimir_host, mimir_port);
info!("Making request to {}", mimir);
let builder = Response::builder();
let post_data = AuthPost { token: params.token };
let response = reqwest::Client::new()
.post(&mimir)
.json(&post_data)
.send()
.await;
// Lookup user in database. If he doesn't exist, generate a user.
let db_client: Client;
match pgdb::establish_connection("test_db").await {
Ok((client, _)) => {
db_client = client;
},
Err(e) => {
let resp = builder.status(StatusCode::from_u16(500).unwrap())
.body(format!("Unable to create connection to postgresql database: {}", e))
.expect("Unable to create HTTP Response");
return Ok(resp)
}
};
let resp = match response {
Ok(resp) => {
if resp.status() != 201 {
builder
.status(resp.status())
.body(format!("Unable to generate JWT token"))
} else { // Generate JWT
let dbuser = models::User {
email: user.email.clone(),
first_name: String::from(""),
last_name: String::from(""),
username: user.user_name.clone(),
user_id: -1
};
match pgdb::lookup_user(&db_client, "users", &dbuser).await {
Ok(user_id) => {
if user_id.len() != 1 {
error!("There is an error with query or multiple usernames found");
panic!("Integrity with database is compromised");
}
let userid = user_id[0];
info!("User ID is {}", userid);
// TODO, perform any other logic here
},
Err(_) => { // In this case, we haven't seen this user before, so let's add him
match pgdb::insert_user(&db_client, "users", &dbuser).await {
Ok(count) => {
if count != 1 {
return Ok(builder.status(StatusCode::from_u16(500).unwrap())
.body("Unable to insert user into database".into())
.expect("Unable to create HTTP Response"));
}
},
Err(e) => {
return Ok(builder.status(StatusCode::from_u16(500).unwrap())
.body(format!("Unable to insert user into database: {}", e))
.expect("Unable to create HTTP Response"))
}
}
}
};
match create_jwt(&user.user_name, &user.email) {
Ok(jwt) => {
let jwt_resp: JWTResponse = serde_json::from_str(&jwt)
.expect("Could not deserialize");
let duration = Duration::minutes(15);
let exp = Utc::now() + duration;
let secure_flags = vec!["secure", "samesite=strict"];
// This kind of sucks, but this is how you can concat slice/vecs
let http_only_flags = [&["httpOnly"], &secure_flags[..]].concat();
let cookie = build_cookie(
"jwt",
&jwt_resp.token,
Some(duration),
&http_only_flags
);
info!("jwt cookie: {}", cookie);
let expires = build_cookie("expiry", &exp.to_rfc2822(), None, &vec![]);
info!("expiry cookie: {}", expires);
let username_s: Vec<&str> = user.email.split("@").collect();
let username = username_s.get(0).expect("Could not determine username");
let khadga_user = build_cookie(
"khadga_user",
&username,
Some(duration),
&secure_flags
);
info!("khadga_user cookie: {}", khadga_user);
let resp = builder
.status(StatusCode::OK)
.header("Set-Cookie", cookie)
.header("Set-Cookie", expires)
.header("Set-Cookie", khadga_user);
info!("{:?}", resp);
resp.body(jwt)
},
Err(e) => {
builder
.status(StatusCode::from_u16(403).unwrap())
.body(format!("Unable to generate JWT token: {}", e))
}
}
}
},
Err(err) => {
builder
.status(StatusCode::from_u16(500).unwrap())
.body(format!("Failed getting response: {}", err))
}
};
Ok(resp.expect("Could not build response"))
}
/// This is the handler for when the user clicks the Sign in with Google button on the app.
///
/// Once the user authorizes us with Google, the client will hit this endpoint and provide some
/// information. We will store some user information in the database and then return back a JWT
/// that the client will save in memory. Eventually we will provide a means for the user to submit
/// a public key which we will store. We can then use a custom header for the JWT token and sign it
/// with the public key. We can then allow the client to store the JWT in a cookie
pub fn login() -> BoxedFilter<(impl Reply,)> {
let login = warp::post()
.and(warp::path("login"))
.and(warp::body::json())
.map(|login_params: LoginParams| {
// TODO: Need a login handler and a websocket endpoint
// When a user logs in, they will be given an auth token which can be used
// to gain access to chat and video for as long as the session maintains activity
let params_copy = login_params.clone();
let user = User::new(
login_params.uname,
login_params.first,
login_params.last,
login_params.email,
login_params.token
);
(params_copy, user)
})
.and_then(make_verify_request);
login.boxed()
}
|
use super::*;
use crate::errors::*;
use crate::util::*;
use stun::message::*;
use async_trait::async_trait;
use crc::{Crc, CRC_32_ISCSI};
use std::fmt;
use std::ops::Add;
use std::sync::atomic::{AtomicU16, AtomicU64, AtomicU8, Ordering};
use std::sync::Arc;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use tokio::sync::{broadcast, Mutex};
#[derive(Default)]
pub struct CandidateBaseConfig {
pub candidate_id: String,
pub network: String,
pub address: String,
pub port: u16,
pub component: u16,
pub priority: u32,
pub foundation: String,
pub conn: Option<Arc<dyn util::Conn + Send + Sync>>,
pub initialized_ch: Option<broadcast::Receiver<()>>,
}
pub(crate) type OnClose = fn() -> Result<(), Error>;
pub struct CandidateBase {
pub(crate) id: String,
pub(crate) network_type: AtomicU8,
pub(crate) candidate_type: CandidateType,
pub(crate) component: AtomicU16,
pub(crate) address: String,
pub(crate) port: u16,
pub(crate) related_address: Option<CandidateRelatedAddress>,
pub(crate) tcp_type: TcpType,
pub(crate) resolved_addr: Mutex<SocketAddr>,
pub(crate) last_sent: AtomicU64,
pub(crate) last_received: AtomicU64,
pub(crate) conn: Option<Arc<dyn util::Conn + Send + Sync>>,
pub(crate) agent_internal: Option<Arc<Mutex<AgentInternal>>>,
pub(crate) closed_ch: Arc<Mutex<Option<broadcast::Sender<()>>>>,
pub(crate) foundation_override: String,
pub(crate) priority_override: u32,
//CandidateHost
pub(crate) network: String,
//CandidateRelay
pub(crate) relay_client: Option<Arc<turn::client::Client>>,
}
impl Default for CandidateBase {
fn default() -> Self {
Self {
id: String::new(),
network_type: AtomicU8::new(0),
candidate_type: CandidateType::default(),
component: AtomicU16::new(0),
address: String::new(),
port: 0,
related_address: None,
tcp_type: TcpType::default(),
resolved_addr: Mutex::new(SocketAddr::new(IpAddr::from([0, 0, 0, 0]), 0)),
last_sent: AtomicU64::new(0),
last_received: AtomicU64::new(0),
conn: None,
agent_internal: None,
closed_ch: Arc::new(Mutex::new(None)),
foundation_override: String::new(),
priority_override: 0,
network: String::new(),
relay_client: None,
}
}
}
// String makes the candidateBase printable
impl fmt::Display for CandidateBase {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if let Some(related_address) = self.related_address() {
write!(
f,
"{} {} {}:{}{}",
self.network_type(),
self.candidate_type(),
self.address(),
self.port(),
related_address,
)
} else {
write!(
f,
"{} {} {}:{}",
self.network_type(),
self.candidate_type(),
self.address(),
self.port(),
)
}
}
}
#[async_trait]
impl Candidate for CandidateBase {
fn foundation(&self) -> String {
if !self.foundation_override.is_empty() {
return self.foundation_override.clone();
}
let mut buf = vec![];
buf.extend_from_slice(self.candidate_type().to_string().as_bytes());
buf.extend_from_slice(self.address.as_bytes());
buf.extend_from_slice(self.network_type().to_string().as_bytes());
let checksum = Crc::<u32>::new(&CRC_32_ISCSI).checksum(&buf);
format!("{}", checksum)
}
/// Returns Candidate ID.
fn id(&self) -> String {
self.id.clone()
}
/// Returns candidate component.
fn component(&self) -> u16 {
self.component.load(Ordering::SeqCst)
}
fn set_component(&self, component: u16) {
self.component.store(component, Ordering::SeqCst);
}
/// Returns a time indicating the last time this candidate was received.
fn last_received(&self) -> SystemTime {
UNIX_EPOCH.add(Duration::from_nanos(
self.last_received.load(Ordering::SeqCst),
))
}
/// Returns a time indicating the last time this candidate was sent.
fn last_sent(&self) -> SystemTime {
UNIX_EPOCH.add(Duration::from_nanos(self.last_sent.load(Ordering::SeqCst)))
}
/// Returns candidate NetworkType.
fn network_type(&self) -> NetworkType {
NetworkType::from(self.network_type.load(Ordering::SeqCst))
}
/// Returns Candidate Address.
fn address(&self) -> String {
self.address.clone()
}
/// Returns Candidate Port.
fn port(&self) -> u16 {
self.port
}
/// Computes the priority for this ICE Candidate.
fn priority(&self) -> u32 {
if self.priority_override != 0 {
return self.priority_override;
}
// The local preference MUST be an integer from 0 (lowest preference) to
// 65535 (highest preference) inclusive. When there is only a single IP
// address, this value SHOULD be set to 65535. If there are multiple
// candidates for a particular component for a particular data stream
// that have the same type, the local preference MUST be unique for each
// one.
(1 << 24) * u32::from(self.candidate_type().preference())
+ (1 << 8) * u32::from(self.local_preference())
+ (256 - u32::from(self.component()))
}
/// Returns `Option<CandidateRelatedAddress>`.
fn related_address(&self) -> Option<CandidateRelatedAddress> {
self.related_address.as_ref().cloned()
}
/// Returns candidate type.
fn candidate_type(&self) -> CandidateType {
self.candidate_type
}
fn tcp_type(&self) -> TcpType {
self.tcp_type
}
/// Returns the string representation of the ICECandidate.
fn marshal(&self) -> String {
let mut val = format!(
"{} {} {} {} {} {} typ {}",
self.foundation(),
self.component(),
self.network_type().network_short(),
self.priority(),
self.address(),
self.port(),
self.candidate_type()
);
if self.tcp_type != TcpType::Unspecified {
val += format!(" tcptype {}", self.tcp_type()).as_str();
}
if let Some(related_address) = self.related_address() {
val += format!(
" raddr {} rport {}",
related_address.address, related_address.port,
)
.as_str();
}
val
}
async fn addr(&self) -> SocketAddr {
let resolved_addr = self.resolved_addr.lock().await;
*resolved_addr
}
/// Stops the recvLoop.
async fn close(&self) -> Result<(), Error> {
{
let mut closed_ch = self.closed_ch.lock().await;
if closed_ch.is_none() {
return Err(ERR_CLOSED.to_owned());
}
closed_ch.take();
}
if let Some(relay_client) = &self.relay_client {
relay_client.close().await
} else {
Ok(())
}
}
fn seen(&self, outbound: bool) {
let d = match SystemTime::now().duration_since(UNIX_EPOCH) {
Ok(d) => d,
Err(_) => Duration::from_secs(0),
};
if outbound {
self.set_last_sent(d);
} else {
self.set_last_received(d);
}
}
async fn write_to(
&self,
raw: &[u8],
dst: &(dyn Candidate + Send + Sync),
) -> Result<usize, Error> {
let n = if let Some(conn) = &self.conn {
let addr = dst.addr().await;
conn.send_to(raw, addr).await?
} else {
0
};
self.seen(true);
Ok(n)
}
/// Used to compare two candidateBases.
fn equal(&self, other: &dyn Candidate) -> bool {
self.network_type() == other.network_type()
&& self.candidate_type() == other.candidate_type()
&& self.address() == other.address()
&& self.port() == other.port()
&& self.tcp_type() == other.tcp_type()
&& self.related_address() == other.related_address()
}
async fn set_ip(&self, ip: &IpAddr) -> Result<(), Error> {
let network_type = determine_network_type(&self.network, ip)?;
self.network_type
.store(network_type as u8, Ordering::SeqCst);
let mut resolved_addr = self.resolved_addr.lock().await;
*resolved_addr = create_addr(network_type, *ip, self.port);
Ok(())
}
fn get_conn(&self) -> Option<&Arc<dyn util::Conn + Send + Sync>> {
self.conn.as_ref()
}
fn get_agent(&self) -> Option<&Arc<Mutex<AgentInternal>>> {
self.agent_internal.as_ref()
}
fn get_closed_ch(&self) -> Arc<Mutex<Option<broadcast::Sender<()>>>> {
self.closed_ch.clone()
}
}
impl CandidateBase {
pub fn set_last_received(&self, d: Duration) {
#[allow(clippy::cast_possible_truncation)]
self.last_received
.store(d.as_nanos() as u64, Ordering::SeqCst);
}
pub fn set_last_sent(&self, d: Duration) {
#[allow(clippy::cast_possible_truncation)]
self.last_sent.store(d.as_nanos() as u64, Ordering::SeqCst);
}
/// Returns the local preference for this candidate.
pub fn local_preference(&self) -> u16 {
if self.network_type().is_tcp() {
// RFC 6544, section 4.2
//
// In Section 4.1.2.1 of [RFC5245], a recommended formula for UDP ICE
// candidate prioritization is defined. For TCP candidates, the same
// formula and candidate type preferences SHOULD be used, and the
// RECOMMENDED type preferences for the new candidate types defined in
// this document (see Section 5) are 105 for NAT-assisted candidates and
// 75 for UDP-tunneled candidates.
//
// (...)
//
// With TCP candidates, the local preference part of the recommended
// priority formula is updated to also include the directionality
// (active, passive, or simultaneous-open) of the TCP connection. The
// RECOMMENDED local preference is then defined as:
//
// local preference = (2^13) * direction-pref + other-pref
//
// The direction-pref MUST be between 0 and 7 (both inclusive), with 7
// being the most preferred. The other-pref MUST be between 0 and 8191
// (both inclusive), with 8191 being the most preferred. It is
// RECOMMENDED that the host, UDP-tunneled, and relayed TCP candidates
// have the direction-pref assigned as follows: 6 for active, 4 for
// passive, and 2 for S-O. For the NAT-assisted and server reflexive
// candidates, the RECOMMENDED values are: 6 for S-O, 4 for active, and
// 2 for passive.
//
// (...)
//
// If any two candidates have the same type-preference and direction-
// pref, they MUST have a unique other-pref. With this specification,
// this usually only happens with multi-homed hosts, in which case
// other-pref is the preference for the particular IP address from which
// the candidate was obtained. When there is only a single IP address,
// this value SHOULD be set to the maximum allowed value (8191).
let other_pref: u16 = 8191;
let direction_pref: u16 = match self.candidate_type() {
CandidateType::Host | CandidateType::Relay => match self.tcp_type() {
TcpType::Active => 6,
TcpType::Passive => 4,
TcpType::SimultaneousOpen => 2,
TcpType::Unspecified => 0,
},
CandidateType::PeerReflexive | CandidateType::ServerReflexive => {
match self.tcp_type() {
TcpType::SimultaneousOpen => 6,
TcpType::Active => 4,
TcpType::Passive => 2,
TcpType::Unspecified => 0,
}
}
CandidateType::Unspecified => 0,
};
(1 << 13) * direction_pref + other_pref
} else {
DEFAULT_LOCAL_PREFERENCE
}
}
pub(crate) async fn recv_loop(
candidate: Arc<dyn Candidate + Send + Sync>,
agent_internal: Arc<Mutex<AgentInternal>>,
mut closed_ch_rx: broadcast::Receiver<()>,
initialized_ch: Option<broadcast::Receiver<()>>,
conn: Arc<dyn util::Conn + Send + Sync>,
addr: SocketAddr,
) -> Result<(), Error> {
if let Some(mut initialized_ch) = initialized_ch {
tokio::select! {
_ = initialized_ch.recv() => {}
_ = closed_ch_rx.recv() => return Err(ERR_CLOSED.to_owned()),
}
}
let mut buffer = vec![0_u8; RECEIVE_MTU];
let mut n;
let mut src_addr;
loop {
tokio::select! {
result = conn.recv_from(&mut buffer) => {
match result {
Ok((num, src)) => {
n = num;
src_addr = src;
}
Err(err) => return Err(Error::new(err.to_string())),
}
},
_ = closed_ch_rx.recv() => return Err(ERR_CLOSED.to_owned()),
}
Self::handle_inbound_candidate_msg(
&candidate,
&agent_internal,
&buffer[..n],
src_addr,
addr,
)
.await;
}
}
async fn handle_inbound_candidate_msg(
c: &Arc<dyn Candidate + Send + Sync>,
agent_internal: &Arc<Mutex<AgentInternal>>,
buf: &[u8],
src_addr: SocketAddr,
addr: SocketAddr,
) {
if stun::message::is_message(buf) {
let mut m = Message {
raw: vec![],
..Message::default()
};
// Explicitly copy raw buffer so Message can own the memory.
m.raw.extend_from_slice(buf);
if let Err(err) = m.decode() {
log::warn!(
"Failed to handle decode ICE from {} to {}: {}",
addr,
src_addr,
err
);
} else {
let agent_internal_clone = Arc::clone(agent_internal);
let mut ai = agent_internal.lock().await;
ai.handle_inbound(&mut m, c, src_addr, agent_internal_clone)
.await;
}
} else {
let ai = agent_internal.lock().await;
if !ai.validate_non_stun_traffic(c, src_addr).await {
log::warn!(
"Discarded message from {}, not a valid remote candidate",
c.addr().await
);
} else if let Err(err) = ai.agent_conn.buffer.write(buf).await {
// NOTE This will return packetio.ErrFull if the buffer ever manages to fill up.
log::warn!("failed to write packet: {}", err);
}
}
}
}
|
use anchor_lang::prelude::*;
declare_id!("Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS");
#[program]
pub mod test_recent_bh {
use super::*;
pub fn initialize(_ctx: Context<Initialize>) -> ProgramResult {
Ok(())
}
}
#[derive(Accounts)]
pub struct Initialize<'info> {
pub recent_blockhashes: Sysvar<'info, RecentBlockhashes>,
}
|
// Copyright 2021 Protocol Labs.
//
// 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 futures::executor::LocalPool;
use futures::future::FutureExt;
use futures::io::{AsyncRead, AsyncWrite};
use futures::stream::StreamExt;
use futures::task::Spawn;
use libp2p_core::multiaddr::{Multiaddr, Protocol};
use libp2p_core::muxing::StreamMuxerBox;
use libp2p_core::transport::upgrade::Version;
use libp2p_core::transport::{Boxed, MemoryTransport, OrTransport, Transport};
use libp2p_core::PublicKey;
use libp2p_core::{identity, PeerId};
use libp2p_dcutr as dcutr;
use libp2p_plaintext::PlainText2Config;
use libp2p_relay as relay;
use libp2p_swarm::{AddressScore, NetworkBehaviour, Swarm, SwarmEvent};
use std::time::Duration;
#[test]
fn connect() {
let _ = env_logger::try_init();
let mut pool = LocalPool::new();
let relay_addr = Multiaddr::empty().with(Protocol::Memory(rand::random::<u64>()));
let mut relay = build_relay();
let relay_peer_id = *relay.local_peer_id();
relay.listen_on(relay_addr.clone()).unwrap();
relay.add_external_address(relay_addr.clone(), AddressScore::Infinite);
spawn_swarm_on_pool(&pool, relay);
let mut dst = build_client();
let dst_peer_id = *dst.local_peer_id();
let dst_relayed_addr = relay_addr
.with(Protocol::P2p(relay_peer_id.into()))
.with(Protocol::P2pCircuit)
.with(Protocol::P2p(dst_peer_id.into()));
let dst_addr = Multiaddr::empty().with(Protocol::Memory(rand::random::<u64>()));
dst.listen_on(dst_relayed_addr.clone()).unwrap();
dst.listen_on(dst_addr.clone()).unwrap();
dst.add_external_address(dst_addr.clone(), AddressScore::Infinite);
pool.run_until(wait_for_reservation(
&mut dst,
dst_relayed_addr.clone(),
relay_peer_id,
false, // No renewal.
));
spawn_swarm_on_pool(&pool, dst);
let mut src = build_client();
let src_addr = Multiaddr::empty().with(Protocol::Memory(rand::random::<u64>()));
src.listen_on(src_addr.clone()).unwrap();
pool.run_until(wait_for_new_listen_addr(&mut src, &src_addr));
src.add_external_address(src_addr.clone(), AddressScore::Infinite);
src.dial(dst_relayed_addr.clone()).unwrap();
pool.run_until(wait_for_connection_established(&mut src, &dst_relayed_addr));
match pool.run_until(wait_for_dcutr_event(&mut src)) {
dcutr::Event::RemoteInitiatedDirectConnectionUpgrade {
remote_peer_id,
remote_relayed_addr,
} if remote_peer_id == dst_peer_id && remote_relayed_addr == dst_relayed_addr => {}
e => panic!("Unexpected event: {e:?}."),
}
pool.run_until(wait_for_connection_established(
&mut src,
&dst_addr.with(Protocol::P2p(dst_peer_id.into())),
));
}
fn build_relay() -> Swarm<relay::Behaviour> {
let local_key = identity::Keypair::generate_ed25519();
let local_public_key = local_key.public();
let local_peer_id = local_public_key.to_peer_id();
let transport = build_transport(MemoryTransport::default().boxed(), local_public_key);
Swarm::with_threadpool_executor(
transport,
relay::Behaviour::new(
local_peer_id,
relay::Config {
reservation_duration: Duration::from_secs(2),
..Default::default()
},
),
local_peer_id,
)
}
fn build_client() -> Swarm<Client> {
let local_key = identity::Keypair::generate_ed25519();
let local_public_key = local_key.public();
let local_peer_id = local_public_key.to_peer_id();
let (relay_transport, behaviour) = relay::client::new(local_peer_id);
let transport = build_transport(
OrTransport::new(relay_transport, MemoryTransport::default()).boxed(),
local_public_key,
);
Swarm::with_threadpool_executor(
transport,
Client {
relay: behaviour,
dcutr: dcutr::Behaviour::new(local_peer_id),
},
local_peer_id,
)
}
fn build_transport<StreamSink>(
transport: Boxed<StreamSink>,
local_public_key: PublicKey,
) -> Boxed<(PeerId, StreamMuxerBox)>
where
StreamSink: AsyncRead + AsyncWrite + Send + Unpin + 'static,
{
transport
.upgrade(Version::V1)
.authenticate(PlainText2Config { local_public_key })
.multiplex(libp2p_yamux::YamuxConfig::default())
.boxed()
}
#[derive(NetworkBehaviour)]
#[behaviour(
out_event = "ClientEvent",
event_process = false,
prelude = "libp2p_swarm::derive_prelude"
)]
struct Client {
relay: relay::client::Behaviour,
dcutr: dcutr::Behaviour,
}
#[derive(Debug)]
enum ClientEvent {
Relay(relay::client::Event),
Dcutr(dcutr::Event),
}
impl From<relay::client::Event> for ClientEvent {
fn from(event: relay::client::Event) -> Self {
ClientEvent::Relay(event)
}
}
impl From<dcutr::Event> for ClientEvent {
fn from(event: dcutr::Event) -> Self {
ClientEvent::Dcutr(event)
}
}
fn spawn_swarm_on_pool<B: NetworkBehaviour + Send>(pool: &LocalPool, swarm: Swarm<B>) {
pool.spawner()
.spawn_obj(swarm.collect::<Vec<_>>().map(|_| ()).boxed().into())
.unwrap();
}
async fn wait_for_reservation(
client: &mut Swarm<Client>,
client_addr: Multiaddr,
relay_peer_id: PeerId,
is_renewal: bool,
) {
let mut new_listen_addr_for_relayed_addr = false;
let mut reservation_req_accepted = false;
loop {
match client.select_next_some().await {
SwarmEvent::NewListenAddr { address, .. } if address != client_addr => {}
SwarmEvent::NewListenAddr { address, .. } if address == client_addr => {
new_listen_addr_for_relayed_addr = true;
if reservation_req_accepted {
break;
}
}
SwarmEvent::Behaviour(ClientEvent::Relay(
relay::client::Event::ReservationReqAccepted {
relay_peer_id: peer_id,
renewal,
..
},
)) if relay_peer_id == peer_id && renewal == is_renewal => {
reservation_req_accepted = true;
if new_listen_addr_for_relayed_addr {
break;
}
}
SwarmEvent::Dialing(peer_id) if peer_id == relay_peer_id => {}
SwarmEvent::ConnectionEstablished { peer_id, .. } if peer_id == relay_peer_id => {}
e => panic!("{e:?}"),
}
}
}
async fn wait_for_connection_established(client: &mut Swarm<Client>, addr: &Multiaddr) {
loop {
match client.select_next_some().await {
SwarmEvent::IncomingConnection { .. } => {}
SwarmEvent::ConnectionEstablished { endpoint, .. }
if endpoint.get_remote_address() == addr =>
{
break
}
SwarmEvent::Dialing(_) => {}
SwarmEvent::Behaviour(ClientEvent::Relay(
relay::client::Event::OutboundCircuitEstablished { .. },
)) => {}
SwarmEvent::ConnectionEstablished { .. } => {}
e => panic!("{e:?}"),
}
}
}
async fn wait_for_new_listen_addr(client: &mut Swarm<Client>, new_addr: &Multiaddr) {
match client.select_next_some().await {
SwarmEvent::NewListenAddr { address, .. } if address == *new_addr => {}
e => panic!("{e:?}"),
}
}
async fn wait_for_dcutr_event(client: &mut Swarm<Client>) -> dcutr::Event {
loop {
match client.select_next_some().await {
SwarmEvent::Behaviour(ClientEvent::Dcutr(e)) => return e,
e => panic!("{e:?}"),
}
}
}
|
use lazy_static::lazy_static;
use crate::{cmap::StreamDescription, options::AuthMechanism};
use super::sasl::SaslStart;
lazy_static! {
static ref MECHS: [String; 2] = [
AuthMechanism::ScramSha1.as_str().to_string(),
AuthMechanism::ScramSha256.as_str().to_string()
];
}
#[test]
fn negotiate_both_scram() {
let description_both = StreamDescription {
sasl_supported_mechs: Some(MECHS.to_vec()),
..Default::default()
};
assert_eq!(
AuthMechanism::from_stream_description(&description_both),
AuthMechanism::ScramSha256
);
}
#[test]
fn negotiate_sha1_only() {
let description_sha1 = StreamDescription {
sasl_supported_mechs: Some(MECHS[0..=0].to_vec()),
..Default::default()
};
assert_eq!(
AuthMechanism::from_stream_description(&description_sha1),
AuthMechanism::ScramSha1
);
}
#[test]
fn negotiate_sha256_only() {
let description_sha256 = StreamDescription {
sasl_supported_mechs: Some(MECHS[1..=1].to_vec()),
..Default::default()
};
assert_eq!(
AuthMechanism::from_stream_description(&description_sha256),
AuthMechanism::ScramSha256
);
}
#[test]
fn negotiate_none() {
let description_none: StreamDescription = Default::default();
assert_eq!(
AuthMechanism::from_stream_description(&description_none),
AuthMechanism::ScramSha1
);
}
#[test]
fn negotiate_mangled() {
let description_mangled = StreamDescription {
sasl_supported_mechs: Some(["NOT A MECHANISM".to_string(), "OTHER".to_string()].to_vec()),
..Default::default()
};
assert_eq!(
AuthMechanism::from_stream_description(&description_mangled),
AuthMechanism::ScramSha1
);
}
fn scram_sasl_first_options(mechanism: AuthMechanism) {
let sasl_first = SaslStart::new(String::new(), mechanism, Vec::new(), None);
let command = sasl_first.into_command();
let options = match command.body.get_document("options") {
Ok(options) => options,
Err(_) => panic!("SaslStart should contain options document"),
};
match options.get_bool("skipEmptyExchange") {
Ok(skip_empty_exchange) => assert!(
skip_empty_exchange,
"skipEmptyExchange should be true for SCRAM authentication"
),
Err(_) => panic!("SaslStart options should contain skipEmptyExchange"),
}
}
#[test]
fn sasl_first_options_specified() {
scram_sasl_first_options(AuthMechanism::ScramSha1);
scram_sasl_first_options(AuthMechanism::ScramSha256);
}
#[test]
fn sasl_first_options_not_specified() {
let sasl_first = SaslStart::new(String::new(), AuthMechanism::MongoDbX509, Vec::new(), None);
let command = sasl_first.into_command();
assert!(
command.body.get_document("options").is_err(),
"SaslStart should not contain options document for X.509 authentication"
);
}
|
mod mbc0;
mod mbc1;
mod mbc3;
use std::fs::File;
use std::io::Read;
pub trait Cartridge {
fn read_rom(&self, addr: u16) -> u8;
fn read_ram(&self, addr: u16) -> u8;
fn write_rom(&mut self, addr: u16, value: u8);
fn write_ram(&mut self, addr: u16, value: u8);
}
pub fn new(rom_name: &str) -> Box<Cartridge> {
let mut rom = vec![];
let _ = File::open(rom_name)
.expect("Could not read ROM file")
.read_to_end(&mut rom);
match rom[0x147] {
0x00 => Box::new(mbc0::new(rom)),
0x01...0x03 => Box::new(mbc1::new(rom)),
0x08...0x0d => Box::new(mbc0::new(rom)),
0x0f...0x13 => Box::new(mbc3::new(rom)),
_ => panic!("Unsupported cartridge type"),
}
}
|
use super::{chunk_header::*, chunk_type::*, *};
use bytes::{Buf, BufMut, Bytes, BytesMut};
use std::fmt;
///This chunk shall be used by the data sender to inform the data
///receiver to adjust its cumulative received TSN point forward because
///some missing TSNs are associated with data chunks that SHOULD NOT be
///transmitted or retransmitted by the sender.
/// 0 1 2 3
/// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
///| Type = 192 | Flags = 0x00 | Length = Variable |
///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
///| New Cumulative TSN |
///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
///| Stream-1 | Stream Sequence-1 |
///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
///| |
///| |
///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
///| Stream-N | Stream Sequence-N |
///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
#[derive(Default, Debug, Clone)]
pub(crate) struct ChunkForwardTsn {
/// This indicates the new cumulative TSN to the data receiver. Upon
/// the reception of this value, the data receiver MUST consider
/// any missing TSNs earlier than or equal to this value as received,
/// and stop reporting them as gaps in any subsequent SACKs.
pub(crate) new_cumulative_tsn: u32,
pub(crate) streams: Vec<ChunkForwardTsnStream>,
}
pub(crate) const NEW_CUMULATIVE_TSN_LENGTH: usize = 4;
pub(crate) const FORWARD_TSN_STREAM_LENGTH: usize = 4;
/// makes ChunkForwardTsn printable
impl fmt::Display for ChunkForwardTsn {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut res = vec![self.header().to_string()];
res.push(format!("New Cumulative TSN: {}", self.new_cumulative_tsn));
for s in &self.streams {
res.push(format!(" - si={}, ssn={}", s.identifier, s.sequence));
}
write!(f, "{}", res.join("\n"))
}
}
impl Chunk for ChunkForwardTsn {
fn header(&self) -> ChunkHeader {
ChunkHeader {
typ: CT_FORWARD_TSN,
flags: 0,
value_length: self.value_length() as u16,
}
}
fn unmarshal(buf: &Bytes) -> Result<Self, Error> {
let header = ChunkHeader::unmarshal(buf)?;
if header.typ != CT_FORWARD_TSN {
return Err(Error::ErrChunkTypeNotForwardTsn);
}
let mut offset = CHUNK_HEADER_SIZE + NEW_CUMULATIVE_TSN_LENGTH;
if buf.len() < offset {
return Err(Error::ErrChunkTooShort);
}
let reader = &mut buf.slice(CHUNK_HEADER_SIZE..CHUNK_HEADER_SIZE + header.value_length());
let new_cumulative_tsn = reader.get_u32();
let mut streams = vec![];
let mut remaining = buf.len() - offset;
while remaining > 0 {
let s = ChunkForwardTsnStream::unmarshal(
&buf.slice(offset..CHUNK_HEADER_SIZE + header.value_length()),
)?;
offset += s.value_length();
remaining -= s.value_length();
streams.push(s);
}
Ok(ChunkForwardTsn {
new_cumulative_tsn,
streams,
})
}
fn marshal_to(&self, writer: &mut BytesMut) -> Result<usize, Error> {
self.header().marshal_to(writer)?;
writer.put_u32(self.new_cumulative_tsn);
for s in &self.streams {
writer.extend(s.marshal()?);
}
Ok(writer.len())
}
fn check(&self) -> Result<(), Error> {
Ok(())
}
fn value_length(&self) -> usize {
NEW_CUMULATIVE_TSN_LENGTH + FORWARD_TSN_STREAM_LENGTH * self.streams.len()
}
fn as_any(&self) -> &(dyn Any + Send + Sync) {
self
}
}
#[derive(Debug, Clone)]
pub(crate) struct ChunkForwardTsnStream {
/// This field holds a stream number that was skipped by this
/// FWD-TSN.
pub(crate) identifier: u16,
/// This field holds the sequence number associated with the stream
/// that was skipped. The stream sequence field holds the largest
/// stream sequence number in this stream being skipped. The receiver
/// of the FWD-TSN's can use the Stream-N and Stream Sequence-N fields
/// to enable delivery of any stranded TSN's that remain on the stream
/// re-ordering queues. This field MUST NOT report TSN's corresponding
/// to DATA chunks that are marked as unordered. For ordered DATA
/// chunks this field MUST be filled in.
pub(crate) sequence: u16,
}
/// makes ChunkForwardTsnStream printable
impl fmt::Display for ChunkForwardTsnStream {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}, {}", self.identifier, self.sequence)
}
}
impl Chunk for ChunkForwardTsnStream {
fn header(&self) -> ChunkHeader {
ChunkHeader {
typ: ChunkType(0),
flags: 0,
value_length: self.value_length() as u16,
}
}
fn unmarshal(buf: &Bytes) -> Result<Self, Error> {
if buf.len() < FORWARD_TSN_STREAM_LENGTH {
return Err(Error::ErrChunkTooShort);
}
let reader = &mut buf.clone();
let identifier = reader.get_u16();
let sequence = reader.get_u16();
Ok(ChunkForwardTsnStream {
identifier,
sequence,
})
}
fn marshal_to(&self, writer: &mut BytesMut) -> Result<usize, Error> {
writer.put_u16(self.identifier);
writer.put_u16(self.sequence);
Ok(writer.len())
}
fn check(&self) -> Result<(), Error> {
Ok(())
}
fn value_length(&self) -> usize {
FORWARD_TSN_STREAM_LENGTH
}
fn as_any(&self) -> &(dyn Any + Send + Sync) {
self
}
}
|
fn main() {
let one_thousand = 1e3;
let one_million = 1e6;
let thirteen_billions_and_half = 13.5e9;
let twelve_millionths = 12e-6;
println!("{}\n{}\n{}\n{}",
one_thousand,
one_million,
thirteen_billions_and_half,
twelve_millionths);
}
|
#[macro_use]
extern crate syn;
extern crate proc_macro;
mod impls;
#[proc_macro_attribute]
pub fn parameterized(
args: ::proc_macro::TokenStream,
input: ::proc_macro::TokenStream,
) -> ::proc_macro::TokenStream {
impl_macro(args, input)
}
fn impl_macro(
args: ::proc_macro::TokenStream,
input: ::proc_macro::TokenStream,
) -> ::proc_macro::TokenStream {
let argument_lists = parse_macro_input!(args as impls::AttributeArgList);
let func = parse_macro_input!(input as ::syn::ItemFn);
impls::restructure::generate_test_cases(argument_lists, func)
}
|
use approx::{abs_diff_eq};
use lazy_static::lazy_static;
use ndarray::{arr2, s, stack, Array2, ArrayView2, Axis};
use rayon::prelude::*;
type M2 = Array2<f64>;
lazy_static! {
static ref LEVEL_26_ANSWER: M2 = arr2(&[
#[allow(clippy::unreadable_literal)]
[0.6106926463383254, -0.7918677236182143, 102.80083691920044],
#[allow(clippy::unreadable_literal)]
[0.7918677236182146, 0.6106926463383255, 46.69157747803904]
]);
static ref LEVEL_24_ANSWER: M2 = arr2(&[
#[allow(clippy::unreadable_literal)]
[-0.24615384615384622, -0.9692307692307695, 76.15384615384615],
#[allow(clippy::unreadable_literal)]
[0.9692307692307695, -0.24615384615384622, 76.76923076923077]
]);
static ref IDENTITY2: M2 = arr2(&[[1., 0.], [0., 1.]]);
static ref IDENTITY3: M2 = arr2(&[[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]]);
}
const LEVEL_24_LINES: [[isize; 4]; 4] = [
[20, 0, 0, 100],
[50, 0, 0, 100],
[10, 0, 90, 70],
[0, 70, 100, -50],
];
const LEVEL_26_LINES: [[isize; 4]; 4] = [
[0, 10, 50, 90],
[50, 0, 0, 100],
[0, 60, 100, 0],
[0, 40, 100, -10],
];
// this isn't threads, rayon manages threads, it's just a workaround for
// no infinities
const CHUNKS: usize = 64;
const EPSILON: f64 = 64. * f64::EPSILON;
fn super_floor(a: usize, b: usize) -> usize {
let floor = a / b;
if floor * b == a {
floor - 1
} else {
floor
}
}
// this is by a still brute force, slightly more mathematically informed
// strategy
// k only necessary to include zeroes for convenience
fn factoradic_string(mut m: usize, k: usize) -> Vec<usize> {
let mut string = vec![];
for rad in 1..=k {
let quot = m / rad;
let rem = m - quot * rad;
string.push(rem);
m = quot;
}
string.into_iter().rev().collect()
}
fn factorial(n: usize) -> usize {
if n <= 1 {
1
} else {
n * factorial(n - 1)
}
}
fn lehmer_code<T>(i: usize, mut poss: Vec<T>) -> Vec<T> {
let mut combo = vec![];
for digit in factoradic_string(i, poss.len()) {
let element = poss.remove(digit);
combo.push(element);
}
combo
}
fn pair_combos(num_lines: usize) -> Vec<(usize, usize)> {
let mut combos = vec![];
for i in 0..num_lines {
for j in 0..num_lines {
if i != j {
combos.push((i, j));
}
}
}
combos
}
// based off biject but with changing k
// https://en.wikipedia.org/wiki/Bijective_numeration
fn triangle_string(m: usize, mut k: usize) -> Vec<usize> {
if m == 0 {
return vec![];
}
let mut string = vec![];
let mut qn = m;
while qn != 0 {
// divide value
let qn_inc = super_floor(qn, k);
// mod value
let an_inc = qn - qn_inc * k;
qn = qn_inc;
k = an_inc;
string.push(an_inc - 1); // from 0 (the zero part of the name)
}
string.into_iter().rev().collect()
}
fn square(mat: &M2) -> ArrayView2<f64> {
mat.slice(s![0..=1, 0..=1])
}
fn extend(mat: &M2) -> M2 {
stack!(Axis(0), mat.view(), arr2(&[[0., 0., 1.]]))
}
fn check_combo(combo: &[usize], mats: &[M2], answer: &M2) -> bool {
let mut matrix = IDENTITY2.clone();
for ind in combo {
matrix = square(&mats[*ind]).dot(&matrix)
}
abs_diff_eq!(&matrix, answer, epsilon = EPSILON)
}
fn permutations(pairs: &[(usize, usize)], mats: &[&M2], answer: M2) -> Vec<Vec<usize>> {
// every permutation of pairs
// even though we properly paralellize combinations this ends up being
// the slower part of the process so we want to parallel it too
(0..factorial(pairs.len())).into_iter().filter_map(|i| {
let mut matrix = IDENTITY3.clone();
let seq = lehmer_code(i, (0..pairs.len()).collect());
for i in &seq {
matrix = mats[*i].dot(&matrix);
}
println!("com {:?}\n{}\n{}\n--------------", seq, matrix, answer);
if abs_diff_eq!(matrix, answer, epsilon = EPSILON) {
Some(seq.into_iter()
.flat_map(|ind| vec![pairs[ind].0, pairs[ind].1])
.collect())
} else {
None
}
}).collect()
}
fn pair_to_mat(x: &(usize, usize), lines: [[isize; 4]; 4]) -> M2 {
extend(&get_reflection_matrix(&lines[x.1]))
.dot(&extend(&get_reflection_matrix(&lines[x.0])))
}
fn main() {
const LINES: [[isize; 4]; 4] = LEVEL_26_LINES;
let answer = &LEVEL_26_ANSWER;
let pairs = pair_combos(LINES.len());
let mats: Vec<M2> = pairs
.iter()
.map(|pair| pair_to_mat(pair, LINES))
.collect();
let square_answer = square(&answer).to_owned();
for i in (0..).step_by(CHUNKS) {
(i..i + CHUNKS).into_par_iter().for_each(|i| {
let combo = triangle_string(i, 12);
if check_combo(&combo, &mats, &square_answer) {
let as_pairs: Vec<(usize, usize)> = combo.iter().map(|ind| pairs[*ind]).collect();
let as_mats: Vec<&M2> = combo.iter().map(|ind| &mats[*ind]).collect();
println!("naive combo found: {:?}", as_pairs);
let permutes = permutations(&as_pairs, &as_mats, extend(&answer));
if permutes.len() != 0 {
println!("true solutions {:?}", permutes);
println!("---------------------------------------------");
}
}
});
}
}
// translated from game.js
fn get_reflection_matrix(line: &[isize]) -> M2 {
match slope(line) {
Some(m) if m != 0. => {
let b = line[1] as f64 - m * line[0] as f64;
let q1 = m + (1. / m);
let q2 = 1. + m * m;
// Matricized version of http://martin-thoma.com/reflecting-a-point-over-a-line/
// 1 3 5
// 2 4 6
arr2(&[
[2. / m / q1 - 1., 2. / q1, -2. * b / q1],
[2. * m / q2, 2. * m * m / q2 - 1., 2. * b / q2],
])
}
None => {
// Vertical line flip
arr2(&[[-1., 0., 2. * line[0] as f64], [0., 1., 0.]])
}
Some(_) => {
// Horizontal line flip
arr2(&[[1., 0., 0.], [0., -1., 2. * line[1] as f64]])
}
}
}
fn slope(line: &[isize]) -> Option<f64> {
if line[2] == 0 {
None
} else {
Some(line[3] as f64 / line[2] as f64)
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn check_combo_24_known() {
const SOLN: [usize; 6] = [1, 3, 2, 0, 3, 0];
let mats: Vec<M2> = LEVEL_24_LINES
.iter()
.map(|line| get_reflection_matrix(line))
.collect();
assert!(check_combo(
&SOLN,
&mats,
&square(&LEVEL_24_ANSWER).to_owned()
));
}
#[test]
fn check_permute_24_known() {
let pairs = [(1, 3), (2, 0), (3, 0)];
let mats: Vec<M2> = pairs.iter().map(|pair| pair_to_mat(pair, LEVEL_24_LINES)).collect();
let mats_ref: Vec<&M2> = mats.iter().map(|x| x).collect();
assert_eq!(permutations(
&pairs,
&mats_ref,
extend(&LEVEL_24_ANSWER),
), [[1, 3, 2, 0, 3, 0]]);
}
#[test]
fn level_26_redundant_combo() {
const SOLN: [usize; 16] = [0, 1, 1, 0, 0, 3, 2, 0, 2, 0, 2, 0, 2, 0, 0, 1];
//const SOLN: [usize; 14] = [0, 3, 2, 0, 2, 0, 2, 0, 2, 1]
//const SOLN: [usize; 14] = [0, 1, 1, 0, 0, 3, 2, 0, 2, 0, 2, 0, 1, 2]
//const SOLN: [usize; 10] = [0, 3, 2, 0, 2, 0, 2, 0, 1, 2]
let mats: Vec<M2> = LEVEL_26_LINES
.iter()
.map(|line| get_reflection_matrix(line))
.collect();
assert!(check_combo(
&SOLN,
&mats,
&square(&LEVEL_26_ANSWER).to_owned()
));
}
#[test]
fn level_26_failed_10_move_combo() {
const MISSED_SOLN: [usize; 10] = [0, 3, 2, 0, 2, 0, 2, 0, 2, 1];
let mats: Vec<M2> = LEVEL_26_LINES
.iter()
.map(|line| get_reflection_matrix(line))
.collect();
assert!(check_combo(
&MISSED_SOLN,
&mats,
&square(&LEVEL_26_ANSWER).to_owned()
));
}
#[test]
fn level_26_failed_10_move_permute() {
const PAIRS: [(usize, usize); 5] = [(0, 3), (2, 0), (2, 0), (2, 0), (2, 1)];
let mats: Vec<M2> = PAIRS.iter().map(|pair| pair_to_mat(pair, LEVEL_26_LINES)).collect();
let mats_ref: Vec<&M2> = mats.iter().map(|x| x).collect();
assert!(permutations(
&PAIRS,
&mats_ref,
extend(&LEVEL_26_ANSWER),
).len() > 0);
}
#[test]
fn eqs() {
let a: M2 = arr2(&[[0.6106926463383254, -0.7918677236182144, 102.80083691920042],
[0.7918677236182146, 0.6106926463383255, 46.69157747803905],
[0., 0., 1.]]);
let b: M2 = arr2(&[[0.6106926463383254, -0.7918677236182143, 102.80083691920044],
[0.7918677236182146, 0.6106926463383255, 46.69157747803904],
[0., 0., 1.]]);
assert!(abs_diff_eq!(a, b, epsilon = EPSILON));
}
#[test]
fn eqs_adjusted() {
// adjusted to be exactly-equal
let a: M2 = arr2(&[[0.6106926463383254, -0.7918677236182143, 102.80083691920044],
[0.7918677236182146, 0.6106926463383255, 46.69157747803904],
[0., 0., 1.]]);
let b: M2 = arr2(&[[0.6106926463383254, -0.7918677236182143, 102.80083691920044],
[0.7918677236182146, 0.6106926463383255, 46.69157747803904],
[0., 0., 1.]]);
assert!(abs_diff_eq!(a, b, epsilon = EPSILON));
}
}
|
#[repr(C)]
struct Eye {
current_facing_dir: Direction
}
impl Eye {
pub fn new(facing_dir: Direction) -> {
Eye {
current_facing_dir = facing_dir
}
}
pub fn turn(&mut self, degrees_to_right: f32) {
self.current_facing_dir = /**/;
unimplemented!();
}
pub fn get_near_objects() -> Vec<(Coord,EntityType)> {
// Don't implement now, not needed
unimplemented!();
}
pub fn find_near_humans() -> Vec<Coord> {
/*
* See 120 degree in front (ie. till 60 degree on both side)
**/
unimplemented!();
}
}
|
pub mod davidson;
|
use super::{Subsystem, WebsocketSystem};
use crate::error::error_chain_fmt;
use anyhow::Context;
use glob::glob;
use serde::Deserialize;
use std::path::Path;
#[derive(thiserror::Error)]
pub enum PythonRepoError {
#[error("Invalid path: {0:?}")]
InvalidPath(String),
#[error(transparent)]
UnexpectedError(#[from] anyhow::Error),
}
impl std::fmt::Debug for PythonRepoError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
error_chain_fmt(self, f)
}
}
pub struct PythonRepoSystem;
#[async_trait::async_trait]
impl Subsystem for PythonRepoSystem {
type Error = PythonRepoError;
type Task = Task;
fn system(&self) -> WebsocketSystem {
WebsocketSystem::PythonRepo
}
#[tracing::instrument(name = "Handling PythonRepo message", skip(self))]
async fn handle_message(
&self,
task: Self::Task,
payload: serde_json::Value,
) -> Result<serde_json::Value, Self::Error> {
match task {
Task::GetFiles => get_files(payload),
}
}
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Task {
GetFiles,
}
#[tracing::instrument(name = "GetFiles task")]
fn get_files(payload: serde_json::Value) -> Result<serde_json::Value, PythonRepoError> {
let path = payload.as_str().unwrap_or("");
if !Path::new(path).exists() {
return Err(PythonRepoError::InvalidPath(path.into()));
}
let files = glob(&format!("{}/**/*.py", path))
.context("Failed to perform glob on path.")?
.filter_map(Result::ok)
.collect::<Vec<_>>();
let result =
serde_json::to_value(files).context("Failed to convert message to JSON format.")?;
Ok(result)
}
|
//! A thin wrapper around [`text_size`] to add some helper functions and types.
#![deny(clippy::pedantic, missing_debug_implementations, missing_docs, rust_2018_idioms)]
pub use text_size::{TextLen, TextRange, TextSize};
/// A value located in a text file.
#[derive(Debug, Clone, Copy)]
pub struct WithRange<T> {
/// The value.
pub val: T,
/// The location.
pub range: text_size::TextRange,
}
impl<T> WithRange<T> {
/// Wrap a new value with the location from `self`.
pub fn wrap<U>(&self, val: U) -> WithRange<U> {
WithRange { val, range: self.range }
}
}
/// Make a text size or panic. Panics if the usize overflows a u32.
#[must_use]
pub fn mk_text_size(n: usize) -> TextSize {
TextSize::try_from(n).expect("could not make text size")
}
|
use std::error::Error;
use std::fmt::Display;
/// # The error type for encoding
#[derive(Debug)]
pub enum EncodingError {
/// An invalid app segment number has been used
InvalidAppSegment(u8),
/// App segment exceeds maximum allowed data length
AppSegmentTooLarge(usize),
/// Color profile exceeds maximum allowed data length
IccTooLarge(usize),
/// Image data is too short
BadImageData { length: usize, required: usize },
/// Width or height is zero
ZeroImageDimensions { width: u16, height: u16 },
/// An io error occurred during writing
IoError(std::io::Error),
}
impl From<std::io::Error> for EncodingError {
fn from(err: std::io::Error) -> EncodingError {
EncodingError::IoError(err)
}
}
impl Display for EncodingError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
use EncodingError::*;
match self {
InvalidAppSegment(nr) => write!(
f,
"Invalid app segment number: {}",
nr
),
AppSegmentTooLarge(length) => write!(
f,
"App segment exceeds maximum allowed data length of 65533: {}",
length
),
IccTooLarge(length) => write!(
f,
"ICC profile exceeds maximum allowed data length: {}",
length
),
BadImageData { length, required } => write!(
f,
"Image data too small for dimensions and color_type: {} need at least {}",
length,
required
),
ZeroImageDimensions { width, height } => write!(
f,
"Image dimensions must be non zero: {}x{}",
width,
height
),
IoError(err) => err.fmt(f),
}
}
}
impl Error for EncodingError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
EncodingError::IoError(err) => Some(err),
_ => None
}
}
}
|
extern crate getopts;
extern crate termios;
extern crate libc;
extern crate unicode_width;
use std::env;
use std::io;
use getopts::Options;
use input::{InputHandler, PosixInputHandler, DefaultInputHandler};
use input::InputCmd;
use interpreter::Interpreter;
mod parser;
mod ast;
mod errors;
mod interpreter;
mod lexer;
mod token;
mod input;
const PROG_NAME: &'static str = "calcr";
const VERSION: &'static str = "v0.7.0";
#[cfg(unix)]
type TargetInputHandler = PosixInputHandler;
#[cfg(windows)]
type TargetInputHandler = DefaultInputHandler;
fn main() {
let args: Vec<String> = env::args().collect();
let mut opts = Options::new();
opts.optflag("v", "version", "print the program version");
opts.optflag("h", "help", "print this and then exit");
let matches = match opts.parse(&args[1..]) {
Ok(m) => m,
Err(e) => {
println!("{}", e.to_string());
return;
}
};
if matches.opt_present("h") {
println!("calcr - a small commandline calculator");
print_usage(opts);
} else if matches.opt_present("v") {
print_version();
} else if !matches.free.is_empty() {
let mut interp = Interpreter::new();
for eq in matches.free {
match interp.eval_expression(&eq) {
Ok(Some(num)) => println!("{}", num),
Err(e) => {
println!("{}", e);
e.print_location_highlight(&eq, true);
},
_ => {}, // do nothing
}
}
} else {
run_enviroment(TargetInputHandler::new()).ok().unwrap(); // TODO: Deal with the error case
}
}
fn run_enviroment<H: InputHandler>(mut ih: H) -> io::Result<()> {
try!(ih.start());
print_version();
let mut interp = Interpreter::new();
loop {
ih.print_prompt();
match ih.handle_input() {
InputCmd::Quit => break,
InputCmd::Equation(eq) => {
match interp.eval_expression(&eq) {
Ok(Some(num)) => println!("{}", num.to_string()),
Err(e) => {
e.print_location_highlight(&eq, false);
println!("{}", e);
},
_ => {} // do nothing
}
},
InputCmd::None => {} // do nothing
}
}
println!(""); // an extra newline to make sure the terminal looks tidy
Ok(())
}
fn print_usage(opts: Options) {
let brief = format!("Usage:\n {} [options...] [equation...]", PROG_NAME);
println!("{}", opts.usage(&brief));
}
fn print_version() {
println!("{} {}", PROG_NAME, VERSION);
} |
// Copyright 2020 The VectorDB Authors.
//
// Code is licensed under Apache License, Version 2.0.
mod tests;
pub mod binary;
pub mod constant;
pub mod expression;
pub mod factory;
pub mod variable;
pub use binary::BinaryExpression;
pub use constant::ConstantExpression;
pub use expression::Expression;
pub use expression::IExpression;
pub use variable::VariableExpression;
|
mod lease_blob_options;
pub use self::lease_blob_options::{LeaseBlobOptions, LEASE_BLOB_OPTIONS_DEFAULT};
mod blob_block_type;
pub use self::blob_block_type::BlobBlockType;
mod block_list_type;
pub use self::block_list_type::BlockListType;
mod blob_block_with_size;
pub use self::blob_block_with_size::BlobBlockWithSize;
mod block_with_size_list;
pub use self::block_with_size_list::BlockWithSizeList;
mod block_list;
pub use self::block_list::BlockList;
pub mod requests;
pub mod responses;
use crate::headers::CONTENT_CRC64;
use crate::{
headers::{CONTENT_MD5, COPY_ID},
ConsistencyCRC64, ConsistencyMD5,
};
use crate::{AccessTier, CopyId, CopyProgress};
use azure_core::headers::{
BLOB_SEQUENCE_NUMBER, BLOB_TYPE, COPY_COMPLETION_TIME, COPY_PROGRESS, COPY_SOURCE, COPY_STATUS,
COPY_STATUS_DESCRIPTION, CREATION_TIME, LEASE_DURATION, LEASE_STATE, LEASE_STATUS, META_PREFIX,
SERVER_ENCRYPTED,
};
use azure_core::{
lease::{LeaseDuration, LeaseState, LeaseStatus},
parsing::from_azure_time,
prelude::*,
util::HeaderMapExt,
};
use chrono::{DateTime, Utc};
use http::header;
use std::{collections::HashMap, convert::TryInto, str::FromStr};
#[cfg(feature = "azurite_workaround")]
fn get_creation_time(h: &header::HeaderMap) -> crate::Result<Option<DateTime<Utc>>> {
if let Some(creation_time) = h.get(CREATION_TIME) {
// Check that the creation time is valid
let creation_time = creation_time.to_str()?;
let creation_time = DateTime::parse_from_rfc2822(creation_time)?;
let creation_time = DateTime::from_utc(creation_time.naive_utc(), Utc);
Ok(Some(creation_time))
} else {
// Not having a creation time is ok
Ok(None)
}
}
create_enum!(
BlobType,
(BlockBlob, "BlockBlob"),
(PageBlob, "PageBlob"),
(AppendBlob, "AppendBlob")
);
create_enum!(
CopyStatus,
(Pending, "pending"),
(Success, "success"),
(Aborted, "aborted"),
(Failed, "failed")
);
create_enum!(RehydratePriority, (High, "High"), (Standard, "Standard"));
create_enum!(PageWriteType, (Update, "update"), (Clear, "clear"));
use serde::{self, Deserialize, Deserializer};
fn deserialize_crc64_optional<'de, D>(
deserializer: D,
) -> Result<Option<crate::ConsistencyCRC64>, D::Error>
where
D: Deserializer<'de>,
{
let s: Option<String> = Option::deserialize(deserializer)?;
s.filter(|s| !s.is_empty())
.map(crate::ConsistencyCRC64::decode)
.transpose()
.map_err(serde::de::Error::custom)
}
fn deserialize_md5_optional<'de, D>(
deserializer: D,
) -> Result<Option<crate::ConsistencyMD5>, D::Error>
where
D: Deserializer<'de>,
{
let s: Option<String> = Option::deserialize(deserializer)?;
s.filter(|s| !s.is_empty())
.map(crate::ConsistencyMD5::decode)
.transpose()
.map_err(serde::de::Error::custom)
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct Blob {
pub name: String,
pub snapshot: Option<DateTime<Utc>>,
pub version_id: Option<String>,
pub is_current_version: Option<bool>,
pub deleted: Option<bool>,
pub properties: BlobProperties,
pub metadata: Option<HashMap<String, String>>,
pub tags: Option<Tags>,
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct Tags {
pub tag_set: Option<TagSet>,
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct TagSet {
pub tag: Vec<Tag>,
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct Tag {
pub key: String,
pub value: String,
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct BlobProperties {
#[cfg(not(feature = "azurite_workaround"))]
#[serde(rename = "Creation-Time")]
#[serde(with = "azure_core::parsing::rfc2822_time_format")]
pub creation_time: DateTime<Utc>,
#[cfg(feature = "azurite_workaround")]
#[serde(rename = "Creation-Time")]
#[serde(with = "azure_core::parsing::rfc2822_time_format_optional")]
pub creation_time: Option<DateTime<Utc>>,
#[serde(rename = "Last-Modified")]
#[serde(with = "azure_core::parsing::rfc2822_time_format")]
pub last_modified: DateTime<Utc>,
#[serde(default)]
#[serde(with = "azure_core::parsing::rfc2822_time_format_optional")]
pub last_access_time: Option<DateTime<Utc>>,
pub etag: Etag,
#[serde(rename = "Content-Length")]
pub content_length: u64,
#[serde(rename = "Content-Type")]
pub content_type: String,
#[serde(rename = "Content-Encoding")]
pub content_encoding: Option<String>,
#[serde(rename = "Content-Language")]
pub content_language: Option<String>,
#[serde(rename = "Content-Disposition")]
pub content_disposition: Option<String>,
#[serde(rename = "Content-MD5")]
#[serde(default)]
#[serde(deserialize_with = "deserialize_md5_optional")]
pub content_md5: Option<ConsistencyMD5>,
#[serde(rename = "Content-CRC64")]
#[serde(default)]
#[serde(deserialize_with = "deserialize_crc64_optional")]
pub content_crc64: Option<ConsistencyCRC64>,
#[serde(rename = "Cache-Control")]
pub cache_control: Option<String>,
#[serde(rename = "x-ms-blob-sequence-number")]
pub blob_sequence_number: Option<u64>,
pub blob_type: BlobType,
pub access_tier: Option<AccessTier>,
#[serde(default)]
#[serde(with = "azure_core::parsing::rfc2822_time_format_optional")]
pub access_tier_change_time: Option<DateTime<Utc>>,
pub lease_status: LeaseStatus,
pub lease_state: LeaseState,
pub lease_duration: Option<LeaseDuration>,
pub copy_id: Option<CopyId>,
pub copy_status: Option<CopyStatus>,
pub copy_source: Option<String>,
pub copy_progress: Option<CopyProgress>,
#[serde(default)]
#[serde(with = "azure_core::parsing::rfc2822_time_format_optional")]
pub copy_completion_time: Option<DateTime<Utc>>,
pub copy_status_description: Option<String>,
pub server_encrypted: bool,
pub customer_provided_key_sha256: Option<String>,
pub encryption_scope: Option<String>,
pub incremental_copy: Option<bool>,
pub access_tier_inferred: Option<bool>,
#[serde(default)]
#[serde(with = "azure_core::parsing::rfc2822_time_format_optional")]
pub deleted_time: Option<DateTime<Utc>>,
pub remaining_retention_days: Option<u32>,
pub tag_count: Option<u32>,
pub rehydrate_priority: Option<RehydratePriority>,
#[serde(flatten)]
extra: HashMap<String, String>, // For debug purposes, should be compiled out in the future
}
impl Blob {
pub(crate) fn from_headers<BN: Into<String>>(
blob_name: BN,
h: &header::HeaderMap,
) -> crate::Result<Blob> {
trace!("\n{:?}", h);
#[cfg(not(feature = "azurite_workaround"))]
let creation_time = {
let creation_time = h
.get(CREATION_TIME)
.ok_or_else(|| crate::Error::HeaderNotFound(CREATION_TIME.to_owned()))?
.to_str()?;
let creation_time = DateTime::parse_from_rfc2822(creation_time)?;
let creation_time = DateTime::from_utc(creation_time.naive_utc(), Utc);
trace!("creation_time == {:?}", creation_time);
creation_time
};
#[cfg(feature = "azurite_workaround")]
let creation_time = get_creation_time(h)?;
let content_type = h
.get_as_string(header::CONTENT_TYPE)
.unwrap_or_else(|| "application/octet-stream".to_owned());
trace!("content_type == {:?}", content_type);
let content_length = h
.get(header::CONTENT_LENGTH)
.ok_or_else(|| {
static CL: header::HeaderName = header::CONTENT_LENGTH;
crate::Error::HeaderNotFound(CL.as_str().to_owned())
})?
.to_str()?
.parse::<u64>()?;
trace!("content_length == {:?}", content_length);
let last_modified = h.get_as_str(header::LAST_MODIFIED).ok_or_else(|| {
static LM: header::HeaderName = header::LAST_MODIFIED;
crate::Error::HeaderNotFound(LM.as_str().to_owned())
})?;
let last_modified = from_azure_time(last_modified)?;
trace!("last_modified == {:?}", last_modified);
let etag = h.get_as_string(header::ETAG).ok_or_else(|| {
static E: header::HeaderName = header::ETAG;
crate::Error::HeaderNotFound(E.as_str().to_owned())
})?;
let etag = etag.into();
trace!("etag == {:?}", etag);
let blob_sequence_number = h.get_as_u64(BLOB_SEQUENCE_NUMBER);
trace!("blob_sequence_number == {:?}", blob_sequence_number);
let blob_type = h
.get_as_str(BLOB_TYPE)
.ok_or_else(|| crate::Error::HeaderNotFound(BLOB_TYPE.to_owned()))?
.parse::<BlobType>()?;
trace!("blob_type == {:?}", blob_type);
let content_encoding = h.get_as_string(header::CONTENT_ENCODING);
trace!("content_encoding == {:?}", content_encoding);
let content_language = h.get_as_string(header::CONTENT_LANGUAGE);
trace!("content_language == {:?}", content_language);
let content_md5 = h
.get_header(CONTENT_MD5)
.map(|header| ConsistencyMD5::decode(header.as_bytes()))
.transpose()?;
trace!("content_md5 == {:?}", content_md5);
let content_crc64 = h
.get_header(CONTENT_CRC64)
.map(|header| ConsistencyCRC64::decode(header.as_bytes()))
.transpose()?;
trace!("content_crc64 == {:?}", content_crc64);
let cache_control = h.get_as_string(header::CACHE_CONTROL);
let content_disposition = h.get_as_string(header::CONTENT_DISPOSITION);
let lease_status = h
.get_as_enum(LEASE_STATUS)?
.ok_or_else(|| crate::Error::HeaderNotFound(LEASE_STATUS.to_owned()))?;
trace!("lease_status == {:?}", lease_status);
let lease_state = h
.get_as_enum(LEASE_STATE)?
.ok_or_else(|| crate::Error::HeaderNotFound(LEASE_STATE.to_owned()))?;
trace!("lease_state == {:?}", lease_state);
let lease_duration = h.get_as_enum(LEASE_DURATION)?;
trace!("lease_duration == {:?}", lease_duration);
let copy_id = h
.get_as_string(COPY_ID)
.map(|c| (&c as &str).try_into())
.transpose()?;
trace!("copy_id == {:?}", copy_id);
let copy_status = h.get_as_enum(COPY_STATUS)?;
trace!("copy_status == {:?}", copy_status);
let copy_source = h.get_as_string(COPY_SOURCE);
trace!("copy_source == {:?}", copy_source);
let copy_progress = h
.get_as_str(COPY_PROGRESS)
.and_then(|cp| Some(CopyProgress::from_str(cp).ok())?);
trace!("copy_progress == {:?}", copy_progress);
let copy_completion_time: Option<DateTime<Utc>> =
h.get_as_str(COPY_COMPLETION_TIME).and_then(|cct| {
Some(DateTime::from_utc(
DateTime::parse_from_rfc2822(cct).ok()?.naive_utc(),
Utc,
))
});
trace!("copy_completion_time == {:?}", copy_completion_time);
let copy_status_description = h.get_as_string(COPY_STATUS_DESCRIPTION);
trace!("copy_status_description == {:?}", copy_status_description);
let server_encrypted = h
.get_as_str(SERVER_ENCRYPTED)
.ok_or_else(|| crate::Error::HeaderNotFound(SERVER_ENCRYPTED.to_owned()))?
.parse::<bool>()?;
let mut metadata = HashMap::new();
for (name, value) in h.iter() {
let name = name.as_str();
if let Some(name) = name.strip_prefix(META_PREFIX) {
if let Ok(value) = value.to_str() {
metadata.insert(name.to_string(), value.to_string());
}
}
}
let metadata = if metadata.is_empty() {
None
} else {
Some(metadata)
};
// TODO: Retrieve the snapshot time from
// the headers
let snapshot = None;
Ok(Blob {
name: blob_name.into(),
snapshot,
deleted: None, //TODO
is_current_version: None, //TODO
version_id: None, //TODO
properties: BlobProperties {
creation_time,
last_modified,
last_access_time: None, // TODO
etag,
content_length,
content_type,
content_encoding,
content_language,
content_md5,
content_crc64,
cache_control,
content_disposition,
blob_sequence_number,
blob_type,
access_tier: None,
lease_status,
lease_state,
lease_duration,
copy_id,
copy_status,
copy_source,
copy_progress,
copy_completion_time,
copy_status_description,
incremental_copy: None, // TODO: Not present or documentation bug?
server_encrypted,
customer_provided_key_sha256: None, // TODO
encryption_scope: None, // TODO
access_tier_inferred: None, // TODO: Not present
access_tier_change_time: None, // TODO: Not present
deleted_time: None, // TODO
remaining_retention_days: None, // TODO: Not present or documentation bug?
tag_count: None, // TODO
rehydrate_priority: None, // TODO
extra: HashMap::new(),
},
metadata,
tags: None,
})
}
}
pub(crate) fn copy_status_from_headers(headers: &http::HeaderMap) -> crate::Result<CopyStatus> {
let val = headers
.get_as_str(azure_core::headers::COPY_STATUS)
.ok_or_else(|| crate::Error::HeaderNotFound(azure_core::headers::COPY_STATUS.to_owned()))?;
Ok(CopyStatus::from_str(val)?)
}
|
use actix_web::{middleware::Logger, App, HttpServer};
use dotenv::dotenv;
use octo_budget_api::{config, db::ConnectionPool, redis::Redis, routes::init_routes};
use octo_budget_lib::auth_token::ApiJwtTokenAuthConfig;
#[actix_rt::main]
async fn main() -> std::io::Result<()> {
dotenv().expect("Failed to parse .env file");
env_logger::init();
let redis = Redis::new().await;
HttpServer::new(move || {
App::new()
.data(ConnectionPool::new())
.data(redis.clone())
.app_data(ApiJwtTokenAuthConfig::new(
config::AUTH_TOKEN_SECRET.as_bytes(),
))
.wrap(middlewares::force_https::ForceHttps::new(
config::is_force_https(),
))
.wrap(Logger::default())
.configure(init_routes)
})
.bind(format!(
"{}:{}",
config::LISTEN_IP.as_str(),
config::PORT.as_str()
))?
.run()
.await
}
|
/// A struct to wrap any sized type that could be used as a key
pub struct Key<T: Sized>(T);
// Implement From for any Sized type and wrap it in a Key struct
impl<T> From<T> for Key<T> {
fn from(input: T) -> Self {
Key::<T> { 0: input }
}
}
impl Into<Key<String>> for Key<&str> {
fn into(self) -> Key<String> {
Key::<String> {
0: self.0.to_string(),
}
}
}
impl Into<Vec<u8>> for Key<u32> {
fn into(self) -> Vec<u8> {
self.0.to_be_bytes().to_vec()
}
}
impl Into<Vec<u8>> for Key<u64> {
fn into(self) -> Vec<u8> {
self.0.to_be_bytes().to_vec()
}
}
impl Into<Vec<u8>> for Key<String> {
fn into(self) -> Vec<u8> {
self.0.as_bytes().to_vec()
}
}
impl Into<Vec<u8>> for Key<&str> {
fn into(self) -> Vec<u8> {
self.0.as_bytes().to_vec()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Record;
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
struct Thing {
id: u32,
}
impl Record for Thing {
type Key = Key<u32>;
fn key(&self) -> Self::Key {
Key::from(self.id)
}
}
#[derive(Serialize, Deserialize)]
struct OtherThing {
id: std::string::String,
}
impl Record for OtherThing {
type Key = std::string::String;
fn key(&self) -> Self::Key {
//Key::from(self.id.clone())
self.id.clone()
}
}
#[derive(Serialize, Deserialize)]
struct AnotherThing {
id: u32,
}
impl Record for AnotherThing {
type Key = Key<u32>;
fn key(&self) -> Self::Key {
Key::from(self.id)
}
}
// A dummy function that ensures things compile
fn get<T: Record>(_key: T::Key) {}
// Another dummy function to use to see if we can transform inputs and what that looks like
fn get2<T: Record, K: Into<T::Key>>(_key: K) -> Option<T> {
None
}
#[test]
fn test_that_are_key_type_is_useful() {
let a = Key::<u8> { 0: 0 };
assert_eq!(0, a.0);
let b = Key::from(8);
assert_eq!(8, b.0);
let c = Key::from("Yo");
assert_eq!("Yo", c.0);
let d = Key::from(String::from("LOL"));
assert_eq!("LOL".to_string(), d.0);
let _e = get::<Thing>(Key::from(8));
let _f = get::<OtherThing>(String::from("LOL"));
let g = Key::from([0, 1, 2, 3]);
assert_eq!([0, 1, 2, 3], g.0);
let _h: Option<Thing> = get2(8);
let _i: Option<OtherThing> = get2("Hello".to_string());
let _j: Option<OtherThing> = get2("Hi");
}
}
|
#[macro_use]
extern crate serde_derive;
extern crate chrono;
pub mod handle;
pub mod slack;
use chrono::prelude::*;
use rocket::request::FromForm;
#[derive(Deserialize, Debug)]
pub struct SlackEvent {
pub token: String,
pub challenge: Option<String>,
pub event: Option<EventDetails>,
}
#[derive(Deserialize, Debug, FromForm)]
pub struct SlackSlashEvent {
pub token: String,
pub response_url: String,
pub trigger_id: String,
pub user_id: String,
}
#[derive(Deserialize, Debug)]
pub struct EventDetails {
pub text: String,
pub user: String,
pub channel: String,
pub r#type: String,
pub bot_id: Option<String>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct SlackConfigResource {
pub id: String,
pub name: String,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct SlackConfigSubmission {
pub reminder: Option<String>,
pub channel: Option<String>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct SlackConfig {
pub user: SlackConfigResource,
pub channel: SlackConfigResource,
pub submission: SlackConfigSubmission,
}
#[derive(Debug, FromForm)]
pub struct SlackConfigResponse {
pub payload: String,
}
#[derive(Debug)]
pub struct Standup {
user: String,
date: Date<Utc>,
// not sure if it would be better to encapsulate this?
prev_day: Option<String>,
day: Option<String>,
blocker: Option<String>,
}
#[derive(Debug)]
pub enum UserState {
Idle,
AddPrevDay,
AddDay,
AddBlocker,
}
#[derive(Debug)]
pub struct User {
username: String,
channel: Option<String>,
reminder: Option<DateTime<Utc>>,
state: UserState,
real_name: Option<String>,
avatar_url: Option<String>,
}
impl User {
pub fn new(username: &str) -> User {
User {
username: String::from(username),
state: UserState::Idle,
channel: None,
reminder: None,
real_name: None,
avatar_url: None,
}
}
pub fn update_config(&mut self, config: SlackConfig) {
self.channel = config.submission.channel;
//self.reminder = Some(config.submission.reminder);
}
}
#[derive(Debug)]
pub struct UserList {
list: Vec<User>,
}
impl UserList {
pub fn new() -> UserList {
UserList { list: vec![] }
}
pub fn find_user(&mut self, username: &str) -> Option<&mut User> {
self.list
.iter_mut()
.filter(|u| u.username == username)
.next()
}
pub fn add_user(&mut self, user: User) {
self.list.push(user);
}
}
pub enum StandupStage {
PrevDay,
Today,
Blocker,
Complete,
}
impl Standup {
pub fn new(user: &str) -> Standup {
Standup {
user: String::from(user),
date: Utc::now().date(),
prev_day: None,
day: None,
blocker: None,
}
}
}
#[derive(Debug)]
pub struct StandupList {
list: Vec<Standup>,
}
impl StandupList {
pub fn new() -> StandupList {
StandupList { list: vec![] }
}
pub fn add_standup(&mut self, s: Standup) {
self.list.push(s);
}
pub fn get_todays_mut(&mut self, user: &str) -> Option<&mut Standup> {
let today = Utc::now().date();
self.list
.iter_mut()
.filter(|standup| standup.user == user && standup.date == today)
.take(1)
.next()
}
pub fn get_latest(&self, user: &str) -> Option<&Standup> {
let mut lower_date = Utc.ymd(1990, 1, 1);
self.list
.iter()
.filter(|standup| standup.user == user)
.fold(None, |acc, x| {
if x.date > lower_date {
lower_date = x.date;
Some(x)
} else {
acc
}
})
}
pub fn remove_todays_from_user(&mut self, user: &str) {
let today = Utc::now().date();
self.list.retain(|s| s.user != user && s.date != today);
}
}
#[cfg(test)]
mod test {
use crate::{Standup, StandupList};
use chrono::prelude::*;
#[test]
fn create_standup_list() {
let sl = StandupList::new();
assert_eq!(sl.list.len(), 0);
}
#[test]
fn add_standup_to_list() {
let user = "ruiramos";
let mut sl = StandupList::new();
let s = Standup::new(user);
sl.add_standup(s);
assert_eq!(sl.list.len(), 1);
}
#[test]
fn get_todays_standup() {
let user = "ruiramos";
let user2 = "ruiramos2";
let mut sl = StandupList::new();
let s = Standup::new(user);
let s2 = Standup::new(user);
let mut s3 = Standup::new(user);
let s2_1 = Standup::new(user2);
let s2_2 = Standup::new(user2);
s3.date = Utc.ymd(2020, 1, 15);
sl.add_standup(s);
sl.add_standup(s2);
sl.add_standup(s3);
sl.add_standup(s2_1);
sl.add_standup(s2_2);
let result = sl.get_todays_mut(user).unwrap();
assert_eq!(result.date, Utc::now().date());
}
#[test]
fn get_latest_standup() {
let user = "ruiramos";
let user2 = "ruiramos2";
let mut sl = StandupList::new();
let mut s = Standup::new(user);
let mut s2 = Standup::new(user);
let mut s3 = Standup::new(user);
let s2_1 = Standup::new(user2);
let s2_2 = Standup::new(user2);
s.date = Utc.ymd(2011, 1, 1);
// this is actually the latest one:
s2.date = Utc.ymd(2011, 2, 1);
s3.date = Utc.ymd(2011, 1, 15);
sl.add_standup(s);
sl.add_standup(s2);
sl.add_standup(s3);
sl.add_standup(s2_1);
sl.add_standup(s2_2);
let result = sl.get_latest(user).unwrap();
assert_eq!(result.date, Utc.ymd(2011, 2, 1));
}
}
|
pub mod google_tts;
pub mod models;
|
fn main() {
let pattern = [7, 0, 4, 3, 2, 1];
let len_pattern = pattern.len();
let mut recipies: Vec<usize> = vec![3, 7];
let mut cursor_one = 0;
let mut cursor_two = 1;
let mut check_cursor = 0;
loop {
// part 1
// if recipies.len() > 704321 + 10 {
// println!("{:?}", &recipies[704321..(704321 + 10)]);
// break;
// }
// part 2
if recipies.len() >= len_pattern {
if recipies[check_cursor..(check_cursor + len_pattern)] == pattern {
dbg!(&check_cursor);
break;
}
check_cursor += 1;
}
let sum = recipies[cursor_one] + recipies[cursor_two];
let sum_str = sum.to_string();
let first_digit: usize = sum_str.get(0..1)
.expect("Sum was empty")
.parse()
.expect("Failed to parse as integer");
recipies.push(first_digit);
let second_digit = sum_str.get(1..).expect("Sum was empty");
if !second_digit.is_empty() {
recipies.push(second_digit.parse::<usize>().expect("Failed to parse as integer"));
}
cursor_one = (cursor_one + 1 + recipies[cursor_one]) % recipies.len();
cursor_two = (cursor_two + 1 + recipies[cursor_two]) % recipies.len();
}
}
|
#[doc = "Register `DDRCTRL_SCHED1` reader"]
pub type R = crate::R<DDRCTRL_SCHED1_SPEC>;
#[doc = "Register `DDRCTRL_SCHED1` writer"]
pub type W = crate::W<DDRCTRL_SCHED1_SPEC>;
#[doc = "Field `PAGECLOSE_TIMER` reader - PAGECLOSE_TIMER"]
pub type PAGECLOSE_TIMER_R = crate::FieldReader;
#[doc = "Field `PAGECLOSE_TIMER` writer - PAGECLOSE_TIMER"]
pub type PAGECLOSE_TIMER_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 8, O>;
impl R {
#[doc = "Bits 0:7 - PAGECLOSE_TIMER"]
#[inline(always)]
pub fn pageclose_timer(&self) -> PAGECLOSE_TIMER_R {
PAGECLOSE_TIMER_R::new((self.bits & 0xff) as u8)
}
}
impl W {
#[doc = "Bits 0:7 - PAGECLOSE_TIMER"]
#[inline(always)]
#[must_use]
pub fn pageclose_timer(&mut self) -> PAGECLOSE_TIMER_W<DDRCTRL_SCHED1_SPEC, 0> {
PAGECLOSE_TIMER_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 = "DDRCTRL scheduler control register 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ddrctrl_sched1::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 [`ddrctrl_sched1::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct DDRCTRL_SCHED1_SPEC;
impl crate::RegisterSpec for DDRCTRL_SCHED1_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`ddrctrl_sched1::R`](R) reader structure"]
impl crate::Readable for DDRCTRL_SCHED1_SPEC {}
#[doc = "`write(|w| ..)` method takes [`ddrctrl_sched1::W`](W) writer structure"]
impl crate::Writable for DDRCTRL_SCHED1_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets DDRCTRL_SCHED1 to value 0"]
impl crate::Resettable for DDRCTRL_SCHED1_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use crate::prelude::*;
pub fn build_dijkstra(starts: &[usize], map: &Map) -> DijkstraMap {
DijkstraMap::new(SCREEN_WIDTH, SCREEN_HEIGHT, starts, map, 1024.0)
}
|
// ===============================================================================
// Authors: AFRL/RQQA
// Organization: Air Force Research Laboratory, Aerospace Systems Directorate, Power and Control Division
//
// Copyright (c) 2017 Government of the United State of America, as represented by
// the Secretary of the Air Force. No copyright is claimed in the United States under
// Title 17, U.S. Code. All Other Rights Reserved.
// ===============================================================================
// This file was auto-created by LmcpGen. Modifications will be overwritten.
use avtas::lmcp::{Error, ErrorType, Lmcp, LmcpSubscription, SrcLoc, Struct, StructInfo};
use std::fmt::Debug;
#[derive(Clone, Debug, Default)]
#[repr(C)]
pub struct GimbalConfiguration {
pub payload_id: i64,
pub payload_kind: Vec<u8>,
pub parameters: Vec<Box<::afrl::cmasi::key_value_pair::KeyValuePairT>>,
pub supported_pointing_modes: Vec<::afrl::cmasi::gimbal_pointing_mode::GimbalPointingMode>,
pub min_azimuth: f32,
pub max_azimuth: f32,
pub is_azimuth_clamped: bool,
pub min_elevation: f32,
pub max_elevation: f32,
pub is_elevation_clamped: bool,
pub min_rotation: f32,
pub max_rotation: f32,
pub is_rotation_clamped: bool,
pub max_azimuth_slew_rate: f32,
pub max_elevation_slew_rate: f32,
pub max_rotation_rate: f32,
pub contained_payload_list: Vec<i64>,
}
impl PartialEq for GimbalConfiguration {
fn eq(&self, _other: &GimbalConfiguration) -> bool {
true
&& &self.supported_pointing_modes == &_other.supported_pointing_modes
&& &self.min_azimuth == &_other.min_azimuth
&& &self.max_azimuth == &_other.max_azimuth
&& &self.is_azimuth_clamped == &_other.is_azimuth_clamped
&& &self.min_elevation == &_other.min_elevation
&& &self.max_elevation == &_other.max_elevation
&& &self.is_elevation_clamped == &_other.is_elevation_clamped
&& &self.min_rotation == &_other.min_rotation
&& &self.max_rotation == &_other.max_rotation
&& &self.is_rotation_clamped == &_other.is_rotation_clamped
&& &self.max_azimuth_slew_rate == &_other.max_azimuth_slew_rate
&& &self.max_elevation_slew_rate == &_other.max_elevation_slew_rate
&& &self.max_rotation_rate == &_other.max_rotation_rate
&& &self.contained_payload_list == &_other.contained_payload_list
}
}
impl LmcpSubscription for GimbalConfiguration {
fn subscription() -> &'static str { "afrl.cmasi.GimbalConfiguration" }
}
impl Struct for GimbalConfiguration {
fn struct_info() -> StructInfo {
StructInfo {
exist: 1,
series: 4849604199710720000u64,
version: 3,
struct_ty: 24,
}
}
}
impl Lmcp for GimbalConfiguration {
fn ser(&self, buf: &mut[u8]) -> Result<usize, Error> {
let mut pos = 0;
{
let x = Self::struct_info().ser(buf)?;
pos += x;
}
{
let r = get!(buf.get_mut(pos ..));
let writeb: usize = self.payload_id.ser(r)?;
pos += writeb;
}
{
let r = get!(buf.get_mut(pos ..));
let writeb: usize = self.payload_kind.ser(r)?;
pos += writeb;
}
{
let r = get!(buf.get_mut(pos ..));
let writeb: usize = self.parameters.ser(r)?;
pos += writeb;
}
{
let r = get!(buf.get_mut(pos ..));
let writeb: usize = self.supported_pointing_modes.ser(r)?;
pos += writeb;
}
{
let r = get!(buf.get_mut(pos ..));
let writeb: usize = self.min_azimuth.ser(r)?;
pos += writeb;
}
{
let r = get!(buf.get_mut(pos ..));
let writeb: usize = self.max_azimuth.ser(r)?;
pos += writeb;
}
{
let r = get!(buf.get_mut(pos ..));
let writeb: usize = self.is_azimuth_clamped.ser(r)?;
pos += writeb;
}
{
let r = get!(buf.get_mut(pos ..));
let writeb: usize = self.min_elevation.ser(r)?;
pos += writeb;
}
{
let r = get!(buf.get_mut(pos ..));
let writeb: usize = self.max_elevation.ser(r)?;
pos += writeb;
}
{
let r = get!(buf.get_mut(pos ..));
let writeb: usize = self.is_elevation_clamped.ser(r)?;
pos += writeb;
}
{
let r = get!(buf.get_mut(pos ..));
let writeb: usize = self.min_rotation.ser(r)?;
pos += writeb;
}
{
let r = get!(buf.get_mut(pos ..));
let writeb: usize = self.max_rotation.ser(r)?;
pos += writeb;
}
{
let r = get!(buf.get_mut(pos ..));
let writeb: usize = self.is_rotation_clamped.ser(r)?;
pos += writeb;
}
{
let r = get!(buf.get_mut(pos ..));
let writeb: usize = self.max_azimuth_slew_rate.ser(r)?;
pos += writeb;
}
{
let r = get!(buf.get_mut(pos ..));
let writeb: usize = self.max_elevation_slew_rate.ser(r)?;
pos += writeb;
}
{
let r = get!(buf.get_mut(pos ..));
let writeb: usize = self.max_rotation_rate.ser(r)?;
pos += writeb;
}
{
let r = get!(buf.get_mut(pos ..));
let writeb: usize = self.contained_payload_list.ser(r)?;
pos += writeb;
}
Ok(pos)
}
fn deser(buf: &[u8]) -> Result<(GimbalConfiguration, usize), Error> {
let mut pos = 0;
let (si, u) = StructInfo::deser(buf)?;
pos += u;
if si == GimbalConfiguration::struct_info() {
let mut out: GimbalConfiguration = Default::default();
{
let r = get!(buf.get(pos ..));
let (x, readb): (i64, usize) = Lmcp::deser(r)?;
out.payload_id = x;
pos += readb;
}
{
let r = get!(buf.get(pos ..));
let (x, readb): (Vec<u8>, usize) = Lmcp::deser(r)?;
out.payload_kind = x;
pos += readb;
}
{
let r = get!(buf.get(pos ..));
let (x, readb): (Vec<Box<::afrl::cmasi::key_value_pair::KeyValuePairT>>, usize) = Lmcp::deser(r)?;
out.parameters = x;
pos += readb;
}
{
let r = get!(buf.get(pos ..));
let (x, readb): (Vec<::afrl::cmasi::gimbal_pointing_mode::GimbalPointingMode>, usize) = Lmcp::deser(r)?;
out.supported_pointing_modes = x;
pos += readb;
}
{
let r = get!(buf.get(pos ..));
let (x, readb): (f32, usize) = Lmcp::deser(r)?;
out.min_azimuth = x;
pos += readb;
}
{
let r = get!(buf.get(pos ..));
let (x, readb): (f32, usize) = Lmcp::deser(r)?;
out.max_azimuth = x;
pos += readb;
}
{
let r = get!(buf.get(pos ..));
let (x, readb): (bool, usize) = Lmcp::deser(r)?;
out.is_azimuth_clamped = x;
pos += readb;
}
{
let r = get!(buf.get(pos ..));
let (x, readb): (f32, usize) = Lmcp::deser(r)?;
out.min_elevation = x;
pos += readb;
}
{
let r = get!(buf.get(pos ..));
let (x, readb): (f32, usize) = Lmcp::deser(r)?;
out.max_elevation = x;
pos += readb;
}
{
let r = get!(buf.get(pos ..));
let (x, readb): (bool, usize) = Lmcp::deser(r)?;
out.is_elevation_clamped = x;
pos += readb;
}
{
let r = get!(buf.get(pos ..));
let (x, readb): (f32, usize) = Lmcp::deser(r)?;
out.min_rotation = x;
pos += readb;
}
{
let r = get!(buf.get(pos ..));
let (x, readb): (f32, usize) = Lmcp::deser(r)?;
out.max_rotation = x;
pos += readb;
}
{
let r = get!(buf.get(pos ..));
let (x, readb): (bool, usize) = Lmcp::deser(r)?;
out.is_rotation_clamped = x;
pos += readb;
}
{
let r = get!(buf.get(pos ..));
let (x, readb): (f32, usize) = Lmcp::deser(r)?;
out.max_azimuth_slew_rate = x;
pos += readb;
}
{
let r = get!(buf.get(pos ..));
let (x, readb): (f32, usize) = Lmcp::deser(r)?;
out.max_elevation_slew_rate = x;
pos += readb;
}
{
let r = get!(buf.get(pos ..));
let (x, readb): (f32, usize) = Lmcp::deser(r)?;
out.max_rotation_rate = x;
pos += readb;
}
{
let r = get!(buf.get(pos ..));
let (x, readb): (Vec<i64>, usize) = Lmcp::deser(r)?;
out.contained_payload_list = x;
pos += readb;
}
Ok((out, pos))
} else {
Err(error!(ErrorType::InvalidStructInfo))
}
}
fn size(&self) -> usize {
let mut size = 15;
size += self.payload_id.size();
size += self.payload_kind.size();
size += self.parameters.size();
size += self.supported_pointing_modes.size();
size += self.min_azimuth.size();
size += self.max_azimuth.size();
size += self.is_azimuth_clamped.size();
size += self.min_elevation.size();
size += self.max_elevation.size();
size += self.is_elevation_clamped.size();
size += self.min_rotation.size();
size += self.max_rotation.size();
size += self.is_rotation_clamped.size();
size += self.max_azimuth_slew_rate.size();
size += self.max_elevation_slew_rate.size();
size += self.max_rotation_rate.size();
size += self.contained_payload_list.size();
size
}
}
pub trait GimbalConfigurationT: Debug + Send + ::afrl::cmasi::payload_configuration::PayloadConfigurationT {
fn as_afrl_cmasi_gimbal_configuration(&self) -> Option<&GimbalConfiguration> { None }
fn as_mut_afrl_cmasi_gimbal_configuration(&mut self) -> Option<&mut GimbalConfiguration> { None }
fn supported_pointing_modes(&self) -> &Vec<::afrl::cmasi::gimbal_pointing_mode::GimbalPointingMode>;
fn supported_pointing_modes_mut(&mut self) -> &mut Vec<::afrl::cmasi::gimbal_pointing_mode::GimbalPointingMode>;
fn min_azimuth(&self) -> f32;
fn min_azimuth_mut(&mut self) -> &mut f32;
fn max_azimuth(&self) -> f32;
fn max_azimuth_mut(&mut self) -> &mut f32;
fn is_azimuth_clamped(&self) -> bool;
fn is_azimuth_clamped_mut(&mut self) -> &mut bool;
fn min_elevation(&self) -> f32;
fn min_elevation_mut(&mut self) -> &mut f32;
fn max_elevation(&self) -> f32;
fn max_elevation_mut(&mut self) -> &mut f32;
fn is_elevation_clamped(&self) -> bool;
fn is_elevation_clamped_mut(&mut self) -> &mut bool;
fn min_rotation(&self) -> f32;
fn min_rotation_mut(&mut self) -> &mut f32;
fn max_rotation(&self) -> f32;
fn max_rotation_mut(&mut self) -> &mut f32;
fn is_rotation_clamped(&self) -> bool;
fn is_rotation_clamped_mut(&mut self) -> &mut bool;
fn max_azimuth_slew_rate(&self) -> f32;
fn max_azimuth_slew_rate_mut(&mut self) -> &mut f32;
fn max_elevation_slew_rate(&self) -> f32;
fn max_elevation_slew_rate_mut(&mut self) -> &mut f32;
fn max_rotation_rate(&self) -> f32;
fn max_rotation_rate_mut(&mut self) -> &mut f32;
fn contained_payload_list(&self) -> &Vec<i64>;
fn contained_payload_list_mut(&mut self) -> &mut Vec<i64>;
}
impl Clone for Box<GimbalConfigurationT> {
fn clone(&self) -> Box<GimbalConfigurationT> {
if let Some(x) = GimbalConfigurationT::as_afrl_cmasi_gimbal_configuration(self.as_ref()) {
Box::new(x.clone())
} else {
unreachable!()
}
}
}
impl Default for Box<GimbalConfigurationT> {
fn default() -> Box<GimbalConfigurationT> { Box::new(GimbalConfiguration::default()) }
}
impl PartialEq for Box<GimbalConfigurationT> {
fn eq(&self, other: &Box<GimbalConfigurationT>) -> bool {
if let (Some(x), Some(y)) =
(GimbalConfigurationT::as_afrl_cmasi_gimbal_configuration(self.as_ref()),
GimbalConfigurationT::as_afrl_cmasi_gimbal_configuration(other.as_ref())) {
x == y
} else {
false
}
}
}
impl Lmcp for Box<GimbalConfigurationT> {
fn ser(&self, buf: &mut[u8]) -> Result<usize, Error> {
if let Some(x) = GimbalConfigurationT::as_afrl_cmasi_gimbal_configuration(self.as_ref()) {
x.ser(buf)
} else {
unreachable!()
}
}
fn deser(buf: &[u8]) -> Result<(Box<GimbalConfigurationT>, usize), Error> {
let (si, _) = StructInfo::deser(buf)?;
if si == GimbalConfiguration::struct_info() {
let (x, readb) = GimbalConfiguration::deser(buf)?;
Ok((Box::new(x), readb))
} else {
Err(error!(ErrorType::InvalidStructInfo))
}
}
fn size(&self) -> usize {
if let Some(x) = GimbalConfigurationT::as_afrl_cmasi_gimbal_configuration(self.as_ref()) {
x.size()
} else {
unreachable!()
}
}
}
impl ::afrl::cmasi::payload_configuration::PayloadConfigurationT for GimbalConfiguration {
fn as_afrl_cmasi_gimbal_configuration(&self) -> Option<&GimbalConfiguration> { Some(self) }
fn as_mut_afrl_cmasi_gimbal_configuration(&mut self) -> Option<&mut GimbalConfiguration> { Some(self) }
fn payload_id(&self) -> i64 { self.payload_id }
fn payload_id_mut(&mut self) -> &mut i64 { &mut self.payload_id }
fn payload_kind(&self) -> &Vec<u8> { &self.payload_kind }
fn payload_kind_mut(&mut self) -> &mut Vec<u8> { &mut self.payload_kind }
fn parameters(&self) -> &Vec<Box<::afrl::cmasi::key_value_pair::KeyValuePairT>> { &self.parameters }
fn parameters_mut(&mut self) -> &mut Vec<Box<::afrl::cmasi::key_value_pair::KeyValuePairT>> { &mut self.parameters }
}
impl GimbalConfigurationT for GimbalConfiguration {
fn as_afrl_cmasi_gimbal_configuration(&self) -> Option<&GimbalConfiguration> { Some(self) }
fn as_mut_afrl_cmasi_gimbal_configuration(&mut self) -> Option<&mut GimbalConfiguration> { Some(self) }
fn supported_pointing_modes(&self) -> &Vec<::afrl::cmasi::gimbal_pointing_mode::GimbalPointingMode> { &self.supported_pointing_modes }
fn supported_pointing_modes_mut(&mut self) -> &mut Vec<::afrl::cmasi::gimbal_pointing_mode::GimbalPointingMode> { &mut self.supported_pointing_modes }
fn min_azimuth(&self) -> f32 { self.min_azimuth }
fn min_azimuth_mut(&mut self) -> &mut f32 { &mut self.min_azimuth }
fn max_azimuth(&self) -> f32 { self.max_azimuth }
fn max_azimuth_mut(&mut self) -> &mut f32 { &mut self.max_azimuth }
fn is_azimuth_clamped(&self) -> bool { self.is_azimuth_clamped }
fn is_azimuth_clamped_mut(&mut self) -> &mut bool { &mut self.is_azimuth_clamped }
fn min_elevation(&self) -> f32 { self.min_elevation }
fn min_elevation_mut(&mut self) -> &mut f32 { &mut self.min_elevation }
fn max_elevation(&self) -> f32 { self.max_elevation }
fn max_elevation_mut(&mut self) -> &mut f32 { &mut self.max_elevation }
fn is_elevation_clamped(&self) -> bool { self.is_elevation_clamped }
fn is_elevation_clamped_mut(&mut self) -> &mut bool { &mut self.is_elevation_clamped }
fn min_rotation(&self) -> f32 { self.min_rotation }
fn min_rotation_mut(&mut self) -> &mut f32 { &mut self.min_rotation }
fn max_rotation(&self) -> f32 { self.max_rotation }
fn max_rotation_mut(&mut self) -> &mut f32 { &mut self.max_rotation }
fn is_rotation_clamped(&self) -> bool { self.is_rotation_clamped }
fn is_rotation_clamped_mut(&mut self) -> &mut bool { &mut self.is_rotation_clamped }
fn max_azimuth_slew_rate(&self) -> f32 { self.max_azimuth_slew_rate }
fn max_azimuth_slew_rate_mut(&mut self) -> &mut f32 { &mut self.max_azimuth_slew_rate }
fn max_elevation_slew_rate(&self) -> f32 { self.max_elevation_slew_rate }
fn max_elevation_slew_rate_mut(&mut self) -> &mut f32 { &mut self.max_elevation_slew_rate }
fn max_rotation_rate(&self) -> f32 { self.max_rotation_rate }
fn max_rotation_rate_mut(&mut self) -> &mut f32 { &mut self.max_rotation_rate }
fn contained_payload_list(&self) -> &Vec<i64> { &self.contained_payload_list }
fn contained_payload_list_mut(&mut self) -> &mut Vec<i64> { &mut self.contained_payload_list }
}
#[cfg(test)]
pub mod tests {
use super::*;
use quickcheck::*;
impl Arbitrary for GimbalConfiguration {
fn arbitrary<G: Gen>(_g: &mut G) -> GimbalConfiguration {
GimbalConfiguration {
payload_id: Arbitrary::arbitrary(_g),
payload_kind: Arbitrary::arbitrary(_g),
parameters: Vec::<::afrl::cmasi::key_value_pair::KeyValuePair>::arbitrary(_g).into_iter().map(|x| Box::new(x) as Box<::afrl::cmasi::key_value_pair::KeyValuePairT>).collect(),
supported_pointing_modes: Arbitrary::arbitrary(_g),
min_azimuth: Arbitrary::arbitrary(_g),
max_azimuth: Arbitrary::arbitrary(_g),
is_azimuth_clamped: Arbitrary::arbitrary(_g),
min_elevation: Arbitrary::arbitrary(_g),
max_elevation: Arbitrary::arbitrary(_g),
is_elevation_clamped: Arbitrary::arbitrary(_g),
min_rotation: Arbitrary::arbitrary(_g),
max_rotation: Arbitrary::arbitrary(_g),
is_rotation_clamped: Arbitrary::arbitrary(_g),
max_azimuth_slew_rate: Arbitrary::arbitrary(_g),
max_elevation_slew_rate: Arbitrary::arbitrary(_g),
max_rotation_rate: Arbitrary::arbitrary(_g),
contained_payload_list: Arbitrary::arbitrary(_g),
}
}
}
quickcheck! {
fn serializes(x: GimbalConfiguration) -> Result<TestResult, Error> {
use std::u16;
if x.parameters.len() > (u16::MAX as usize) { return Ok(TestResult::discard()); }
if x.supported_pointing_modes.len() > (u16::MAX as usize) { return Ok(TestResult::discard()); }
if x.contained_payload_list.len() > (u16::MAX as usize) { return Ok(TestResult::discard()); }
let mut buf: Vec<u8> = vec![0; x.size()];
let sx = x.ser(&mut buf)?;
Ok(TestResult::from_bool(sx == x.size()))
}
fn roundtrips(x: GimbalConfiguration) -> Result<TestResult, Error> {
use std::u16;
if x.parameters.len() > (u16::MAX as usize) { return Ok(TestResult::discard()); }
if x.supported_pointing_modes.len() > (u16::MAX as usize) { return Ok(TestResult::discard()); }
if x.contained_payload_list.len() > (u16::MAX as usize) { return Ok(TestResult::discard()); }
let mut buf: Vec<u8> = vec![0; x.size()];
let sx = x.ser(&mut buf)?;
let (y, sy) = GimbalConfiguration::deser(&buf)?;
Ok(TestResult::from_bool(sx == sy && x == y))
}
}
}
|
#[macro_use]
extern crate log;
use std::fs;
use clap::{App, Arg, SubCommand};
use rsocket_rust::prelude::*;
use rsocket_rust::transport::Connection;
use rsocket_rust::utils::EchoRSocket;
use rsocket_rust::Result;
use rsocket_rust_transport_tcp::{
TcpClientTransport, TcpServerTransport, UnixClientTransport, UnixServerTransport,
};
use rsocket_rust_transport_websocket::{WebsocketClientTransport, WebsocketServerTransport};
enum RequestMode {
FNF,
REQUEST,
STREAM,
CHANNEL,
}
async fn serve<A, B>(transport: A, mtu: usize) -> Result<()>
where
A: Send + Sync + ServerTransport<Item = B> + 'static,
B: Send + Sync + Transport + 'static,
{
RSocketFactory::receive()
.transport(transport)
.fragment(mtu)
.acceptor(Box::new(|setup, _socket| {
info!("accept setup: {:?}", setup);
Ok(Box::new(EchoRSocket))
// Or you can reject setup
// Err(From::from("SETUP_NOT_ALLOW"))
}))
.on_start(Box::new(|| info!("+++++++ echo server started! +++++++")))
.serve()
.await
}
async fn connect<A, B>(transport: A, mtu: usize, req: Payload, mode: RequestMode) -> Result<()>
where
A: Send + Sync + Transport<Conn = B> + 'static,
B: Send + Sync + Connection + 'static,
{
let cli = RSocketFactory::connect()
.fragment(mtu)
.transport(transport)
.start()
.await?;
match mode {
RequestMode::FNF => {
cli.fire_and_forget(req).await?;
}
RequestMode::STREAM => {
let mut results = cli.request_stream(req);
loop {
match results.next().await {
Some(Ok(v)) => info!("{:?}", v),
Some(Err(e)) => {
error!("STREAM_RESPONSE FAILED: {:?}", e);
break;
}
None => break,
}
}
}
RequestMode::CHANNEL => {
let mut results = cli.request_channel(Box::pin(futures::stream::iter(vec![Ok(req)])));
loop {
match results.next().await {
Some(Ok(v)) => info!("{:?}", v),
Some(Err(e)) => {
error!("CHANNEL_RESPONSE FAILED: {:?}", e);
break;
}
None => break,
}
}
}
RequestMode::REQUEST => {
let res = cli.request_response(req).await?;
info!("{:?}", res);
}
}
Ok(())
}
#[tokio::main]
async fn main() -> Result<()> {
env_logger::builder().format_timestamp_millis().init();
let cli = App::new("echo")
.version("0.0.0")
.author("Jeffsky <jjeffcaii@outlook.com>")
.about("An echo tool for RSocket.")
.subcommand(
SubCommand::with_name("serve")
.about("serve an echo server")
.arg(
Arg::with_name("mtu")
.long("mtu")
.required(false)
.takes_value(true)
.help("Fragment mtu."),
)
.arg(
Arg::with_name("URL")
.required(true)
.index(1)
.help("connect url"),
),
)
.subcommand(
SubCommand::with_name("connect")
.about("connect to echo server")
.arg(
Arg::with_name("input")
.short("i")
.long("input")
.required(false)
.takes_value(true)
.help("Input payload data."),
)
.arg(
Arg::with_name("mtu")
.long("mtu")
.required(false)
.takes_value(true)
.help("Fragment mtu."),
)
.arg(
Arg::with_name("request")
.long("request")
.required(false)
.takes_value(false)
.help("request_response mode."),
)
.arg(
Arg::with_name("channel")
.long("channel")
.required(false)
.takes_value(false)
.help("request_channel mode."),
)
.arg(
Arg::with_name("stream")
.long("stream")
.required(false)
.takes_value(false)
.help("request_stream mode."),
)
.arg(
Arg::with_name("fnf")
.long("fnf")
.required(false)
.takes_value(false)
.help("fire_and_forget mode."),
)
.arg(
Arg::with_name("URL")
.required(true)
.index(1)
.help("connect url"),
),
)
.arg(
Arg::with_name("debug")
.short("d")
.help("print debug information verbosely"),
)
.get_matches();
match cli.subcommand() {
("serve", Some(flags)) => {
let addr = flags.value_of("URL").expect("Missing URL");
let mtu: usize = flags
.value_of("mtu")
.map(|it| it.parse().expect("Invalid mtu string!"))
.unwrap_or(0);
if addr.starts_with("ws://") {
serve(WebsocketServerTransport::from(addr), mtu).await
} else if addr.starts_with("unix://") {
let addr_owned = addr.to_owned();
tokio::spawn(async move {
let _ = serve(UnixServerTransport::from(addr_owned), mtu).await;
});
let sockfile = addr.chars().skip(7).collect::<String>();
// Watch signal
tokio::signal::ctrl_c().await?;
info!("ctrl-c received!");
if let Err(e) = std::fs::remove_file(&sockfile) {
error!("remove unix sock file failed: {}", e);
}
Ok(())
} else {
serve(TcpServerTransport::from(addr), mtu).await
}
}
("connect", Some(flags)) => {
let mut modes: Vec<RequestMode> = vec![];
if flags.is_present("stream") {
modes.push(RequestMode::STREAM);
}
if flags.is_present("fnf") {
modes.push(RequestMode::FNF);
}
if flags.is_present("channel") {
modes.push(RequestMode::CHANNEL);
}
if flags.is_present("request") {
modes.push(RequestMode::REQUEST);
}
if modes.len() > 1 {
error!("duplicated request mode: use one of --fnf/--request/--stream/--channel.");
return Ok(());
}
let mtu: usize = flags
.value_of("mtu")
.map(|it| it.parse().expect("Invalid mtu string!"))
.unwrap_or(0);
let addr = flags.value_of("URL").expect("Missing URL");
let mut bu = Payload::builder();
if let Some(data) = flags.value_of("input") {
if data.starts_with("@") {
let file_content =
fs::read_to_string(&data[1..].to_owned()).expect("Read file failed.");
bu = bu.set_data_utf8(&file_content);
} else {
bu = bu.set_data_utf8(data);
}
}
let req = bu.build();
let mode = modes.pop().unwrap_or(RequestMode::REQUEST);
if addr.starts_with("ws://") {
connect(WebsocketClientTransport::from(addr), mtu, req, mode).await
} else if addr.starts_with("unix://") {
connect(UnixClientTransport::from(addr), mtu, req, mode).await
} else {
connect(TcpClientTransport::from(addr), mtu, req, mode).await
}
}
_ => Ok(()),
}
}
|
/// Sort an array using insertion sort
///
/// # Parameters
///
/// - `arr`: A vector to sort in-place
///
/// # Type parameters
///
/// - `T`: A type that can be checked for equality and ordering e.g. a `i32`, a
/// `u8`, or a `f32`.
///
/// # Undefined Behavior
///
/// Does not work with `String` vectors.
///
/// # Examples
///
/// ```rust
/// use algorithmplus::sort::insertion_sort;
///
/// let mut ls = vec![3, 2, 1];
/// insertion_sort(&mut ls);
///
/// assert_eq!(ls, [1, 2, 3]);
/// ```
pub fn insertion_sort<T: PartialEq + PartialOrd + Copy>(arr: &mut [T]) {
for i in 1..arr.len() {
let mut j = i;
while j > 0 && arr[j - 1] > arr[j] {
arr.swap(j - 1, j);
j -= 1;
}
}
}
|
// Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![warn(clippy::all)]
use std::cmp::max as my_max;
use std::cmp::min as my_min;
use std::cmp::{max, min};
const LARGE: usize = 3;
fn main() {
let x;
x = 2usize;
min(1, max(3, x));
min(max(3, x), 1);
max(min(x, 1), 3);
max(3, min(x, 1));
my_max(3, my_min(x, 1));
min(3, max(1, x)); // ok, could be 1, 2 or 3 depending on x
min(1, max(LARGE, x)); // no error, we don't lookup consts here
let y = 2isize;
min(max(y, -1), 3);
let s;
s = "Hello";
min("Apple", max("Zoo", s));
max(min(s, "Apple"), "Zoo");
max("Apple", min(s, "Zoo")); // ok
}
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
use reverie::syscalls::Sysno;
use serde::Deserialize;
use serde::Serialize;
#[derive(Debug, Clone, Deserialize, Serialize, Eq, PartialEq)]
pub struct Filter {
/// Inverses the match.
pub inverse: bool,
/// The set of syscalls to match.
pub syscalls: Vec<Sysno>,
}
impl std::str::FromStr for Filter {
type Err = String;
// Must parse this: [!][?]value1[,[?]value2]...
fn from_str(s: &str) -> Result<Self, Self::Err> {
let (inverse, s) = match s.strip_prefix('!') {
Some(s) => (true, s),
None => (false, s),
};
let mut syscalls = Vec::new();
for value in s.split(',') {
// FIXME: Handle syscall sets, so we can use '%stat` to trace all
// stat calls, for example.
if value.strip_prefix('%').is_some() {
return Err("filtering sets of syscall is not yet supported".into());
}
let syscall: Sysno = value
.parse()
.map_err(|()| format!("invalid syscall name '{}'", value))?;
syscalls.push(syscall);
}
Ok(Self { inverse, syscalls })
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_filter() {
assert_eq!(
"openat,mmap".parse(),
Ok(Filter {
inverse: false,
syscalls: vec![Sysno::openat, Sysno::mmap]
})
);
assert_eq!(
"openat,foobar".parse::<Filter>(),
Err("invalid syscall name 'foobar'".into())
);
assert_eq!(
"!read,write".parse(),
Ok(Filter {
inverse: true,
syscalls: vec![Sysno::read, Sysno::write]
})
);
}
}
|
use core::fmt;
use core::marker::PhantomData;
use conquer_pointer::{MarkedNonNull, MarkedPtr};
use crate::traits::Reclaim;
use crate::{Protected, Shared};
/********** impl Clone ****************************************************************************/
impl<T, R, const N: usize> Clone for Shared<'_, T, R, N> {
#[inline]
fn clone(&self) -> Self {
Self { inner: self.inner, _marker: PhantomData }
}
}
/********** impl Copy *****************************************************************************/
impl<T, R, const N: usize> Copy for Shared<'_, T, R, N> {}
/********** impl inherent (const) *****************************************************************/
impl<T, R, const N: usize> Shared<'_, T, R, N> {
pub const unsafe fn cast<'a, U>(self) -> Shared<'a, U, R, N> {
Shared { inner: self.inner.cast(), _marker: PhantomData }
}
}
/********** impl inherent *************************************************************************/
impl<'g, T, R: Reclaim<T>, const N: usize> Shared<'g, T, R, N> {
impl_from_ptr!();
impl_from_non_null!();
impl_common!();
#[inline]
pub fn into_protected(self) -> Protected<'g, T, R, N> {
Protected { inner: self.inner.into_marked_ptr(), _marker: PhantomData }
}
/// De-references the [`Shared`] reference.
///
/// # Safety
///
/// Since [`Shared`]s can not be `null` and can only be (safely) created
/// by protecting their referenced value from concurrent reclamation,
/// de-referencing them is generally sound.
/// However, it does require the caller to ensure correct synchronization
/// and especially memory orderings are in place.
/// Consider the following example:
///
/// ```
/// use core::sync::atomic::Ordering;
///
/// use conquer_reclaim::leak::{Atomic, Guard, Owned, Shared};
/// use conquer_reclaim::typenum::U0;
///
/// #[derive(Default)]
/// struct Foo {
/// bar: i32,
/// }
///
/// static GLOBAL: Atomic<Foo, U0> = Atomic::null();
///
/// // ...in thread 1
/// let mut owned = Owned::new(Default::default());
/// owned.bar = -1;
///
/// GLOBAL.store(owned, Ordering::Release);
///
/// // ...in thread 2
/// if let NotNull(shared) = GLOBAL.load(&mut &Guard, Ordering::Acquire) {
/// let foo = unsafe { shared.deref() };
/// assert_eq!(foo.bar, -1);
/// }
/// ```
///
/// Due to the correct pairing of [`Acquire`][acq] and [`Release`][rel] in
/// this example calling `deref` in thread 2 is sound.
/// If, however, both memory orderings were set to [`Relaxed`][rlx], this
/// would not be case, since the compiler/cpu would be allowed to re-order
/// the write `owned.bar = -1` after the write (store) to `GLOBAL`, in which
/// case there could be data-race when reading `foo.bar` in thread 2.
/// Calling `deref` is **always** sound when [`SeqCst`][scs] is used
/// exclusively.
///
/// [acq]: core::sync::atomic::Ordering::Acquire
/// [rel]: core::sync::atomic::Ordering::Release
/// [rlx]: core::sync::atomic::Ordering::Relaxed
/// [scs]: core::sync::atomic::Ordering::SeqCst
#[inline]
pub unsafe fn as_ref(self) -> &'g T {
&*self.inner.decompose_ptr()
}
/// Decomposes and de-references the [`Shared`] reference and returns both
/// the reference and its tag value.
///
/// # Safety
///
/// See [`as_ref`][Shared::as_ref] for an explanation of the safety concerns
/// involved in de-referencing a [`Shared`].
#[inline]
pub unsafe fn decompose_ref(self) -> (&'g T, usize) {
let (ptr, tag) = self.inner.decompose();
(&*ptr.as_ptr(), tag)
}
}
/********** impl Debug ****************************************************************************/
impl<T: fmt::Debug, R, const N: usize> fmt::Debug for Shared<'_, T, R, N> {
impl_fmt_debug!(Shared);
}
/********** impl Pointer **************************************************************************/
impl<T, R, const N: usize> fmt::Pointer for Shared<'_, T, R, N> {
impl_fmt_pointer!();
}
|
#![doc = "generated by AutoRust 0.1.0"]
#![allow(unused_mut)]
#![allow(unused_variables)]
#![allow(unused_imports)]
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub mod galleries {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn get(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
gallery_name: &str,
select: Option<&str>,
) -> std::result::Result<Gallery, get::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Compute/galleries/{}",
&operation_config.base_path, subscription_id, resource_group_name, gallery_name
);
let mut req_builder = client.get(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(get::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
if let Some(select) = select {
req_builder = req_builder.query(&[("$select", select)]);
}
let req = req_builder.build().context(get::BuildRequestError)?;
let rsp = client.execute(req).await.context(get::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(get::ResponseBytesError)?;
let rsp_value: Gallery = serde_json::from_slice(&body).context(get::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(get::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(get::DeserializeError { body })?;
get::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod get {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::CloudError,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
pub async fn create_or_update(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
gallery_name: &str,
gallery: &Gallery,
) -> std::result::Result<create_or_update::Response, create_or_update::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Compute/galleries/{}",
&operation_config.base_path, subscription_id, resource_group_name, gallery_name
);
let mut req_builder = client.put(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(create_or_update::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
req_builder = req_builder.json(gallery);
let req = req_builder.build().context(create_or_update::BuildRequestError)?;
let rsp = client.execute(req).await.context(create_or_update::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(create_or_update::ResponseBytesError)?;
let rsp_value: Gallery = serde_json::from_slice(&body).context(create_or_update::DeserializeError { body })?;
Ok(create_or_update::Response::Ok200(rsp_value))
}
StatusCode::CREATED => {
let body: bytes::Bytes = rsp.bytes().await.context(create_or_update::ResponseBytesError)?;
let rsp_value: Gallery = serde_json::from_slice(&body).context(create_or_update::DeserializeError { body })?;
Ok(create_or_update::Response::Created201(rsp_value))
}
StatusCode::ACCEPTED => {
let body: bytes::Bytes = rsp.bytes().await.context(create_or_update::ResponseBytesError)?;
let rsp_value: Gallery = serde_json::from_slice(&body).context(create_or_update::DeserializeError { body })?;
Ok(create_or_update::Response::Accepted202(rsp_value))
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(create_or_update::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(create_or_update::DeserializeError { body })?;
create_or_update::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod create_or_update {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Ok200(Gallery),
Created201(Gallery),
Accepted202(Gallery),
}
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::CloudError,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
pub async fn update(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
gallery_name: &str,
gallery: &GalleryUpdate,
) -> std::result::Result<Gallery, update::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Compute/galleries/{}",
&operation_config.base_path, subscription_id, resource_group_name, gallery_name
);
let mut req_builder = client.patch(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(update::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
req_builder = req_builder.json(gallery);
let req = req_builder.build().context(update::BuildRequestError)?;
let rsp = client.execute(req).await.context(update::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(update::ResponseBytesError)?;
let rsp_value: Gallery = serde_json::from_slice(&body).context(update::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(update::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(update::DeserializeError { body })?;
update::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod update {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::CloudError,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
pub async fn delete(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
gallery_name: &str,
) -> std::result::Result<delete::Response, delete::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Compute/galleries/{}",
&operation_config.base_path, subscription_id, resource_group_name, gallery_name
);
let mut req_builder = client.delete(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(delete::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
let req = req_builder.build().context(delete::BuildRequestError)?;
let rsp = client.execute(req).await.context(delete::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => Ok(delete::Response::Ok200),
StatusCode::ACCEPTED => Ok(delete::Response::Accepted202),
StatusCode::NO_CONTENT => Ok(delete::Response::NoContent204),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(delete::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(delete::DeserializeError { body })?;
delete::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod delete {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Ok200,
Accepted202,
NoContent204,
}
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::CloudError,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
pub async fn list_by_resource_group(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
) -> std::result::Result<GalleryList, list_by_resource_group::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Compute/galleries",
&operation_config.base_path, subscription_id, resource_group_name
);
let mut req_builder = client.get(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(list_by_resource_group::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
let req = req_builder.build().context(list_by_resource_group::BuildRequestError)?;
let rsp = client.execute(req).await.context(list_by_resource_group::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(list_by_resource_group::ResponseBytesError)?;
let rsp_value: GalleryList = serde_json::from_slice(&body).context(list_by_resource_group::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(list_by_resource_group::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(list_by_resource_group::DeserializeError { body })?;
list_by_resource_group::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod list_by_resource_group {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::CloudError,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
pub async fn list(operation_config: &crate::OperationConfig, subscription_id: &str) -> std::result::Result<GalleryList, list::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/providers/Microsoft.Compute/galleries",
&operation_config.base_path, subscription_id
);
let mut req_builder = client.get(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(list::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
let req = req_builder.build().context(list::BuildRequestError)?;
let rsp = client.execute(req).await.context(list::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(list::ResponseBytesError)?;
let rsp_value: GalleryList = serde_json::from_slice(&body).context(list::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(list::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(list::DeserializeError { body })?;
list::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod list {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::CloudError,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
}
pub mod gallery_images {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn get(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
gallery_name: &str,
gallery_image_name: &str,
) -> std::result::Result<GalleryImage, get::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Compute/galleries/{}/images/{}",
&operation_config.base_path, subscription_id, resource_group_name, gallery_name, gallery_image_name
);
let mut req_builder = client.get(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(get::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
let req = req_builder.build().context(get::BuildRequestError)?;
let rsp = client.execute(req).await.context(get::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(get::ResponseBytesError)?;
let rsp_value: GalleryImage = serde_json::from_slice(&body).context(get::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(get::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(get::DeserializeError { body })?;
get::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod get {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::CloudError,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
pub async fn create_or_update(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
gallery_name: &str,
gallery_image_name: &str,
gallery_image: &GalleryImage,
) -> std::result::Result<create_or_update::Response, create_or_update::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Compute/galleries/{}/images/{}",
&operation_config.base_path, subscription_id, resource_group_name, gallery_name, gallery_image_name
);
let mut req_builder = client.put(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(create_or_update::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
req_builder = req_builder.json(gallery_image);
let req = req_builder.build().context(create_or_update::BuildRequestError)?;
let rsp = client.execute(req).await.context(create_or_update::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(create_or_update::ResponseBytesError)?;
let rsp_value: GalleryImage = serde_json::from_slice(&body).context(create_or_update::DeserializeError { body })?;
Ok(create_or_update::Response::Ok200(rsp_value))
}
StatusCode::CREATED => {
let body: bytes::Bytes = rsp.bytes().await.context(create_or_update::ResponseBytesError)?;
let rsp_value: GalleryImage = serde_json::from_slice(&body).context(create_or_update::DeserializeError { body })?;
Ok(create_or_update::Response::Created201(rsp_value))
}
StatusCode::ACCEPTED => {
let body: bytes::Bytes = rsp.bytes().await.context(create_or_update::ResponseBytesError)?;
let rsp_value: GalleryImage = serde_json::from_slice(&body).context(create_or_update::DeserializeError { body })?;
Ok(create_or_update::Response::Accepted202(rsp_value))
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(create_or_update::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(create_or_update::DeserializeError { body })?;
create_or_update::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod create_or_update {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Ok200(GalleryImage),
Created201(GalleryImage),
Accepted202(GalleryImage),
}
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::CloudError,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
pub async fn update(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
gallery_name: &str,
gallery_image_name: &str,
gallery_image: &GalleryImageUpdate,
) -> std::result::Result<GalleryImage, update::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Compute/galleries/{}/images/{}",
&operation_config.base_path, subscription_id, resource_group_name, gallery_name, gallery_image_name
);
let mut req_builder = client.patch(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(update::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
req_builder = req_builder.json(gallery_image);
let req = req_builder.build().context(update::BuildRequestError)?;
let rsp = client.execute(req).await.context(update::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(update::ResponseBytesError)?;
let rsp_value: GalleryImage = serde_json::from_slice(&body).context(update::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(update::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(update::DeserializeError { body })?;
update::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod update {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::CloudError,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
pub async fn delete(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
gallery_name: &str,
gallery_image_name: &str,
) -> std::result::Result<delete::Response, delete::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Compute/galleries/{}/images/{}",
&operation_config.base_path, subscription_id, resource_group_name, gallery_name, gallery_image_name
);
let mut req_builder = client.delete(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(delete::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
let req = req_builder.build().context(delete::BuildRequestError)?;
let rsp = client.execute(req).await.context(delete::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => Ok(delete::Response::Ok200),
StatusCode::ACCEPTED => Ok(delete::Response::Accepted202),
StatusCode::NO_CONTENT => Ok(delete::Response::NoContent204),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(delete::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(delete::DeserializeError { body })?;
delete::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod delete {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Ok200,
Accepted202,
NoContent204,
}
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::CloudError,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
pub async fn list_by_gallery(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
gallery_name: &str,
) -> std::result::Result<GalleryImageList, list_by_gallery::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Compute/galleries/{}/images",
&operation_config.base_path, subscription_id, resource_group_name, gallery_name
);
let mut req_builder = client.get(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(list_by_gallery::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
let req = req_builder.build().context(list_by_gallery::BuildRequestError)?;
let rsp = client.execute(req).await.context(list_by_gallery::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(list_by_gallery::ResponseBytesError)?;
let rsp_value: GalleryImageList = serde_json::from_slice(&body).context(list_by_gallery::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(list_by_gallery::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(list_by_gallery::DeserializeError { body })?;
list_by_gallery::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod list_by_gallery {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::CloudError,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
}
pub mod gallery_image_versions {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn get(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
gallery_name: &str,
gallery_image_name: &str,
gallery_image_version_name: &str,
expand: Option<&str>,
) -> std::result::Result<GalleryImageVersion, get::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Compute/galleries/{}/images/{}/versions/{}",
&operation_config.base_path, subscription_id, resource_group_name, gallery_name, gallery_image_name, gallery_image_version_name
);
let mut req_builder = client.get(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(get::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
if let Some(expand) = expand {
req_builder = req_builder.query(&[("$expand", expand)]);
}
let req = req_builder.build().context(get::BuildRequestError)?;
let rsp = client.execute(req).await.context(get::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(get::ResponseBytesError)?;
let rsp_value: GalleryImageVersion = serde_json::from_slice(&body).context(get::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(get::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(get::DeserializeError { body })?;
get::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod get {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::CloudError,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
pub async fn create_or_update(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
gallery_name: &str,
gallery_image_name: &str,
gallery_image_version_name: &str,
gallery_image_version: &GalleryImageVersion,
) -> std::result::Result<create_or_update::Response, create_or_update::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Compute/galleries/{}/images/{}/versions/{}",
&operation_config.base_path, subscription_id, resource_group_name, gallery_name, gallery_image_name, gallery_image_version_name
);
let mut req_builder = client.put(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(create_or_update::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
req_builder = req_builder.json(gallery_image_version);
let req = req_builder.build().context(create_or_update::BuildRequestError)?;
let rsp = client.execute(req).await.context(create_or_update::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(create_or_update::ResponseBytesError)?;
let rsp_value: GalleryImageVersion = serde_json::from_slice(&body).context(create_or_update::DeserializeError { body })?;
Ok(create_or_update::Response::Ok200(rsp_value))
}
StatusCode::CREATED => {
let body: bytes::Bytes = rsp.bytes().await.context(create_or_update::ResponseBytesError)?;
let rsp_value: GalleryImageVersion = serde_json::from_slice(&body).context(create_or_update::DeserializeError { body })?;
Ok(create_or_update::Response::Created201(rsp_value))
}
StatusCode::ACCEPTED => {
let body: bytes::Bytes = rsp.bytes().await.context(create_or_update::ResponseBytesError)?;
let rsp_value: GalleryImageVersion = serde_json::from_slice(&body).context(create_or_update::DeserializeError { body })?;
Ok(create_or_update::Response::Accepted202(rsp_value))
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(create_or_update::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(create_or_update::DeserializeError { body })?;
create_or_update::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod create_or_update {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Ok200(GalleryImageVersion),
Created201(GalleryImageVersion),
Accepted202(GalleryImageVersion),
}
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::CloudError,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
pub async fn update(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
gallery_name: &str,
gallery_image_name: &str,
gallery_image_version_name: &str,
gallery_image_version: &GalleryImageVersionUpdate,
) -> std::result::Result<GalleryImageVersion, update::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Compute/galleries/{}/images/{}/versions/{}",
&operation_config.base_path, subscription_id, resource_group_name, gallery_name, gallery_image_name, gallery_image_version_name
);
let mut req_builder = client.patch(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(update::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
req_builder = req_builder.json(gallery_image_version);
let req = req_builder.build().context(update::BuildRequestError)?;
let rsp = client.execute(req).await.context(update::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(update::ResponseBytesError)?;
let rsp_value: GalleryImageVersion = serde_json::from_slice(&body).context(update::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(update::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(update::DeserializeError { body })?;
update::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod update {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::CloudError,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
pub async fn delete(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
gallery_name: &str,
gallery_image_name: &str,
gallery_image_version_name: &str,
) -> std::result::Result<delete::Response, delete::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Compute/galleries/{}/images/{}/versions/{}",
&operation_config.base_path, subscription_id, resource_group_name, gallery_name, gallery_image_name, gallery_image_version_name
);
let mut req_builder = client.delete(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(delete::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
let req = req_builder.build().context(delete::BuildRequestError)?;
let rsp = client.execute(req).await.context(delete::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => Ok(delete::Response::Ok200),
StatusCode::ACCEPTED => Ok(delete::Response::Accepted202),
StatusCode::NO_CONTENT => Ok(delete::Response::NoContent204),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(delete::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(delete::DeserializeError { body })?;
delete::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod delete {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Ok200,
Accepted202,
NoContent204,
}
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::CloudError,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
pub async fn list_by_gallery_image(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
gallery_name: &str,
gallery_image_name: &str,
) -> std::result::Result<GalleryImageVersionList, list_by_gallery_image::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Compute/galleries/{}/images/{}/versions",
&operation_config.base_path, subscription_id, resource_group_name, gallery_name, gallery_image_name
);
let mut req_builder = client.get(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(list_by_gallery_image::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
let req = req_builder.build().context(list_by_gallery_image::BuildRequestError)?;
let rsp = client.execute(req).await.context(list_by_gallery_image::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(list_by_gallery_image::ResponseBytesError)?;
let rsp_value: GalleryImageVersionList =
serde_json::from_slice(&body).context(list_by_gallery_image::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(list_by_gallery_image::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(list_by_gallery_image::DeserializeError { body })?;
list_by_gallery_image::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod list_by_gallery_image {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::CloudError,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
}
pub mod gallery_applications {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn get(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
gallery_name: &str,
gallery_application_name: &str,
) -> std::result::Result<GalleryApplication, get::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Compute/galleries/{}/applications/{}",
&operation_config.base_path, subscription_id, resource_group_name, gallery_name, gallery_application_name
);
let mut req_builder = client.get(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(get::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
let req = req_builder.build().context(get::BuildRequestError)?;
let rsp = client.execute(req).await.context(get::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(get::ResponseBytesError)?;
let rsp_value: GalleryApplication = serde_json::from_slice(&body).context(get::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(get::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(get::DeserializeError { body })?;
get::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod get {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::CloudError,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
pub async fn create_or_update(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
gallery_name: &str,
gallery_application_name: &str,
gallery_application: &GalleryApplication,
) -> std::result::Result<create_or_update::Response, create_or_update::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Compute/galleries/{}/applications/{}",
&operation_config.base_path, subscription_id, resource_group_name, gallery_name, gallery_application_name
);
let mut req_builder = client.put(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(create_or_update::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
req_builder = req_builder.json(gallery_application);
let req = req_builder.build().context(create_or_update::BuildRequestError)?;
let rsp = client.execute(req).await.context(create_or_update::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(create_or_update::ResponseBytesError)?;
let rsp_value: GalleryApplication = serde_json::from_slice(&body).context(create_or_update::DeserializeError { body })?;
Ok(create_or_update::Response::Ok200(rsp_value))
}
StatusCode::CREATED => {
let body: bytes::Bytes = rsp.bytes().await.context(create_or_update::ResponseBytesError)?;
let rsp_value: GalleryApplication = serde_json::from_slice(&body).context(create_or_update::DeserializeError { body })?;
Ok(create_or_update::Response::Created201(rsp_value))
}
StatusCode::ACCEPTED => {
let body: bytes::Bytes = rsp.bytes().await.context(create_or_update::ResponseBytesError)?;
let rsp_value: GalleryApplication = serde_json::from_slice(&body).context(create_or_update::DeserializeError { body })?;
Ok(create_or_update::Response::Accepted202(rsp_value))
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(create_or_update::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(create_or_update::DeserializeError { body })?;
create_or_update::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod create_or_update {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Ok200(GalleryApplication),
Created201(GalleryApplication),
Accepted202(GalleryApplication),
}
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::CloudError,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
pub async fn update(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
gallery_name: &str,
gallery_application_name: &str,
gallery_application: &GalleryApplicationUpdate,
) -> std::result::Result<GalleryApplication, update::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Compute/galleries/{}/applications/{}",
&operation_config.base_path, subscription_id, resource_group_name, gallery_name, gallery_application_name
);
let mut req_builder = client.patch(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(update::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
req_builder = req_builder.json(gallery_application);
let req = req_builder.build().context(update::BuildRequestError)?;
let rsp = client.execute(req).await.context(update::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(update::ResponseBytesError)?;
let rsp_value: GalleryApplication = serde_json::from_slice(&body).context(update::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(update::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(update::DeserializeError { body })?;
update::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod update {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::CloudError,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
pub async fn delete(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
gallery_name: &str,
gallery_application_name: &str,
) -> std::result::Result<delete::Response, delete::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Compute/galleries/{}/applications/{}",
&operation_config.base_path, subscription_id, resource_group_name, gallery_name, gallery_application_name
);
let mut req_builder = client.delete(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(delete::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
let req = req_builder.build().context(delete::BuildRequestError)?;
let rsp = client.execute(req).await.context(delete::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => Ok(delete::Response::Ok200),
StatusCode::ACCEPTED => Ok(delete::Response::Accepted202),
StatusCode::NO_CONTENT => Ok(delete::Response::NoContent204),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(delete::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(delete::DeserializeError { body })?;
delete::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod delete {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Ok200,
Accepted202,
NoContent204,
}
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::CloudError,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
pub async fn list_by_gallery(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
gallery_name: &str,
) -> std::result::Result<GalleryApplicationList, list_by_gallery::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Compute/galleries/{}/applications",
&operation_config.base_path, subscription_id, resource_group_name, gallery_name
);
let mut req_builder = client.get(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(list_by_gallery::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
let req = req_builder.build().context(list_by_gallery::BuildRequestError)?;
let rsp = client.execute(req).await.context(list_by_gallery::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(list_by_gallery::ResponseBytesError)?;
let rsp_value: GalleryApplicationList =
serde_json::from_slice(&body).context(list_by_gallery::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(list_by_gallery::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(list_by_gallery::DeserializeError { body })?;
list_by_gallery::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod list_by_gallery {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::CloudError,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
}
pub mod gallery_application_versions {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn get(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
gallery_name: &str,
gallery_application_name: &str,
gallery_application_version_name: &str,
expand: Option<&str>,
) -> std::result::Result<GalleryApplicationVersion, get::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Compute/galleries/{}/applications/{}/versions/{}",
&operation_config.base_path,
subscription_id,
resource_group_name,
gallery_name,
gallery_application_name,
gallery_application_version_name
);
let mut req_builder = client.get(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(get::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
if let Some(expand) = expand {
req_builder = req_builder.query(&[("$expand", expand)]);
}
let req = req_builder.build().context(get::BuildRequestError)?;
let rsp = client.execute(req).await.context(get::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(get::ResponseBytesError)?;
let rsp_value: GalleryApplicationVersion = serde_json::from_slice(&body).context(get::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(get::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(get::DeserializeError { body })?;
get::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod get {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::CloudError,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
pub async fn create_or_update(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
gallery_name: &str,
gallery_application_name: &str,
gallery_application_version_name: &str,
gallery_application_version: &GalleryApplicationVersion,
) -> std::result::Result<create_or_update::Response, create_or_update::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Compute/galleries/{}/applications/{}/versions/{}",
&operation_config.base_path,
subscription_id,
resource_group_name,
gallery_name,
gallery_application_name,
gallery_application_version_name
);
let mut req_builder = client.put(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(create_or_update::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
req_builder = req_builder.json(gallery_application_version);
let req = req_builder.build().context(create_or_update::BuildRequestError)?;
let rsp = client.execute(req).await.context(create_or_update::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(create_or_update::ResponseBytesError)?;
let rsp_value: GalleryApplicationVersion =
serde_json::from_slice(&body).context(create_or_update::DeserializeError { body })?;
Ok(create_or_update::Response::Ok200(rsp_value))
}
StatusCode::CREATED => {
let body: bytes::Bytes = rsp.bytes().await.context(create_or_update::ResponseBytesError)?;
let rsp_value: GalleryApplicationVersion =
serde_json::from_slice(&body).context(create_or_update::DeserializeError { body })?;
Ok(create_or_update::Response::Created201(rsp_value))
}
StatusCode::ACCEPTED => {
let body: bytes::Bytes = rsp.bytes().await.context(create_or_update::ResponseBytesError)?;
let rsp_value: GalleryApplicationVersion =
serde_json::from_slice(&body).context(create_or_update::DeserializeError { body })?;
Ok(create_or_update::Response::Accepted202(rsp_value))
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(create_or_update::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(create_or_update::DeserializeError { body })?;
create_or_update::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod create_or_update {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Ok200(GalleryApplicationVersion),
Created201(GalleryApplicationVersion),
Accepted202(GalleryApplicationVersion),
}
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::CloudError,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
pub async fn update(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
gallery_name: &str,
gallery_application_name: &str,
gallery_application_version_name: &str,
gallery_application_version: &GalleryApplicationVersionUpdate,
) -> std::result::Result<GalleryApplicationVersion, update::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Compute/galleries/{}/applications/{}/versions/{}",
&operation_config.base_path,
subscription_id,
resource_group_name,
gallery_name,
gallery_application_name,
gallery_application_version_name
);
let mut req_builder = client.patch(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(update::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
req_builder = req_builder.json(gallery_application_version);
let req = req_builder.build().context(update::BuildRequestError)?;
let rsp = client.execute(req).await.context(update::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(update::ResponseBytesError)?;
let rsp_value: GalleryApplicationVersion = serde_json::from_slice(&body).context(update::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(update::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(update::DeserializeError { body })?;
update::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod update {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::CloudError,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
pub async fn delete(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
gallery_name: &str,
gallery_application_name: &str,
gallery_application_version_name: &str,
) -> std::result::Result<delete::Response, delete::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Compute/galleries/{}/applications/{}/versions/{}",
&operation_config.base_path,
subscription_id,
resource_group_name,
gallery_name,
gallery_application_name,
gallery_application_version_name
);
let mut req_builder = client.delete(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(delete::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
let req = req_builder.build().context(delete::BuildRequestError)?;
let rsp = client.execute(req).await.context(delete::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => Ok(delete::Response::Ok200),
StatusCode::ACCEPTED => Ok(delete::Response::Accepted202),
StatusCode::NO_CONTENT => Ok(delete::Response::NoContent204),
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(delete::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(delete::DeserializeError { body })?;
delete::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod delete {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Ok200,
Accepted202,
NoContent204,
}
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::CloudError,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
pub async fn list_by_gallery_application(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
gallery_name: &str,
gallery_application_name: &str,
) -> std::result::Result<GalleryApplicationVersionList, list_by_gallery_application::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Compute/galleries/{}/applications/{}/versions",
&operation_config.base_path, subscription_id, resource_group_name, gallery_name, gallery_application_name
);
let mut req_builder = client.get(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(list_by_gallery_application::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
let req = req_builder.build().context(list_by_gallery_application::BuildRequestError)?;
let rsp = client
.execute(req)
.await
.context(list_by_gallery_application::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(list_by_gallery_application::ResponseBytesError)?;
let rsp_value: GalleryApplicationVersionList =
serde_json::from_slice(&body).context(list_by_gallery_application::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(list_by_gallery_application::ResponseBytesError)?;
let rsp_value: CloudError =
serde_json::from_slice(&body).context(list_by_gallery_application::DeserializeError { body })?;
list_by_gallery_application::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod list_by_gallery_application {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::CloudError,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
}
pub mod gallery_sharing_profile {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn update(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
gallery_name: &str,
sharing_update: &SharingUpdate,
) -> std::result::Result<update::Response, update::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Compute/galleries/{}/share",
&operation_config.base_path, subscription_id, resource_group_name, gallery_name
);
let mut req_builder = client.post(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(update::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
req_builder = req_builder.json(sharing_update);
let req = req_builder.build().context(update::BuildRequestError)?;
let rsp = client.execute(req).await.context(update::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(update::ResponseBytesError)?;
let rsp_value: SharingUpdate = serde_json::from_slice(&body).context(update::DeserializeError { body })?;
Ok(update::Response::Ok200(rsp_value))
}
StatusCode::ACCEPTED => {
let body: bytes::Bytes = rsp.bytes().await.context(update::ResponseBytesError)?;
let rsp_value: SharingUpdate = serde_json::from_slice(&body).context(update::DeserializeError { body })?;
Ok(update::Response::Accepted202(rsp_value))
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(update::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(update::DeserializeError { body })?;
update::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod update {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Ok200(SharingUpdate),
Accepted202(SharingUpdate),
}
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::CloudError,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
}
pub mod shared_galleries {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn list(
operation_config: &crate::OperationConfig,
subscription_id: &str,
location: &str,
shared_to: Option<&str>,
) -> std::result::Result<SharedGalleryList, list::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/providers/Microsoft.Compute/locations/{}/sharedGalleries",
&operation_config.base_path, subscription_id, location
);
let mut req_builder = client.get(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(list::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
if let Some(shared_to) = shared_to {
req_builder = req_builder.query(&[("sharedTo", shared_to)]);
}
let req = req_builder.build().context(list::BuildRequestError)?;
let rsp = client.execute(req).await.context(list::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(list::ResponseBytesError)?;
let rsp_value: SharedGalleryList = serde_json::from_slice(&body).context(list::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(list::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(list::DeserializeError { body })?;
list::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod list {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::CloudError,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
pub async fn get(
operation_config: &crate::OperationConfig,
subscription_id: &str,
location: &str,
gallery_unique_name: &str,
) -> std::result::Result<SharedGallery, get::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/providers/Microsoft.Compute/locations/{}/sharedGalleries/{}",
&operation_config.base_path, subscription_id, location, gallery_unique_name
);
let mut req_builder = client.get(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(get::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
let req = req_builder.build().context(get::BuildRequestError)?;
let rsp = client.execute(req).await.context(get::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(get::ResponseBytesError)?;
let rsp_value: SharedGallery = serde_json::from_slice(&body).context(get::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(get::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(get::DeserializeError { body })?;
get::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod get {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::CloudError,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
}
pub mod shared_gallery_images {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn list(
operation_config: &crate::OperationConfig,
subscription_id: &str,
location: &str,
gallery_unique_name: &str,
shared_to: Option<&str>,
) -> std::result::Result<SharedGalleryImageList, list::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/providers/Microsoft.Compute/locations/{}/sharedGalleries/{}/images",
&operation_config.base_path, subscription_id, location, gallery_unique_name
);
let mut req_builder = client.get(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(list::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
if let Some(shared_to) = shared_to {
req_builder = req_builder.query(&[("sharedTo", shared_to)]);
}
let req = req_builder.build().context(list::BuildRequestError)?;
let rsp = client.execute(req).await.context(list::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(list::ResponseBytesError)?;
let rsp_value: SharedGalleryImageList = serde_json::from_slice(&body).context(list::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(list::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(list::DeserializeError { body })?;
list::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod list {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::CloudError,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
pub async fn get(
operation_config: &crate::OperationConfig,
subscription_id: &str,
location: &str,
gallery_unique_name: &str,
gallery_image_name: &str,
) -> std::result::Result<SharedGalleryImage, get::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/providers/Microsoft.Compute/locations/{}/sharedGalleries/{}/images/{}",
&operation_config.base_path, subscription_id, location, gallery_unique_name, gallery_image_name
);
let mut req_builder = client.get(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(get::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
let req = req_builder.build().context(get::BuildRequestError)?;
let rsp = client.execute(req).await.context(get::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(get::ResponseBytesError)?;
let rsp_value: SharedGalleryImage = serde_json::from_slice(&body).context(get::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(get::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(get::DeserializeError { body })?;
get::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod get {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::CloudError,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
}
pub mod shared_gallery_image_versions {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn list(
operation_config: &crate::OperationConfig,
subscription_id: &str,
location: &str,
gallery_unique_name: &str,
gallery_image_name: &str,
shared_to: Option<&str>,
) -> std::result::Result<SharedGalleryImageVersionList, list::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/providers/Microsoft.Compute/locations/{}/sharedGalleries/{}/images/{}/versions",
&operation_config.base_path, subscription_id, location, gallery_unique_name, gallery_image_name
);
let mut req_builder = client.get(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(list::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
if let Some(shared_to) = shared_to {
req_builder = req_builder.query(&[("sharedTo", shared_to)]);
}
let req = req_builder.build().context(list::BuildRequestError)?;
let rsp = client.execute(req).await.context(list::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(list::ResponseBytesError)?;
let rsp_value: SharedGalleryImageVersionList = serde_json::from_slice(&body).context(list::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(list::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(list::DeserializeError { body })?;
list::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod list {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::CloudError,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
pub async fn get(
operation_config: &crate::OperationConfig,
subscription_id: &str,
location: &str,
gallery_unique_name: &str,
gallery_image_name: &str,
gallery_image_version_name: &str,
) -> std::result::Result<SharedGalleryImageVersion, get::Error> {
let client = &operation_config.client;
let uri_str = &format!(
"{}/subscriptions/{}/providers/Microsoft.Compute/locations/{}/sharedGalleries/{}/images/{}/versions/{}",
&operation_config.base_path, subscription_id, location, gallery_unique_name, gallery_image_name, gallery_image_version_name
);
let mut req_builder = client.get(uri_str);
if let Some(token_credential) = &operation_config.token_credential {
let token_response = token_credential
.get_token(&operation_config.token_credential_resource)
.await
.context(get::GetTokenError)?;
req_builder = req_builder.bearer_auth(token_response.token.secret());
}
req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]);
let req = req_builder.build().context(get::BuildRequestError)?;
let rsp = client.execute(req).await.context(get::ExecuteRequestError)?;
match rsp.status() {
StatusCode::OK => {
let body: bytes::Bytes = rsp.bytes().await.context(get::ResponseBytesError)?;
let rsp_value: SharedGalleryImageVersion = serde_json::from_slice(&body).context(get::DeserializeError { body })?;
Ok(rsp_value)
}
status_code => {
let body: bytes::Bytes = rsp.bytes().await.context(get::ResponseBytesError)?;
let rsp_value: CloudError = serde_json::from_slice(&body).context(get::DeserializeError { body })?;
get::DefaultResponse {
status_code,
value: rsp_value,
}
.fail()
}
}
}
pub mod get {
use crate::{models, models::*};
use reqwest::StatusCode;
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
DefaultResponse {
status_code: StatusCode,
value: models::CloudError,
},
BuildRequestError {
source: reqwest::Error,
},
ExecuteRequestError {
source: reqwest::Error,
},
ResponseBytesError {
source: reqwest::Error,
},
DeserializeError {
source: serde_json::Error,
body: bytes::Bytes,
},
GetTokenError {
source: azure_core::errors::AzureError,
},
}
}
}
|
pub use self::users::*;
mod users; |
#[deriving(Show, FromPrimitive)]
pub enum Color {
Black = 0,
Blue = 1,
Green = 2,
Cyan = 3,
Red = 4,
Pink = 5,
Brown = 6,
LightGray = 7,
DarkGray = 8,
LightBlue = 9,
LightGreen = 10,
LightCyan = 11,
LightRed = 12,
LightPink = 13,
Yellow = 14,
White = 15,
}
struct Char {
pub char: u8,
flags: u8, // 4 bits for foreground and 4 bits for background
}
impl Char {
pub fn new(c: char, fg: Color, bg: Color) -> Char {
Char { char: c as u8, flags: fg as u8 | (bg as u8 << 4) }
}
pub fn background(&self) -> Color {
match FromPrimitive::from_u8(self.flags >> 4 as u8) {
Some(color) => color,
None => Black
}
}
pub fn foreground(&self) -> Color {
match FromPrimitive::from_u8(self.flags & 0x0F as u8) {
Some(color) => color,
None => Black
}
}
}
fn main() {
let c = Char::new('f', Green, Black);
println!("foreground: {}, background: {}", c.foreground(), c.background());
}
|
use diesel::prelude::*;
use hyper::{Body, Response};
use nails::error::NailsError;
use nails::Preroute;
use serde::Serialize;
use crate::context::AppCtx;
use crate::models::Tag;
#[derive(Debug, Preroute)]
#[nails(path = "/api/tags")]
pub(crate) struct ListTagsRequest;
#[derive(Debug, Serialize)]
pub(crate) struct ListTagsResponseBody {
tags: Vec<String>,
}
pub(crate) async fn list_tags(
ctx: AppCtx,
_req: ListTagsRequest,
) -> Result<Response<Body>, NailsError> {
use crate::schema::tags::dsl::*;
// TODO: async
let conn = ctx.db.get().unwrap(); // TODO: handle errors
let all_tags = tags.load::<Tag>(&conn).unwrap(); // TODO: handle errors
let body = ListTagsResponseBody {
tags: all_tags.iter().map(|t| t.tag.clone()).collect(),
};
Ok(super::json_response(&body))
}
|
use crate::glsl::Glsl;
use std::{
collections::HashMap,
convert::{TryFrom, TryInto},
};
use syn::{Error, Result, Stmt};
use crate::yasl_expr::YaslExprFunctionScope;
use crate::{yasl_ident::YaslIdent, yasl_item::YaslItem, yasl_type::YaslType};
mod local;
use local::YaslLocal;
#[derive(Debug)]
pub enum YaslStmt {
Item(YaslItem),
Expr(YaslExprFunctionScope),
// ReturnExpr(YaslExprReturnScope),
Local(YaslLocal),
}
impl YaslStmt {
pub fn attempt_type_anotation(&mut self, idents: &HashMap<String, YaslType>) {
match self {
YaslStmt::Local(l) => l.attempt_type_anotation(idents),
YaslStmt::Expr(e) => e.attempt_type_anotation(idents),
_ => {}
}
}
pub fn update_idents(&mut self) -> Vec<YaslIdent> {
match self {
YaslStmt::Local(l) => {
let mut out = Vec::new();
if let Some(i) = l.get_ident() {
out.push(i);
}
out
}
_ => vec![],
}
}
}
impl From<&YaslStmt> for Glsl {
fn from(item: &YaslStmt) -> Glsl {
use YaslStmt::*;
let inner = match item {
Item(i) => i.into(),
Expr(e) => e.into(),
// ReturnExpr(e) => e.into(),
Local(l) => l.into(),
};
inner
}
}
impl TryFrom<Stmt> for YaslStmt {
type Error = Error;
fn try_from(stmt: Stmt) -> Result<Self> {
Ok(match stmt {
Stmt::Item(i) => Self::Item(i.try_into()?),
Stmt::Expr(e) => Self::Expr(e.try_into()?),
Stmt::Semi(e, _) => Self::Expr(e.try_into()?),
Stmt::Local(l) => Self::Local(l.try_into()?),
})
}
}
|
// This file is part of dpdk. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/dpdk/master/COPYRIGHT. No part of dpdk, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file.
// Copyright © 2017 The developers of dpdk. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/dpdk/master/COPYRIGHT.
use super::*;
use ::errno::errno;
use ::libc::c_void;
use ::libc::O_CREAT;
use ::libc::O_EXCL;
use ::libc::timespec;
use ::rust_extra::unlikely;
use ::std::ffi::CStr;
use ::std::marker::PhantomData;
use ::std::mem::uninitialized;
use ::syscall_alt::constants::E;
pub mod queuePairs;
pub mod sharedReceiveQueues;
include!("AddressHandle.rs");
include!("AsynchronousEvent.rs");
include!("Context.rs");
include!("Device.rs");
include!("DeviceListIterator.rs");
include!("ExtendedReliableConnectionDomain.rs");
include!("MemoryRegion.rs");
include!("MemoryWindow.rs");
include!("Port.rs");
include!("ProtectionDomain.rs");
|
use alloc::boxed::Box;
use core::mem::transmute;
use collections::Vec;
use super::c_char;
pub struct CString {
inner: Box<[u8]>
}
impl CString {
pub fn new(bytes: Vec<u8>) -> Result<CString, ()> {
// let bytes = t.into();
match bytes.iter().position(|x| *x == 0) {
Some(i) => Err(()), // (NulError(i, bytes)),
None => Ok(unsafe { CString::from_vec_unchecked(bytes) }),
}
}
pub unsafe fn from_vec_unchecked(mut v: Vec<u8>) -> CString {
v.push(0);
CString { inner: v.into_boxed_slice() }
}
pub fn as_ptr(&self) -> *const c_char {
unsafe { transmute(self.inner.as_ptr()) }
}
}
|
// thread 'rustc' panicked at 'not implemented: NonMutatingUse(ShallowBorrow)'
// prusti-interface/src/environment/loops.rs:117:22
fn main() {
loop {
match Some(1) {
Some(c) if c <= 1 => (),
Some(_) => (),
None => (),
}
}
}
|
/// An enum to represent all characters in the HanifiRohingya block.
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
pub enum HanifiRohingya {
/// \u{10d00}: '𐴀'
LetterA,
/// \u{10d01}: '𐴁'
LetterBa,
/// \u{10d02}: '𐴂'
LetterPa,
/// \u{10d03}: '𐴃'
LetterTa,
/// \u{10d04}: '𐴄'
LetterTta,
/// \u{10d05}: '𐴅'
LetterJa,
/// \u{10d06}: '𐴆'
LetterCa,
/// \u{10d07}: '𐴇'
LetterHa,
/// \u{10d08}: '𐴈'
LetterKha,
/// \u{10d09}: '𐴉'
LetterFa,
/// \u{10d0a}: '𐴊'
LetterDa,
/// \u{10d0b}: '𐴋'
LetterDda,
/// \u{10d0c}: '𐴌'
LetterRa,
/// \u{10d0d}: '𐴍'
LetterRra,
/// \u{10d0e}: '𐴎'
LetterZa,
/// \u{10d0f}: '𐴏'
LetterSa,
/// \u{10d10}: '𐴐'
LetterSha,
/// \u{10d11}: '𐴑'
LetterKa,
/// \u{10d12}: '𐴒'
LetterGa,
/// \u{10d13}: '𐴓'
LetterLa,
/// \u{10d14}: '𐴔'
LetterMa,
/// \u{10d15}: '𐴕'
LetterNa,
/// \u{10d16}: '𐴖'
LetterWa,
/// \u{10d17}: '𐴗'
LetterKinnaWa,
/// \u{10d18}: '𐴘'
LetterYa,
/// \u{10d19}: '𐴙'
LetterKinnaYa,
/// \u{10d1a}: '𐴚'
LetterNga,
/// \u{10d1b}: '𐴛'
LetterNya,
/// \u{10d1c}: '𐴜'
LetterVa,
/// \u{10d1d}: '𐴝'
VowelA,
/// \u{10d1e}: '𐴞'
VowelI,
/// \u{10d1f}: '𐴟'
VowelU,
/// \u{10d20}: '𐴠'
VowelE,
/// \u{10d21}: '𐴡'
VowelO,
/// \u{10d22}: '𐴢'
MarkSakin,
/// \u{10d23}: '𐴣'
MarkNaKhonna,
/// \u{10d24}: '𐴤'
SignHarbahay,
/// \u{10d25}: '𐴥'
SignTahala,
/// \u{10d26}: '𐴦'
SignTana,
/// \u{10d27}: '𐴧'
SignTassi,
/// \u{10d30}: '𐴰'
DigitZero,
/// \u{10d31}: '𐴱'
DigitOne,
/// \u{10d32}: '𐴲'
DigitTwo,
/// \u{10d33}: '𐴳'
DigitThree,
/// \u{10d34}: '𐴴'
DigitFour,
/// \u{10d35}: '𐴵'
DigitFive,
/// \u{10d36}: '𐴶'
DigitSix,
/// \u{10d37}: '𐴷'
DigitSeven,
/// \u{10d38}: '𐴸'
DigitEight,
/// \u{10d39}: '𐴹'
DigitNine,
}
impl Into<char> for HanifiRohingya {
fn into(self) -> char {
match self {
HanifiRohingya::LetterA => '𐴀',
HanifiRohingya::LetterBa => '𐴁',
HanifiRohingya::LetterPa => '𐴂',
HanifiRohingya::LetterTa => '𐴃',
HanifiRohingya::LetterTta => '𐴄',
HanifiRohingya::LetterJa => '𐴅',
HanifiRohingya::LetterCa => '𐴆',
HanifiRohingya::LetterHa => '𐴇',
HanifiRohingya::LetterKha => '𐴈',
HanifiRohingya::LetterFa => '𐴉',
HanifiRohingya::LetterDa => '𐴊',
HanifiRohingya::LetterDda => '𐴋',
HanifiRohingya::LetterRa => '𐴌',
HanifiRohingya::LetterRra => '𐴍',
HanifiRohingya::LetterZa => '𐴎',
HanifiRohingya::LetterSa => '𐴏',
HanifiRohingya::LetterSha => '𐴐',
HanifiRohingya::LetterKa => '𐴑',
HanifiRohingya::LetterGa => '𐴒',
HanifiRohingya::LetterLa => '𐴓',
HanifiRohingya::LetterMa => '𐴔',
HanifiRohingya::LetterNa => '𐴕',
HanifiRohingya::LetterWa => '𐴖',
HanifiRohingya::LetterKinnaWa => '𐴗',
HanifiRohingya::LetterYa => '𐴘',
HanifiRohingya::LetterKinnaYa => '𐴙',
HanifiRohingya::LetterNga => '𐴚',
HanifiRohingya::LetterNya => '𐴛',
HanifiRohingya::LetterVa => '𐴜',
HanifiRohingya::VowelA => '𐴝',
HanifiRohingya::VowelI => '𐴞',
HanifiRohingya::VowelU => '𐴟',
HanifiRohingya::VowelE => '𐴠',
HanifiRohingya::VowelO => '𐴡',
HanifiRohingya::MarkSakin => '𐴢',
HanifiRohingya::MarkNaKhonna => '𐴣',
HanifiRohingya::SignHarbahay => '𐴤',
HanifiRohingya::SignTahala => '𐴥',
HanifiRohingya::SignTana => '𐴦',
HanifiRohingya::SignTassi => '𐴧',
HanifiRohingya::DigitZero => '𐴰',
HanifiRohingya::DigitOne => '𐴱',
HanifiRohingya::DigitTwo => '𐴲',
HanifiRohingya::DigitThree => '𐴳',
HanifiRohingya::DigitFour => '𐴴',
HanifiRohingya::DigitFive => '𐴵',
HanifiRohingya::DigitSix => '𐴶',
HanifiRohingya::DigitSeven => '𐴷',
HanifiRohingya::DigitEight => '𐴸',
HanifiRohingya::DigitNine => '𐴹',
}
}
}
impl std::convert::TryFrom<char> for HanifiRohingya {
type Error = ();
fn try_from(c: char) -> Result<Self, Self::Error> {
match c {
'𐴀' => Ok(HanifiRohingya::LetterA),
'𐴁' => Ok(HanifiRohingya::LetterBa),
'𐴂' => Ok(HanifiRohingya::LetterPa),
'𐴃' => Ok(HanifiRohingya::LetterTa),
'𐴄' => Ok(HanifiRohingya::LetterTta),
'𐴅' => Ok(HanifiRohingya::LetterJa),
'𐴆' => Ok(HanifiRohingya::LetterCa),
'𐴇' => Ok(HanifiRohingya::LetterHa),
'𐴈' => Ok(HanifiRohingya::LetterKha),
'𐴉' => Ok(HanifiRohingya::LetterFa),
'𐴊' => Ok(HanifiRohingya::LetterDa),
'𐴋' => Ok(HanifiRohingya::LetterDda),
'𐴌' => Ok(HanifiRohingya::LetterRa),
'𐴍' => Ok(HanifiRohingya::LetterRra),
'𐴎' => Ok(HanifiRohingya::LetterZa),
'𐴏' => Ok(HanifiRohingya::LetterSa),
'𐴐' => Ok(HanifiRohingya::LetterSha),
'𐴑' => Ok(HanifiRohingya::LetterKa),
'𐴒' => Ok(HanifiRohingya::LetterGa),
'𐴓' => Ok(HanifiRohingya::LetterLa),
'𐴔' => Ok(HanifiRohingya::LetterMa),
'𐴕' => Ok(HanifiRohingya::LetterNa),
'𐴖' => Ok(HanifiRohingya::LetterWa),
'𐴗' => Ok(HanifiRohingya::LetterKinnaWa),
'𐴘' => Ok(HanifiRohingya::LetterYa),
'𐴙' => Ok(HanifiRohingya::LetterKinnaYa),
'𐴚' => Ok(HanifiRohingya::LetterNga),
'𐴛' => Ok(HanifiRohingya::LetterNya),
'𐴜' => Ok(HanifiRohingya::LetterVa),
'𐴝' => Ok(HanifiRohingya::VowelA),
'𐴞' => Ok(HanifiRohingya::VowelI),
'𐴟' => Ok(HanifiRohingya::VowelU),
'𐴠' => Ok(HanifiRohingya::VowelE),
'𐴡' => Ok(HanifiRohingya::VowelO),
'𐴢' => Ok(HanifiRohingya::MarkSakin),
'𐴣' => Ok(HanifiRohingya::MarkNaKhonna),
'𐴤' => Ok(HanifiRohingya::SignHarbahay),
'𐴥' => Ok(HanifiRohingya::SignTahala),
'𐴦' => Ok(HanifiRohingya::SignTana),
'𐴧' => Ok(HanifiRohingya::SignTassi),
'𐴰' => Ok(HanifiRohingya::DigitZero),
'𐴱' => Ok(HanifiRohingya::DigitOne),
'𐴲' => Ok(HanifiRohingya::DigitTwo),
'𐴳' => Ok(HanifiRohingya::DigitThree),
'𐴴' => Ok(HanifiRohingya::DigitFour),
'𐴵' => Ok(HanifiRohingya::DigitFive),
'𐴶' => Ok(HanifiRohingya::DigitSix),
'𐴷' => Ok(HanifiRohingya::DigitSeven),
'𐴸' => Ok(HanifiRohingya::DigitEight),
'𐴹' => Ok(HanifiRohingya::DigitNine),
_ => Err(()),
}
}
}
impl Into<u32> for HanifiRohingya {
fn into(self) -> u32 {
let c: char = self.into();
let hex = c
.escape_unicode()
.to_string()
.replace("\\u{", "")
.replace("}", "");
u32::from_str_radix(&hex, 16).unwrap()
}
}
impl std::convert::TryFrom<u32> for HanifiRohingya {
type Error = ();
fn try_from(u: u32) -> Result<Self, Self::Error> {
if let Ok(c) = char::try_from(u) {
Self::try_from(c)
} else {
Err(())
}
}
}
impl Iterator for HanifiRohingya {
type Item = Self;
fn next(&mut self) -> Option<Self> {
let index: u32 = (*self).into();
use std::convert::TryFrom;
Self::try_from(index + 1).ok()
}
}
impl HanifiRohingya {
/// The character with the lowest index in this unicode block
pub fn new() -> Self {
HanifiRohingya::LetterA
}
/// The character's name, in sentence case
pub fn name(&self) -> String {
let s = std::format!("HanifiRohingya{:#?}", self);
string_morph::to_sentence_case(&s)
}
}
|
use pyo3::exceptions;
use pyo3::prelude::*;
use pyo3::types::PyDict;
use pyo3::{wrap_pymodule};
mod macros;
pub(crate) use crate::macros::*;
mod edge_file_writer;
mod from_csv;
mod getters;
mod setters;
mod edge_lists;
mod filters;
mod metrics;
mod node_file_writer;
mod preprocessing;
mod remap;
mod trees;
mod connected_components;
mod tarjan;
mod thread_safe;
mod utilities;
pub(crate) use crate::preprocessing::*;
pub(crate) use crate::utilities::*;
mod types;
pub(crate) use crate::types::*;
mod walks;
pub(crate) use crate::types::EnsmallenGraph;
mod modifiers;
mod remove;
mod holdout;
mod operators;
#[pymodule]
fn ensmallen_graph(_py: Python, m: &PyModule) -> PyResult<()> {
m.add_class::<EnsmallenGraph>()?;
m.add_wrapped(wrap_pymodule!(preprocessing))?;
env_logger::init();
Ok(())
}
|
fn decode_boarding_pass(pass: &str) -> (i32, i32) {
// here as a monument to my folly
// let mut row_cur = 0;
// let mut row_gap = 128;
// let mut col_cur = 0;
// let mut col_gap = 8;
// let chars = pass.chars();
// for char in chars {
// match char {
// 'F' => { row_gap = row_gap / 2; }
// 'B' => {
// row_gap = row_gap / 2;
// row_cur += row_gap;
// }
// 'L' => { col_gap = col_gap / 2; }
// 'R' => {
// col_gap = col_gap / 2;
// col_cur += col_gap;
// }
// _ => panic!("Unrecognized character {}", char),
// }
// };
let row_bin = pass.chars().collect::<Vec<char>>()[..7]
.iter().map(|&c| if c == 'F' { '0' } else { '1' }).collect::<String>();
let col_bin = pass.chars().collect::<Vec<char>>()[7..]
.iter().map(|&c| if c == 'L' { '0' } else { '1' }).collect::<String>();
let row = i32::from_str_radix(&row_bin, 2).unwrap();
let col = i32::from_str_radix(&col_bin, 2).unwrap();
return (row, col);
}
pub fn part_one(input: &str) -> String {
input.split_whitespace().map(|pass| {
let (row, col) = decode_boarding_pass(pass);
return row * 8 + col;
}).max().unwrap().to_string()
}
pub fn part_two(input: &str) -> String {
let mut id_list: Vec<i32> = input.split_whitespace().map(|pass| {
let (row, col) = decode_boarding_pass(pass);
return row * 8 + col;
}).collect();
id_list.sort();
for (pos, el) in id_list.iter().enumerate() {
if pos == id_list.len() - 1 {
panic!("no seat found");
}
if id_list[pos + 1] == el + 2 {
return (el + 1).to_string();
}
}
panic!("no seat found");
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn d05_decode_checks() {
assert_eq!(decode_boarding_pass("FBFBBFFRLR"), (44, 5));
assert_eq!(decode_boarding_pass("BFFFBBFRRR"), (70, 7));
assert_eq!(decode_boarding_pass("FFFBBBFRRR"), (14, 7));
assert_eq!(decode_boarding_pass("BBFFBBFRLL"), (102, 4));
}
} |
use std::fs::File;
use std::io::Read;
fn main() {
let mut file = File::open("input").unwrap();
let mut buf = String::new();
file.read_to_string(&mut buf).unwrap();
let initial_chars: Vec<char> = buf.lines().next().unwrap().chars().collect();
let mut min = std::i32::MAX;
for (lower, upper) in ('a' as i32 ..'z' as i32).zip('A' as i32 ..'Z' as i32) {
let mut chars: Vec<char> = initial_chars
.clone()
.into_iter()
.filter(|c| *c as i32 != lower && *c as i32 != upper)
.collect();
let mut new: Vec<char> = Vec::new();
let mut changed = true;
while changed {
let mut iter = chars.into_iter();
new.push(iter.next().unwrap());
changed = false;
while let Some(c) = iter.next() {
if new.len() > 0 {
let last = new.last().unwrap();
if (*last as i32 - c as i32).abs() == 32 {
new.pop();
changed = true;
} else {
new.push(c);
}
} else {
new.push(c);
}
}
chars = new;
new = Vec::new();
}
min = i32::min(chars.len() as i32, min);
}
println!("{}", min);
}
|
use rodio::Source;
use serde::{Deserialize, Serialize};
use std::{
cmp::Ordering,
fs::File,
io::{BufReader, BufWriter, Read, Write},
path::Path,
time::Duration,
};
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("io error: {0}")]
IO(#[from] std::io::Error),
#[error("json error: {0}")]
Json(#[from] serde_json::Error),
#[cfg(feature = "mp3")]
#[error("mp3 error: {0}")]
Mp3(#[from] minimp3::Error),
#[cfg(feature = "mp3")]
#[error("id3 error: {0}")]
Id3(#[from] id3::Error),
#[cfg(feature = "flac")]
#[error("flac error: {0}")]
Flac(#[from] claxon::Error),
#[cfg(feature = "ogg")]
#[error("ogg error: {0}")]
Ogg(#[from] lewton::VorbisError),
#[cfg(feature = "wav")]
#[error("wav error: {0}")]
Wav(#[from] hound::Error),
}
#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Lilac {
pub title: Option<String>,
pub artist: Option<String>,
pub year: Option<i32>,
pub album: Option<String>,
pub track: Option<u32>,
pub channels: u16,
pub sample_rate: u32,
pub bit_depth: u32,
samples: Vec<i32>,
}
impl Lilac {
pub fn read<R: Read>(reader: R) -> Result<Self, Error> {
serde_json::from_reader(reader).map_err(Into::into)
}
pub fn read_file<P: AsRef<Path>>(path: P) -> Result<Self, Error> {
Self::read(BufReader::new(File::open(path)?))
}
pub fn write<W: Write>(&self, writer: W) -> Result<(), Error> {
serde_json::to_writer_pretty(writer, self).map_err(Into::into)
}
pub fn write_file<P: AsRef<Path>>(&self, path: P) -> Result<(), Error> {
self.write(BufWriter::new(File::create(path)?))
}
pub fn title(&self) -> &str {
self.title.as_ref().map(AsRef::as_ref).unwrap_or("Unknown")
}
pub fn artist(&self) -> &str {
self.artist.as_ref().map(AsRef::as_ref).unwrap_or("Unknown")
}
pub fn album(&self) -> &str {
self.album.as_ref().map(AsRef::as_ref).unwrap_or("Unknown")
}
pub fn source(self) -> impl Source<Item = f32> {
let min = (2u32.pow(self.bit_depth - 1)) as f32;
let max = (2u32.pow(self.bit_depth - 1) - 1) as f32;
let samples_len = self.samples.len();
LilacSource {
channels: self.channels,
sample_rate: self.sample_rate,
samples: self.samples.into_iter().map(move |s| match s.cmp(&0) {
Ordering::Less => (s as f32 / min),
Ordering::Equal => 0.0,
Ordering::Greater => (s as f32 / max),
}),
duration: Duration::from_millis(
samples_len as u64 / self.channels as u64 / (self.sample_rate / 1000) as u64,
),
}
}
}
struct LilacSource<T: Iterator<Item = f32>> {
channels: u16,
sample_rate: u32,
samples: T,
duration: Duration,
}
impl<T: Iterator<Item = f32>> Iterator for LilacSource<T> {
type Item = f32;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
self.samples.next()
}
}
impl<T: Iterator<Item = f32>> Source for LilacSource<T> {
#[inline]
fn current_frame_len(&self) -> Option<usize> {
None
}
#[inline]
fn channels(&self) -> u16 {
self.channels
}
#[inline]
fn sample_rate(&self) -> u32 {
self.sample_rate
}
#[inline]
fn total_duration(&self) -> Option<Duration> {
Some(self.duration)
}
}
#[cfg(feature = "mp3")]
mod mp3 {
use crate::{Error, Lilac};
use id3::{ErrorKind, Tag};
use minimp3::Decoder;
use std::{
fs::File,
io::{BufReader, Read, Seek, SeekFrom},
path::Path,
};
impl Lilac {
pub fn from_mp3<R: Read + Seek>(mut reader: R) -> Result<Self, Error> {
let (title, artist, year, album, track) = match Tag::read_from(&mut reader) {
Ok(tag) => {
let title = tag.title().map(ToOwned::to_owned);
let artist = tag.artist().map(ToOwned::to_owned);
let year = tag.year();
let album = tag.album().map(ToOwned::to_owned);
let track = tag.track();
(title, artist, year, album, track)
}
Err(e) => match e.kind {
ErrorKind::NoTag => (None, None, None, None, None),
_ => return Err(e.into()),
},
};
reader.seek(SeekFrom::Start(0))?;
let mut reader = Decoder::new(reader);
let mut samples = Vec::new();
let first_frame = reader.next_frame()?;
let channels = first_frame.channels as u16;
let sample_rate = first_frame.sample_rate as u32;
samples.extend(first_frame.data.into_iter().map(|s| s as i32));
loop {
match reader.next_frame() {
Ok(f) => samples.extend(f.data.into_iter().map(|s| s as i32)),
Err(e) => match e {
minimp3::Error::Eof => break,
_ => return Err(e.into()),
},
}
}
Ok(Lilac {
title,
artist,
year,
album,
track,
channels,
sample_rate,
bit_depth: 16,
samples,
})
}
pub fn from_mp3_file<P: AsRef<Path>>(path: P) -> Result<Self, Error> {
Self::from_mp3(BufReader::new(File::open(path)?))
}
}
}
#[cfg(feature = "flac")]
mod flac {
use crate::{Error, Lilac};
use claxon::FlacReader;
use std::{
fs::File,
io::{BufReader, Read},
path::Path,
};
impl Lilac {
pub fn from_flac<R: Read>(reader: R) -> Result<Self, Error> {
let mut reader = FlacReader::new(reader)?;
let info = reader.streaminfo();
let title = reader.get_tag("TITLE").next().map(ToOwned::to_owned);
let artist = {
let artists: Vec<&str> = reader.get_tag("ARTIST").collect();
if !artists.is_empty() {
Some(artists.join(", "))
} else {
None
}
};
let album = reader.get_tag("ALBUM").next().map(ToOwned::to_owned);
let track = match reader.get_tag("TRACKNUMBER").next() {
Some(tn) => match tn.parse() {
Ok(tn) => Some(tn),
Err(_) => None,
},
None => None,
};
Ok(Lilac {
title,
artist,
year: None,
album,
track,
channels: info.channels as u16,
sample_rate: info.sample_rate,
bit_depth: info.bits_per_sample,
samples: reader.samples().collect::<Result<_, _>>()?,
})
}
pub fn from_flac_file<P: AsRef<Path>>(path: P) -> Result<Self, Error> {
Self::from_flac(BufReader::new(File::open(path)?))
}
}
}
#[cfg(feature = "ogg")]
mod ogg {
use crate::{Error, Lilac};
use lewton::inside_ogg::OggStreamReader;
use std::{
fs::File,
io::{BufReader, Read, Seek},
path::Path,
};
impl Lilac {
pub fn from_ogg<R: Read + Seek>(reader: R) -> Result<Self, Error> {
let mut reader = OggStreamReader::new(reader)?;
let mut title = None;
let mut artists = Vec::new();
let mut album = None;
let mut track = None;
for (k, v) in &reader.comment_hdr.comment_list {
let uk = k.to_ascii_uppercase();
if uk == "TITLE" && title.is_none() {
title = Some(v.clone());
} else if uk == "ARTIST" {
artists.push(v.as_ref());
} else if uk == "ALBUM" && album.is_none() {
album = Some(v.clone());
} else if uk == "TRACKNUMBER" && track.is_none() {
if let Ok(tn) = v.parse() {
track = Some(tn);
}
}
}
let artist = if !artists.is_empty() {
Some(artists.join(", "))
} else {
None
};
let mut samples = Vec::new();
while let Some(packet) = reader.read_dec_packet_itl()? {
samples.extend(packet.into_iter().map(|s| s as i32));
}
Ok(Lilac {
title,
artist,
year: None,
album,
track,
channels: reader.ident_hdr.audio_channels as u16,
sample_rate: reader.ident_hdr.audio_sample_rate,
bit_depth: 16,
samples,
})
}
pub fn from_ogg_file<P: AsRef<Path>>(path: P) -> Result<Self, Error> {
Self::from_ogg(BufReader::new(File::open(path)?))
}
}
}
#[cfg(feature = "wav")]
mod wav {
use crate::{Error, Lilac};
use hound::{SampleFormat, WavReader, WavSpec, WavWriter};
use std::{
fs::File,
io::{BufReader, BufWriter, Read, Seek, Write},
path::Path,
};
impl Lilac {
pub fn from_wav<R: Read>(reader: R) -> Result<Self, Error> {
let mut reader = WavReader::new(reader)?;
let spec = reader.spec();
let samples = reader.samples().collect::<Result<_, _>>()?;
Ok(Lilac {
title: None,
artist: None,
year: None,
album: None,
track: None,
channels: spec.channels,
sample_rate: spec.sample_rate,
bit_depth: spec.bits_per_sample as u32,
samples,
})
}
pub fn from_wav_file<P: AsRef<Path>>(path: P) -> Result<Self, Error> {
Self::from_wav(BufReader::new(File::open(path)?))
}
pub fn to_wav<W: Write + Seek>(&self, writer: W) -> Result<(), Error> {
let spec = WavSpec {
channels: self.channels,
sample_rate: self.sample_rate,
bits_per_sample: self.bit_depth as u16,
sample_format: SampleFormat::Int,
};
let mut writer = WavWriter::new(writer, spec)?;
for sample in self.samples.iter().copied() {
writer.write_sample(sample)?;
}
writer.finalize().map_err(Into::into)
}
pub fn to_wav_file<P: AsRef<Path>>(&self, path: P) -> Result<(), Error> {
self.to_wav(BufWriter::new(File::create(path)?))
}
}
}
|
use crate::Error;
use common::rsip::{self};
use models::transport::TransportMsg;
//transport processor
#[derive(Debug, Default)]
pub struct Processor;
impl Processor {
pub async fn process_incoming_message(&self, msg: TransportMsg) -> Result<TransportMsg, Error> {
use super::{uac, uas};
let TransportMsg {
sip_message,
peer,
transport,
} = msg;
let sip_message = match sip_message {
rsip::SipMessage::Request(request) => {
uas::apply_request_defaults(request, peer, transport)?
}
rsip::SipMessage::Response(response) => {
uac::apply_response_defaults(response, peer, transport)?
}
};
Ok(TransportMsg {
sip_message,
peer,
transport,
})
}
pub fn process_outgoing_message(&self, msg: TransportMsg) -> Result<TransportMsg, Error> {
use super::{uac, uas};
let TransportMsg {
sip_message,
peer,
transport,
} = msg;
let sip_message = match sip_message {
rsip::SipMessage::Request(request) => {
uac::apply_request_defaults(request, peer, transport)?
}
rsip::SipMessage::Response(response) => {
uas::apply_response_defaults(response, peer, transport)
}
};
Ok(TransportMsg {
sip_message,
peer,
transport,
})
}
}
|
#[macro_export]
macro_rules! uint_from_bytes {
(u32 => $i:expr, $block:expr, $bytes:expr, $from_bytes:ident) => {
$block[$i] = u32::$from_bytes([
$bytes[$i * 4],
$bytes[$i * 4 + 1],
$bytes[$i * 4 + 2],
$bytes[$i * 4 + 3],
]);
};
(u64 => $i:expr, $block:expr, $bytes:expr, $from_bytes:ident) => {
$block[$i] = u64::$from_bytes([
$bytes[$i * 8],
$bytes[$i * 8 + 1],
$bytes[$i * 8 + 2],
$bytes[$i * 8 + 3],
$bytes[$i * 8 + 4],
$bytes[$i * 8 + 5],
$bytes[$i * 8 + 6],
$bytes[$i * 8 + 7],
]);
};
}
// main flow for MD4, MD5, RIPEMD-{128, 160, 256, 320}, SHA-0, SHA-1 and SHA-2
#[macro_export]
macro_rules! impl_md_flow {
// $self: T, $message: input bytes
// $from_bytes
//// from_be_bytes: SHA-{0, 1, 2}
//// from_le_bytes: Others
// $to_bytes
//// to_be_bytes: SHA-{0, 1, 2}
//// to_le_bytes: Others
// u32
// 64 - 1(0x80) - 8(l) = 55
// u64
// 128 - 1(0x80) - 16(l) = 111
(u32 => $self:expr, $message:ident, $from_bytes:ident, $to_bytes:ident) => {
use util::uint_from_bytes;
let l = $message.len();
let mut block = [0u32; 16];
if l >= 64 {
$message.chunks_exact(64).for_each(|bytes| {
uint_from_bytes!(u32 => 0, block, bytes, $from_bytes);
uint_from_bytes!(u32 => 1, block, bytes, $from_bytes);
uint_from_bytes!(u32 => 2, block, bytes, $from_bytes);
uint_from_bytes!(u32 => 3, block, bytes, $from_bytes);
uint_from_bytes!(u32 => 4, block, bytes, $from_bytes);
uint_from_bytes!(u32 => 5, block, bytes, $from_bytes);
uint_from_bytes!(u32 => 6, block, bytes, $from_bytes);
uint_from_bytes!(u32 => 7, block, bytes, $from_bytes);
uint_from_bytes!(u32 => 8, block, bytes, $from_bytes);
uint_from_bytes!(u32 => 9, block, bytes, $from_bytes);
uint_from_bytes!(u32 => 10, block, bytes, $from_bytes);
uint_from_bytes!(u32 => 11, block, bytes, $from_bytes);
uint_from_bytes!(u32 => 12, block, bytes, $from_bytes);
uint_from_bytes!(u32 => 13, block, bytes, $from_bytes);
uint_from_bytes!(u32 => 14, block, bytes, $from_bytes);
uint_from_bytes!(u32 => 15, block, bytes, $from_bytes);
$self.compress(&block);
});
} else if l == 0 {
$self.compress(&[
u32::$from_bytes([0x80, 0, 0, 0]),
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
])
}
if l != 0 {
let offset = (l / 64) * 64;
let remainder = l % 64;
match (l % 64).cmp(&55) {
Ordering::Greater => {
// two blocks
let mut byte_block = [0u8; 128];
byte_block[..remainder].copy_from_slice(&$message[offset..]);
byte_block[remainder] = 0x80;
byte_block[120..].copy_from_slice(&(8 * l as u64).$to_bytes());
byte_block.chunks_exact(64).for_each(|bytes| {
uint_from_bytes!(u32 => 0, block, bytes, $from_bytes);
uint_from_bytes!(u32 => 1, block, bytes, $from_bytes);
uint_from_bytes!(u32 => 2, block, bytes, $from_bytes);
uint_from_bytes!(u32 => 3, block, bytes, $from_bytes);
uint_from_bytes!(u32 => 4, block, bytes, $from_bytes);
uint_from_bytes!(u32 => 5, block, bytes, $from_bytes);
uint_from_bytes!(u32 => 6, block, bytes, $from_bytes);
uint_from_bytes!(u32 => 7, block, bytes, $from_bytes);
uint_from_bytes!(u32 => 8, block, bytes, $from_bytes);
uint_from_bytes!(u32 => 9, block, bytes, $from_bytes);
uint_from_bytes!(u32 => 10, block, bytes, $from_bytes);
uint_from_bytes!(u32 => 11, block, bytes, $from_bytes);
uint_from_bytes!(u32 => 12, block, bytes, $from_bytes);
uint_from_bytes!(u32 => 13, block, bytes, $from_bytes);
uint_from_bytes!(u32 => 14, block, bytes, $from_bytes);
uint_from_bytes!(u32 => 15, block, bytes, $from_bytes);
$self.compress(&block);
});
}
Ordering::Less | Ordering::Equal => {
// one block
let mut byte_block = [0u8; 64];
byte_block[..remainder].copy_from_slice(&$message[offset..]);
byte_block[remainder] = 0x80;
byte_block[56..].copy_from_slice(&(8 * l as u64).$to_bytes());
uint_from_bytes!(u32 => 0, block, byte_block, $from_bytes);
uint_from_bytes!(u32 => 1, block, byte_block, $from_bytes);
uint_from_bytes!(u32 => 2, block, byte_block, $from_bytes);
uint_from_bytes!(u32 => 3, block, byte_block, $from_bytes);
uint_from_bytes!(u32 => 4, block, byte_block, $from_bytes);
uint_from_bytes!(u32 => 5, block, byte_block, $from_bytes);
uint_from_bytes!(u32 => 6, block, byte_block, $from_bytes);
uint_from_bytes!(u32 => 7, block, byte_block, $from_bytes);
uint_from_bytes!(u32 => 8, block, byte_block, $from_bytes);
uint_from_bytes!(u32 => 9, block, byte_block, $from_bytes);
uint_from_bytes!(u32 => 10, block, byte_block, $from_bytes);
uint_from_bytes!(u32 => 11, block, byte_block, $from_bytes);
uint_from_bytes!(u32 => 12, block, byte_block, $from_bytes);
uint_from_bytes!(u32 => 13, block, byte_block, $from_bytes);
uint_from_bytes!(u32 => 14, block, byte_block, $from_bytes);
uint_from_bytes!(u32 => 15, block, byte_block, $from_bytes);
$self.compress(&block);
}
}
}
};
(u64 => $self:expr, $message:ident, $from_bytes:ident, $to_bytes:ident) => {
use util::uint_from_bytes;
let l = $message.len();
let mut block = [0u64; 16];
if l >= 128 {
$message.chunks_exact(128).for_each(|bytes| {
uint_from_bytes!(u64 => 0, block, bytes, $from_bytes);
uint_from_bytes!(u64 => 1, block, bytes, $from_bytes);
uint_from_bytes!(u64 => 2, block, bytes, $from_bytes);
uint_from_bytes!(u64 => 3, block, bytes, $from_bytes);
uint_from_bytes!(u64 => 4, block, bytes, $from_bytes);
uint_from_bytes!(u64 => 5, block, bytes, $from_bytes);
uint_from_bytes!(u64 => 6, block, bytes, $from_bytes);
uint_from_bytes!(u64 => 7, block, bytes, $from_bytes);
uint_from_bytes!(u64 => 8, block, bytes, $from_bytes);
uint_from_bytes!(u64 => 9, block, bytes, $from_bytes);
uint_from_bytes!(u64 => 10, block, bytes, $from_bytes);
uint_from_bytes!(u64 => 11, block, bytes, $from_bytes);
uint_from_bytes!(u64 => 12, block, bytes, $from_bytes);
uint_from_bytes!(u64 => 13, block, bytes, $from_bytes);
uint_from_bytes!(u64 => 14, block, bytes, $from_bytes);
uint_from_bytes!(u64 => 15, block, bytes, $from_bytes);
$self.compress(&block);
});
} else if l == 0 {
$self.compress(&[
u64::$from_bytes([0x80, 0, 0, 0, 0, 0, 0, 0]),
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
])
}
if l != 0 {
let offset = (l / 128) * 128;
let remainder = l % 128;
match (l % 128).cmp(&111) {
Ordering::Greater => {
// two blocks
let mut byte_block = [0u8; 256];
byte_block[..remainder].copy_from_slice(&$message[offset..]);
byte_block[remainder] = 0x80;
byte_block[240..].copy_from_slice(&(8 * l as u128).$to_bytes());
byte_block.chunks_exact(128).for_each(|bytes| {
uint_from_bytes!(u64 => 0, block, bytes, $from_bytes);
uint_from_bytes!(u64 => 1, block, bytes, $from_bytes);
uint_from_bytes!(u64 => 2, block, bytes, $from_bytes);
uint_from_bytes!(u64 => 3, block, bytes, $from_bytes);
uint_from_bytes!(u64 => 4, block, bytes, $from_bytes);
uint_from_bytes!(u64 => 5, block, bytes, $from_bytes);
uint_from_bytes!(u64 => 6, block, bytes, $from_bytes);
uint_from_bytes!(u64 => 7, block, bytes, $from_bytes);
uint_from_bytes!(u64 => 8, block, bytes, $from_bytes);
uint_from_bytes!(u64 => 9, block, bytes, $from_bytes);
uint_from_bytes!(u64 => 10, block, bytes, $from_bytes);
uint_from_bytes!(u64 => 11, block, bytes, $from_bytes);
uint_from_bytes!(u64 => 12, block, bytes, $from_bytes);
uint_from_bytes!(u64 => 13, block, bytes, $from_bytes);
uint_from_bytes!(u64 => 14, block, bytes, $from_bytes);
uint_from_bytes!(u64 => 15, block, bytes, $from_bytes);
$self.compress(&block);
});
}
Ordering::Less | Ordering::Equal => {
// one block
let mut byte_block = [0u8; 128];
byte_block[..remainder].copy_from_slice(&$message[offset..]);
byte_block[remainder] = 0x80;
byte_block[112..].copy_from_slice(&(8 * l as u128).$to_bytes());
uint_from_bytes!(u64 => 0, block, byte_block, $from_bytes);
uint_from_bytes!(u64 => 1, block, byte_block, $from_bytes);
uint_from_bytes!(u64 => 2, block, byte_block, $from_bytes);
uint_from_bytes!(u64 => 3, block, byte_block, $from_bytes);
uint_from_bytes!(u64 => 4, block, byte_block, $from_bytes);
uint_from_bytes!(u64 => 5, block, byte_block, $from_bytes);
uint_from_bytes!(u64 => 6, block, byte_block, $from_bytes);
uint_from_bytes!(u64 => 7, block, byte_block, $from_bytes);
uint_from_bytes!(u64 => 8, block, byte_block, $from_bytes);
uint_from_bytes!(u64 => 9, block, byte_block, $from_bytes);
uint_from_bytes!(u64 => 10, block, byte_block, $from_bytes);
uint_from_bytes!(u64 => 11, block, byte_block, $from_bytes);
uint_from_bytes!(u64 => 12, block, byte_block, $from_bytes);
uint_from_bytes!(u64 => 13, block, byte_block, $from_bytes);
uint_from_bytes!(u64 => 14, block, byte_block, $from_bytes);
uint_from_bytes!(u64 => 15, block, byte_block, $from_bytes);
$self.compress(&block);
}
}
}
};
}
// minimal version of impl_md_flow
#[macro_export]
macro_rules! impl_md_flow_minimal {
(u32 => $self:expr, $message:ident, $from_bytes:ident, $to_bytes:ident) => {
let l = $message.len();
let mut block = [0u32; 16];
if l >= 64 {
$message.chunks_exact(64).for_each(|bytes| {
(0..16).for_each(|i| {
block[i] = u32::$from_bytes([
bytes[i * 4],
bytes[i * 4 + 1],
bytes[i * 4 + 2],
bytes[i * 4 + 3],
]);
});
$self.compress(&block);
});
} else if l == 0 {
$self.compress(&[
u32::$from_bytes([0x80, 0, 0, 0]),
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
])
}
if l != 0 {
let offset = (l / 64) * 64;
let remainder = l % 64;
match (l % 64).cmp(&55) {
Ordering::Greater => {
// two blocks
let mut byte_block = [0u8; 128];
byte_block[..remainder].copy_from_slice(&$message[offset..]);
byte_block[remainder] = 0x80;
byte_block[120..].copy_from_slice(&(8 * l as u64).$to_bytes());
byte_block.chunks_exact(64).for_each(|bytes| {
(0..16).for_each(|i| {
block[i] = u32::$from_bytes([
bytes[i * 4],
bytes[i * 4 + 1],
bytes[i * 4 + 2],
bytes[i * 4 + 3],
]);
});
$self.compress(&block);
});
}
Ordering::Less | Ordering::Equal => {
// one block
let mut byte_block = [0u8; 64];
byte_block[..remainder].copy_from_slice(&$message[offset..]);
byte_block[remainder] = 0x80;
byte_block[56..].copy_from_slice(&(8 * l as u64).$to_bytes());
(0..16).for_each(|i| {
block[i] = u32::$from_bytes([
byte_block[i * 4],
byte_block[i * 4 + 1],
byte_block[i * 4 + 2],
byte_block[i * 4 + 3],
]);
});
$self.compress(&block);
}
}
}
};
(u64 => $self:expr, $message:ident, $from_bytes:ident, $to_bytes:ident) => {
let l = $message.len();
let mut block = [0u64; 16];
if l >= 128 {
$message.chunks_exact(128).for_each(|bytes| {
(0..16).for_each(|i| {
block[i] = u64::$from_bytes([
bytes[i * 8],
bytes[i * 8 + 1],
bytes[i * 8 + 2],
bytes[i * 8 + 3],
bytes[i * 8 + 4],
bytes[i * 8 + 5],
bytes[i * 8 + 6],
bytes[i * 8 + 7],
]);
});
$self.compress(&block);
});
} else if l == 0 {
$self.compress(&[
u64::$from_bytes([0x80, 0, 0, 0, 0, 0, 0, 0]),
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
])
}
if l != 0 {
let offset = (l / 128) * 128;
let remainder = l % 128;
match (l % 128).cmp(&111) {
Ordering::Greater => {
// two blocks
let mut byte_block = [0u8; 256];
byte_block[..remainder].copy_from_slice(&$message[offset..]);
byte_block[remainder] = 0x80;
byte_block[240..].copy_from_slice(&(8 * l as u128).$to_bytes());
byte_block.chunks_exact(128).for_each(|bytes| {
(0..16).for_each(|i| {
block[i] = u64::$from_bytes([
bytes[i * 8],
bytes[i * 8 + 1],
bytes[i * 8 + 2],
bytes[i * 8 + 3],
bytes[i * 8 + 4],
bytes[i * 8 + 5],
bytes[i * 8 + 6],
bytes[i * 8 + 7],
]);
});
$self.compress(&block);
});
}
Ordering::Less | Ordering::Equal => {
// one block
let mut byte_block = [0u8; 128];
byte_block[..remainder].copy_from_slice(&$message[offset..]);
byte_block[remainder] = 0x80;
byte_block[112..].copy_from_slice(&(8 * l as u128).$to_bytes());
(0..16).for_each(|i| {
block[i] = u64::$from_bytes([
byte_block[i * 8],
byte_block[i * 8 + 1],
byte_block[i * 8 + 2],
byte_block[i * 8 + 3],
byte_block[i * 8 + 4],
byte_block[i * 8 + 5],
byte_block[i * 8 + 6],
byte_block[i * 8 + 7],
]);
});
$self.compress(&block);
}
}
}
};
}
|
mod front_of_house;
mod front_of_house2;
pub use crate::front_of_house::hosting;
pub use crate::front_of_house2::hosting2;
pub fn eat_at_restaurant() {
hosting::add_to_waitlist();
hosting::add_to_waitlist();
hosting::add_to_waitlist();
hosting2::add_to_waitlist();
hosting2::add_to_waitlist();
hosting2::add_to_waitlist();
hosting2::add_to_waitlist();
}
|
use super::File;
use crate::command::Command;
use crate::date::Date;
use crate::error::*;
use crate::field::*;
use crate::filter::Filter;
use crate::modification::Modification;
#[derive(Debug, PartialEq)]
enum ArgStage {
Filter,
Command,
Modification,
}
pub enum ArgNext<'a> {
Filter(Filter<'a>),
Command(Command),
Modification(Modification<'a>),
}
pub struct ArgIter<'a> {
stage: ArgStage,
stack: Vec<&'a str>,
force_append: bool,
now: &'a Date,
date_keys: &'a [Key<'a>],
filter_aliases: &'a [File],
command_aliases: &'a [File],
modification_aliases: &'a [File],
}
impl<'a> ArgIter<'a> {
pub fn new(
args: &'a [String],
now: &'a Date,
date_keys: &'a [Key<'a>],
filter_aliases: &'a [File],
command_aliases: &'a [File],
modification_aliases: &'a [File],
) -> Self {
let mut stack = Vec::new();
for arg in args {
stack.insert(0, arg.as_ref());
}
ArgIter {
stage: ArgStage::Filter,
stack,
force_append: false,
now,
date_keys,
filter_aliases,
command_aliases,
modification_aliases,
}
}
}
impl<'a> Iterator for ArgIter<'a> {
type Item = Result<ArgNext<'a>>;
fn next(&mut self) -> Option<Self::Item> {
let mut arg = self.stack.pop()?;
if self.stage == ArgStage::Filter {
if let Some(File { content, .. }) = find_name(arg, self.filter_aliases) {
let mut aliases = content.as_ref();
let i = self.stack.len();
while let Some((head, tail)) = split_token(aliases) {
self.stack.insert(i, head);
aliases = tail;
}
arg = self.stack.pop()?;
}
}
while self.stage == ArgStage::Filter && is_all_whitespace(arg) {
arg = self.stack.pop()?;
}
if self.stage == ArgStage::Filter {
match Filter::new(arg, &self.now, &self.date_keys) {
Err(err) => return Some(Err(err)),
Ok(Some(filter)) => return Some(Ok(ArgNext::Filter(filter))),
Ok(None) => self.stage = ArgStage::Command,
}
}
if self.stage == ArgStage::Command {
if let Some(File { content, .. }) = find_name(arg, self.command_aliases) {
let mut aliases = content.as_ref();
let i = self.stack.len();
while let Some((head, tail)) = split_token(aliases) {
self.stack.insert(i, head);
aliases = tail;
}
arg = self.stack.pop()?;
}
}
if self.stage == ArgStage::Command {
self.stage = ArgStage::Modification;
return match Command::new(arg) {
Some(command) => Some(Ok(ArgNext::Command(command))),
None => Some(Err(NotAFilterOrCommand(arg.to_owned()))),
};
}
if let Some(File { content, .. }) = find_name(arg, self.modification_aliases) {
let mut aliases = content.as_ref();
let i = self.stack.len();
while let Some((head, tail)) = split_token(aliases) {
self.stack.insert(i, head);
aliases = tail;
}
arg = self.stack.pop()?;
}
while !self.force_append && is_all_whitespace(arg) {
arg = self.stack.pop()?;
}
if arg.contains(|c: char| c.is_ascii_whitespace())
&& arg.contains(|c: char| !c.is_ascii_whitespace())
{
let mut content = arg;
let i = self.stack.len();
while let Some((head, tail)) = split_token(content) {
self.stack.insert(i, head);
content = tail;
}
arg = self.stack.pop()?;
}
Some(match Modification::new(arg, &self.now, &self.date_keys) {
Ok(Modification::Append(str)) => {
self.force_append = true;
Ok(ArgNext::Modification(Modification::Append(str)))
}
Ok(Modification::SetBody(str)) if !self.force_append => {
self.force_append = true;
Ok(ArgNext::Modification(Modification::SetBody(str)))
}
Ok(Modification::SetBody(str)) if self.force_append => {
Ok(ArgNext::Modification(Modification::Append(str)))
}
Ok(modification) => {
Ok(ArgNext::Modification(modification))
}
Err(err) => Err(err)
})
}
}
fn find_name<'a>(n: &str, fs: &'a [File]) -> Option<&'a File> {
fs.iter().find(|File { name, .. }| name == n)
}
fn is_all_whitespace(str: &str) -> bool {
str.chars().all(|c: char| c.is_ascii_whitespace())
}
fn split_token(str: &str) -> Option<(&str, &str)> {
let str = str.trim_end();
let head = match str.starts_with(|c: char| c.is_ascii_whitespace()) {
true => str.split(|c: char| !c.is_ascii_whitespace()).next()?,
false => str.split_ascii_whitespace().next()?,
};
let tail = str.get(head.len()..)?;
Some((head, tail))
}
|
extern crate chrono;
extern crate clap;
extern crate rusqlite;
#[macro_use]
extern crate serde_derive;
extern crate serde_rusqlite;
extern crate strum;
#[macro_use]
extern crate strum_macros;
#[macro_use]
extern crate log;
extern crate simplelog;
mod logging;
#[allow(dead_code)]
mod db;
use clap::App;
use db::DataMgr;
use logging::logging_init;
fn main() {
logging_init();
let _matches = App::new("Garden Master")
.version("0.1.0")
.author("Lucas Brendel")
.about("Help keep track of all the things that need to happen in a garden or orchard")
.get_matches();
let _mgr = DataMgr::new(String::from("./data/green-thumb.db"));
}
|
use std::io::Read;
fn main() -> Result<(), Box<dyn std::error::Error>> {
if std::env::args().count() != 1 {
println!("compute_class_hash -- reads from stdin, outputs a class hash");
println!(
"the input read from stdin is expected to be a class definition, which is a json blob."
);
std::process::exit(1);
}
let mut s = Vec::new();
std::io::stdin().read_to_end(&mut s).unwrap();
let s = s;
println!("{:x}", pathfinder_lib::state::compute_class_hash(&s)?.0);
Ok(())
}
|
use crate::utils::asserts::meta::assert_meta;
use crate::utils::asserts::transaction::{assert_vote_data, test_vote_array};
use crate::utils::mockito_helpers::{mock_client, mock_http_request};
use serde_json::from_str;
use serde_json::Value;
use std::borrow::Borrow;
#[tokio::test]
async fn test_all() {
let (_mock, body) = mock_http_request("votes");
{
let mut client = mock_client();
let actual = client.votes.all().await.unwrap();
let expected: Value = from_str(&body).unwrap();
assert_meta(actual.meta.unwrap(), expected["meta"].borrow());
test_vote_array(actual.data, expected);
}
}
#[tokio::test]
async fn test_all_params() {
let (_mock, body) = mock_http_request("votes");
{
let mut client = mock_client();
let params = [("limit", "20")].iter();
let actual = client.votes.all_params(params).await.unwrap();
let expected: Value = from_str(&body).unwrap();
assert_meta(actual.meta.unwrap(), expected["meta"].borrow());
test_vote_array(actual.data, expected);
}
}
#[tokio::test]
async fn test_show() {
let (_mock, body) = mock_http_request("votes/dummy");
{
let mut client = mock_client();
let actual = client.votes.show("dummy").await.unwrap();
let expected: Value = from_str(&body).unwrap();
assert_vote_data(actual.data, &expected["data"]);
}
}
|
// rust-lang/rust#101913: when you run your program explicitly via `ld.so`,
// `std::env::current_exe` will return the path of *that* program, and not
// the Rust program itself.
use std::io::{BufRead, BufReader};
use std::path::{Path, PathBuf};
use std::process::Command;
mod common;
fn main() {
if std::env::var(VAR).is_err() {
// the parent waits for the child; then we then handle either printing
// "test result: ok", "test result: ignored", or panicking.
match parent() {
Ok(()) => {
println!("test result: ok");
}
Err(EarlyExit::IgnoreTest(_)) => {
println!("test result: ignored");
}
Err(EarlyExit::IoError(e)) => {
println!("{} parent encoutered IoError: {:?}", file!(), e);
panic!();
}
}
} else {
// println!("{} running child", file!());
child().unwrap();
}
}
const VAR: &str = "__THE_TEST_YOU_ARE_LUKE";
#[derive(Debug)]
enum EarlyExit {
IgnoreTest(String),
IoError(std::io::Error),
}
impl From<std::io::Error> for EarlyExit {
fn from(e: std::io::Error) -> Self {
EarlyExit::IoError(e)
}
}
fn parent() -> Result<(), EarlyExit> {
// If we cannot re-exec this test, there's no point in trying to do it.
if common::cannot_reexec_the_test() {
return Err(EarlyExit::IgnoreTest("(cannot reexec)".into()));
}
let me = std::env::current_exe().unwrap();
let ld_so = find_interpreter(&me)?;
// use interp to invoke current exe, yielding child test.
//
// (if you're curious what you might compare this against, you can try
// swapping in the below definition for `result`, which is the easy case of
// not using the ld.so interpreter directly that Rust handled fine even
// prior to resolution of rust-lang/rust#101913.)
//
// let result = Command::new(me).env(VAR, "1").output()?;
let result = Command::new(ld_so).env(VAR, "1").arg(&me).output().unwrap();
if result.status.success() {
return Ok(());
}
println!("stdout:\n{}", String::from_utf8_lossy(&result.stdout));
println!("stderr:\n{}", String::from_utf8_lossy(&result.stderr));
println!("code: {}", result.status);
panic!();
}
fn child() -> Result<(), EarlyExit> {
let bt = backtrace::Backtrace::new();
println!("{:?}", bt);
let mut found_my_name = false;
let my_filename = file!();
'frames: for frame in bt.frames() {
let symbols = frame.symbols();
if symbols.is_empty() {
continue;
}
for sym in symbols {
if let Some(filename) = sym.filename() {
if filename.ends_with(my_filename) {
// huzzah!
found_my_name = true;
break 'frames;
}
}
}
}
assert!(found_my_name);
Ok(())
}
// we use the `readelf` command to extract the path to the interpreter requested
// by our binary.
//
// if we cannot `readelf` for some reason, or if we fail to parse its output,
// then we will just give up on this test (and not treat it as a test failure).
fn find_interpreter(me: &Path) -> Result<PathBuf, EarlyExit> {
let result = Command::new("readelf")
.arg("-l")
.arg(me)
.output()
.map_err(|_err| EarlyExit::IgnoreTest("readelf invocation failed".into()))?;
if result.status.success() {
let r = BufReader::new(&result.stdout[..]);
for line in r.lines() {
let line = line?;
let line = line.trim();
let prefix = "[Requesting program interpreter: ";
if let Some((_, suffix)) = line.split_once(prefix) {
if let Some((found_path, _)) = suffix.rsplit_once("]") {
return Ok(found_path.into());
}
}
}
Err(EarlyExit::IgnoreTest(
"could not find interpreter from readelf output".into(),
))
} else {
Err(EarlyExit::IgnoreTest("readelf returned non-success".into()))
}
}
|
use crate::headers::{HEADER_DATE, HEADER_VERSION};
use crate::resources::permission::AuthorizationToken;
use crate::resources::ResourceType;
use crate::TimeNonce;
use azure_core::{Context, Policy, PolicyResult, Request, Response};
use http::header::AUTHORIZATION;
use http::HeaderValue;
use ring::hmac;
use std::borrow::Cow;
use std::sync::Arc;
use url::form_urlencoded;
const AZURE_VERSION: &str = "2018-12-31";
const VERSION: &str = "1.0";
/// The `AuthorizationPolicy` takes care to authenticate your calls to Azure CosmosDB. Currently it
/// supports two type of authorization: one at service level and another at resource level (see
/// [AuthorizationToken] for more info). The policy must be added just before the transport policy
/// because it needs to inspect the values that are about to be sent to the transport and inject
/// the proper authorization token.
/// The `AuthorizationPolicy` is the only owner of the passed credentials so if you want to
/// authenticate the same operation with different credentials all you have to do is to swap the
/// `AuthorizationPolicy`.
/// This struct is `Debug` but secrets are encrypted by `AuthorizationToken` so there is no risk of
/// leaks in debug logs (secrets are stored in cleartext in memory: dumps are still leaky).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AuthorizationPolicy {
authorization_token: AuthorizationToken,
}
impl AuthorizationPolicy {
pub(crate) fn new(authorization_token: AuthorizationToken) -> Self {
Self {
authorization_token,
}
}
}
#[async_trait::async_trait]
impl Policy for AuthorizationPolicy {
async fn send(
&self,
ctx: &mut Context,
request: &mut Request,
next: &[Arc<dyn Policy>],
) -> PolicyResult<Response> {
trace!("called AuthorizationPolicy::send. self == {:#?}", self);
if next.is_empty() {
return Err(Box::new(azure_core::PipelineError::InvalidTailPolicy(
"Authorization policies cannot be the last policy of a pipeline".to_owned(),
)));
}
let time_nonce = TimeNonce::new();
let uri_path = &request.uri().path_and_query().unwrap().to_string()[1..];
trace!("uri_path used by AuthorizationPolicy == {:#?}", uri_path);
let auth = {
let resource_link = generate_resource_link(uri_path);
trace!("resource_link == {}", resource_link);
generate_authorization(
&self.authorization_token,
&request.method(),
ctx.get()
.expect("ResourceType must be in the Context at this point"),
resource_link,
time_nonce,
)
};
trace!(
"AuthorizationPolicy calculated authorization == {}: {}",
AUTHORIZATION,
&auth
);
request
.headers_mut()
.insert(HEADER_DATE, HeaderValue::from_str(&time_nonce.to_string())?);
request
.headers_mut()
.insert(HEADER_VERSION, HeaderValue::from_static(AZURE_VERSION));
request
.headers_mut()
.insert(AUTHORIZATION, HeaderValue::from_str(&auth)?);
// now next[0] is safe (will not panic) because we checked
// at the beginning of the function.
next[0].send(ctx, request, &next[1..]).await
}
}
/// This function strips the resource name from the passed uri. It does not alter the uri if a
/// resource name is not present. This is accomplished in three steps (with eager return):
/// 1. Find if the uri ends with a ENDING_STRING. If so, strip it and return. Every ENDING_STRING
/// starts with a leading slash so this check will not match uri compsed **only** by the
/// ENDING_STRING.
/// 2. Find if the uri **is** the ending string (without the leading slash). If so return an empty
/// string. This covers the exception of the rule above.
/// 3. Return the received uri unchanged.
// TODO: will become private as soon as cosmos_client will be migrated
// to pipeline arch.
pub(crate) fn generate_resource_link(uri: &str) -> &str {
static ENDING_STRINGS: &[&str] = &[
"/dbs",
"/colls",
"/docs",
"/sprocs",
"/users",
"/permissions",
"/attachments",
"/pkranges",
"/udfs",
"/triggers",
];
// We find the above resource names. If found, we strip it and eagerly return. Note that the
// resource names have a leading slash so the suffix will match `test/users` but not
// `test-users`.
for ending in ENDING_STRINGS {
if let Some(uri_without_ending) = uri.strip_suffix(ending) {
return uri_without_ending;
}
}
// This check handles the uris comprised by resource names only. It will match `users` and
// return an empty string. This is necessary because the previous check included a leading
// slash.
if ENDING_STRINGS
.iter()
.map(|ending| &ending[1..]) // this is safe since every ENDING_STRING starts with a slash
.any(|item| uri == item)
{
""
} else {
uri
}
}
/// The CosmosDB authorization can either be "primary" (ie one of the two service-level tokens) or
/// "resource" (ie a single database). In the first case the signature must be constructed by
/// signing the HTTP method, resource type, resource link (the relative URI) and the current time.
/// In the second case, the signature is just the resource key.
// TODO: make it private after pipeline migration
pub(crate) fn generate_authorization(
auth_token: &AuthorizationToken,
http_method: &http::Method,
resource_type: &ResourceType,
resource_link: &str,
time_nonce: TimeNonce,
) -> String {
let (authorization_type, signature) = match auth_token {
AuthorizationToken::Primary(key) => {
let string_to_sign =
string_to_sign(http_method, resource_type, resource_link, time_nonce);
(
"master",
Cow::Owned(encode_str_to_sign(&string_to_sign, key)),
)
}
AuthorizationToken::Resource(key) => ("resource", Cow::Borrowed(key)),
};
let str_unencoded = format!(
"type={}&ver={}&sig={}",
authorization_type, VERSION, signature
);
trace!(
"generate_authorization::str_unencoded == {:?}",
str_unencoded
);
form_urlencoded::byte_serialize(str_unencoded.as_bytes()).collect::<String>()
}
/// This function generates a valid authorization string, according to the documentation.
/// In case of authorization problems we can compare the string_to_sign generated by Azure against
/// our own.
fn string_to_sign(
http_method: &http::Method,
rt: &ResourceType,
resource_link: &str,
time_nonce: TimeNonce,
) -> String {
// From official docs:
// StringToSign =
// Verb.toLowerCase() + "\n" +
// ResourceType.toLowerCase() + "\n" +
// ResourceLink + "\n" +
// Date.toLowerCase() + "\n" +
// "" + "\n";
// Notice the empty string at the end so we need to add two new lines
format!(
"{}\n{}\n{}\n{}\n\n",
match *http_method {
http::Method::GET => "get",
http::Method::PUT => "put",
http::Method::POST => "post",
http::Method::DELETE => "delete",
http::Method::HEAD => "head",
http::Method::TRACE => "trace",
http::Method::OPTIONS => "options",
http::Method::CONNECT => "connect",
http::Method::PATCH => "patch",
_ => "extension",
},
match rt {
ResourceType::Databases => "dbs",
ResourceType::Collections => "colls",
ResourceType::Documents => "docs",
ResourceType::StoredProcedures => "sprocs",
ResourceType::Users => "users",
ResourceType::Permissions => "permissions",
ResourceType::Attachments => "attachments",
ResourceType::PartitionKeyRanges => "pkranges",
ResourceType::UserDefinedFunctions => "udfs",
ResourceType::Triggers => "triggers",
},
resource_link,
time_nonce.to_string().to_lowercase()
)
}
/// This function HMAC_SHA256 signs the passed string, given the supplied key. The passed string
/// will be encoded as per its UTF-8 representation. The resulting byte array is then base64
/// encoded and returned to the caller. Possibile optimization: profile if the HMAC struct
/// initialization is expensive and, if so, cache it somehow to avoid recreating it at every
/// request.
fn encode_str_to_sign(str_to_sign: &str, key: &[u8]) -> String {
let key = hmac::Key::new(ring::hmac::HMAC_SHA256, key);
let sig = hmac::sign(&key, str_to_sign.as_bytes());
base64::encode(sig.as_ref())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn string_to_sign_00() {
let time =
chrono::DateTime::parse_from_rfc3339("1900-01-01T01:00:00.000000000+00:00").unwrap();
let time = time.with_timezone(&chrono::Utc).into();
let ret = string_to_sign(
&http::Method::GET,
&ResourceType::Databases,
"dbs/MyDatabase/colls/MyCollection",
time,
);
assert_eq!(
ret,
"get
dbs
dbs/MyDatabase/colls/MyCollection
mon, 01 jan 1900 01:00:00 gmt
"
);
}
#[test]
fn generate_authorization_00() {
let time =
chrono::DateTime::parse_from_rfc3339("1900-01-01T01:00:00.000000000+00:00").unwrap();
let time = time.with_timezone(&chrono::Utc).into();
let auth_token = AuthorizationToken::primary_from_base64(
"8F8xXXOptJxkblM1DBXW7a6NMI5oE8NnwPGYBmwxLCKfejOK7B7yhcCHMGvN3PBrlMLIOeol1Hv9RCdzAZR5sg==",
)
.unwrap();
let ret = generate_authorization(
&auth_token,
&http::Method::GET,
&ResourceType::Databases,
"dbs/MyDatabase/colls/MyCollection",
time,
);
assert_eq!(
ret,
"type%3Dmaster%26ver%3D1.0%26sig%3DQkz%2Fr%2B1N2%2BPEnNijxGbGB%2FADvLsLBQmZ7uBBMuIwf4I%3D"
);
}
#[test]
fn generate_authorization_01() {
let time =
chrono::DateTime::parse_from_rfc3339("2017-04-27T00:51:12.000000000+00:00").unwrap();
let time = time.with_timezone(&chrono::Utc).into();
let auth_token = AuthorizationToken::primary_from_base64(
"dsZQi3KtZmCv1ljt3VNWNm7sQUF1y5rJfC6kv5JiwvW0EndXdDku/dkKBp8/ufDToSxL",
)
.unwrap();
let ret = generate_authorization(
&auth_token,
&http::Method::GET,
&ResourceType::Databases,
"dbs/ToDoList",
time,
);
// This is the result shown in the MSDN page. It's clearly wrong :)
// below is the correct one.
//assert_eq!(ret,
// "type%3dmaster%26ver%3d1.0%26sig%3dc09PEVJrgp2uQRkr934kFbTqhByc7TVr3O");
assert_eq!(
ret,
"type%3Dmaster%26ver%3D1.0%26sig%3DKvBM8vONofkv3yKm%2F8zD9MEGlbu6jjHDJBp4E9c2ZZI%3D"
);
}
#[test]
fn generate_resource_link_00() {
assert_eq!(generate_resource_link("dbs/second"), "dbs/second");
assert_eq!(generate_resource_link("dbs"), "");
assert_eq!(
generate_resource_link("colls/second/third"),
"colls/second/third"
);
assert_eq!(generate_resource_link("dbs/test_db/colls"), "dbs/test_db");
}
}
|
use crate::bba;
use crate::proof_system::*;
use crate::schnorr;
use algebra::{AffineCurve, FftField, PrimeField};
use array_init::array_init;
use plonk_5_wires_circuits::gate::GateType;
use schnorr::CoordinateCurve;
// c, total value
pub const PUBLIC_INPUT: usize = 2;
// Parameters for the update proof circuit.
#[derive(Clone)]
pub struct Params {
pub prices: Vec<u32>,
}
pub struct Witness<F> {
pub counters: Vec<u32>,
pub alpha: [F; ZK_ROWS],
}
pub fn circuit<
F: PrimeField + FftField,
G: AffineCurve<BaseField = F> + CoordinateCurve,
Sys: Cs<F>,
>(
params: &Params,
w: &Option<Witness<F>>,
sys: &mut Sys,
public_input: Vec<Var<F>>,
) {
for r in 0..ZK_ROWS {
let row = array_init(|i| {
if i == 0 {
sys.var(|| w.as_ref().unwrap().alpha[r])
} else {
sys.var(|| F::rand(&mut rand_core::OsRng))
}
});
sys.gate(GateSpec {
typ: GateType::Generic,
c: vec![
F::zero(),
F::zero(),
F::zero(),
F::zero(),
F::zero(),
F::zero(),
F::zero(),
],
row,
});
}
let counter = |i| F::from(w.as_ref().unwrap().counters[i] as u64);
let price = |i| F::from(params.prices[i] as u64);
let mut acc = sys.var(|| counter(0) * price(0));
let row0 = [
sys.var(|| counter(0)),
acc,
sys.var(|| F::zero()),
sys.var(|| F::zero()),
sys.var(|| F::zero()),
];
sys.gate(GateSpec {
typ: GateType::Generic,
row: row0,
c: vec![
price(0),
-F::one(),
F::zero(),
F::zero(),
F::zero(),
F::zero(),
F::zero(),
],
});
for i in 1..bba::MAX_COUNTERS {
let new_acc = if i == bba::MAX_COUNTERS - 1 {
public_input[1]
} else {
sys.var(|| acc.val() + counter(i) * price(i))
};
let row = [
sys.var(|| counter(i)),
acc,
new_acc,
sys.var(|| F::zero()),
sys.var(|| F::zero()),
];
sys.gate(GateSpec {
typ: GateType::Generic,
row: row,
c: vec![
price(i),
F::one(),
-F::one(),
F::zero(),
F::zero(),
F::zero(),
F::zero(),
],
});
acc = new_acc;
}
}
|
use std::collections::HashMap;
use std::io::{self, BufRead};
#[derive(PartialEq, PartialOrd, Eq, Ord, Clone, Debug)]
enum Operation {
Mem {
address: u64,
value: u64,
},
Mask {
and_mask: u64,
or_mask: u64,
mask: String,
},
}
fn parse(s: String) -> Option<Operation> {
match s.get(0..4)? {
"mask" => parse_mask(s),
"mem[" => parse_mem(s),
_ => None,
}
}
fn parse_mask(s: String) -> Option<Operation> {
let mut and_mask = (0..28).map(|_| "1").collect::<String>();
let mut or_mask = (0..28).map(|_| "0").collect::<String>();
and_mask.push_str(&s.get(7..)?.replace("X", "1"));
or_mask.push_str(&s.get(7..)?.replace("X", "0"));
Some(Operation::Mask {
and_mask: u64::from_str_radix(&and_mask, 2).ok()?,
or_mask: u64::from_str_radix(&or_mask, 2).ok()?,
mask: s.get(7..)?.to_string(),
})
}
fn parse_mem(s: String) -> Option<Operation> {
let mut it = s.get(4..)?.split("] = ");
Some(Operation::Mem {
address: it.next()?.parse().ok()?,
value: it.next()?.parse().ok()?,
})
}
fn part1(xs: &[Operation]) -> u64 {
let mut memory = HashMap::new();
let mut current_and_mask: u64 = 0;
let mut current_or_mask: u64 = 0;
for x in xs {
match x {
Operation::Mask {
and_mask,
or_mask,
mask: _,
} => {
current_and_mask = *and_mask;
current_or_mask = *or_mask;
}
Operation::Mem { address, mut value } => {
value &= current_and_mask;
value |= current_or_mask;
*memory.entry(address).or_insert(0) = value;
}
}
}
memory.values().sum()
}
fn part2(xs: &[Operation]) -> u64 {
let mut memory = HashMap::new();
let mut current_mask = &String::new();
for x in xs {
match x {
Operation::Mask {
and_mask: _,
or_mask: _,
mask,
} => current_mask = &mask,
Operation::Mem { address, value } => {
write_part2(&mut memory, *address, *value, ¤t_mask, 0)
}
}
}
memory.values().sum()
}
fn write_part2(
memory: &mut HashMap<u64, u64>,
address: u64,
value: u64,
mask: &str,
final_address: u64,
) {
match mask.chars().last() {
None => *memory.entry(final_address).or_insert(0) = value,
Some('0') => write_part2(
memory,
address / 2,
value,
&mask[..mask.len() - 1],
2 * final_address + address % 2,
),
Some('1') => write_part2(
memory,
address / 2,
value,
&mask[..mask.len() - 1],
2 * final_address + 1,
),
Some('X') => {
write_part2(
memory,
address / 2,
value,
&mask[..mask.len() - 1],
2 * final_address,
);
write_part2(
memory,
address / 2,
value,
&mask[..mask.len() - 1],
2 * final_address + 1,
);
}
_ => panic!(),
}
}
fn main() {
let stdin = io::stdin();
let xs: Vec<_> = stdin
.lock()
.lines()
.filter_map(|x| parse(x.ok()?))
.collect();
let result = part1(&xs);
println!("Part 1: {}", result);
let result = part2(&xs);
println!("Part 2: {}", result);
}
|
#![allow(non_camel_case_types)]
#[cfg(target_arch = "aarch64")]
use core::arch::aarch64::*;
use core::mem::transmute;
// TODO: 等待 stdarch 项目增加 这个类型。
type poly128_t = u128;
#[inline]
unsafe fn vreinterpretq_u8_p128(a: poly128_t) -> uint8x16_t {
transmute(a)
}
// NOTE: 不同编译器的优化:
// https://gist.github.com/LuoZijun/ffa7ec2487c4debd50c44bba1434f410
#[inline]
unsafe fn vmull_low(a: uint8x16_t, b: uint8x16_t) -> uint8x16_t {
let t1: poly64x1_t = vget_low_p64(vreinterpretq_p64_u64(vreinterpretq_u64_u8(a)));
let t2: poly64x1_t = vget_low_p64(vreinterpretq_p64_u64(vreinterpretq_u64_u8(b)));
let r: poly128_t = vmull_p64(transmute(t1), transmute(t2));
return vreinterpretq_u8_p128(r);
}
#[inline]
unsafe fn vmull_high(a: uint8x16_t, b: uint8x16_t) -> uint8x16_t {
let t1: poly64x2_t = vreinterpretq_p64_u64(vreinterpretq_u64_u8(a));
let t2: poly64x2_t = vreinterpretq_p64_u64(vreinterpretq_u64_u8(b));
let r: poly128_t = vmull_high_p64(t1, t2);
return vreinterpretq_u8_p128(r);
}
// Perform the multiplication and reduction in GF(2^128)
#[inline]
unsafe fn gf_mul(key: uint8x16_t, m: &[u8], tag: &mut uint8x16_t) {
let m = vrbitq_u8(vld1q_u8(m.as_ptr()));
let a_p = key;
let b_p = veorq_u8(m, *tag);
let z = vdupq_n_u8(0);
let mut r0 = vmull_low(a_p, b_p);
let mut r1 = vmull_high(a_p, b_p);
let mut t0 = vextq_u8(b_p, b_p, 8);
let mut t1 = vmull_low(a_p, t0);
t0 = vmull_high(a_p, t0);
t0 = veorq_u8(t0, t1);
t1 = vextq_u8(z, t0, 8);
r0 = veorq_u8(r0, t1);
t1 = vextq_u8(t0, z, 8);
r1 = veorq_u8(r1, t1);
let p = vreinterpretq_u8_u64(vdupq_n_u64(0x0000000000000087));
t0 = vmull_high(r1, p);
t1 = vextq_u8(t0, z, 8);
r1 = veorq_u8(r1, t1);
t1 = vextq_u8(z, t0, 8);
r0 = veorq_u8(r0, t1);
t0 = vmull_low(r1, p);
let res = veorq_u8(r0, t0);
*tag = res;
}
#[derive(Clone)]
pub struct GHash {
key: uint8x16_t,
tag: uint8x16_t,
}
impl GHash {
pub const KEY_LEN: usize = 16;
pub const BLOCK_LEN: usize = 16;
pub const TAG_LEN: usize = 16;
pub fn new(h: &[u8; Self::KEY_LEN]) -> Self {
unsafe {
let key: uint8x16_t = vld1q_u8(h.as_ptr());
Self {
key: vrbitq_u8(key),
tag: vdupq_n_u8(0),
}
}
}
pub fn update(&mut self, m: &[u8]) {
let mlen = m.len();
if mlen == 0 {
return ();
}
let n = mlen / Self::BLOCK_LEN;
for i in 0..n {
let chunk = &m[i * Self::BLOCK_LEN..i * Self::BLOCK_LEN + Self::BLOCK_LEN];
let mut block = [0u8; Self::BLOCK_LEN];
block.copy_from_slice(chunk);
unsafe {
gf_mul(self.key, &block, &mut self.tag);
}
}
if mlen % Self::BLOCK_LEN != 0 {
let rem = &m[n * Self::BLOCK_LEN..];
let rlen = rem.len();
let mut last_block = [0u8; Self::BLOCK_LEN];
last_block[..rlen].copy_from_slice(rem);
unsafe {
gf_mul(self.key, &last_block, &mut self.tag);
}
}
}
pub fn finalize(self) -> [u8; Self::TAG_LEN] {
unsafe {
// let mut out = [0u8; Self::TAG_LEN];
// vst1q_u8()
transmute(vrbitq_u8(self.tag))
}
}
}
|
pub mod dict;
pub mod json;
|
#[doc = "Register `COMP4_CSR` reader"]
pub type R = crate::R<COMP4_CSR_SPEC>;
#[doc = "Register `COMP4_CSR` writer"]
pub type W = crate::W<COMP4_CSR_SPEC>;
#[doc = "Field `COMP4EN` reader - Comparator 4 enable"]
pub type COMP4EN_R = crate::BitReader<COMP4EN_A>;
#[doc = "Comparator 4 enable\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum COMP4EN_A {
#[doc = "0: Comparator disabled"]
Disabled = 0,
#[doc = "1: Comparator enabled"]
Enabled = 1,
}
impl From<COMP4EN_A> for bool {
#[inline(always)]
fn from(variant: COMP4EN_A) -> Self {
variant as u8 != 0
}
}
impl COMP4EN_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> COMP4EN_A {
match self.bits {
false => COMP4EN_A::Disabled,
true => COMP4EN_A::Enabled,
}
}
#[doc = "Comparator disabled"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == COMP4EN_A::Disabled
}
#[doc = "Comparator enabled"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == COMP4EN_A::Enabled
}
}
#[doc = "Field `COMP4EN` writer - Comparator 4 enable"]
pub type COMP4EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, COMP4EN_A>;
impl<'a, REG, const O: u8> COMP4EN_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Comparator disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(COMP4EN_A::Disabled)
}
#[doc = "Comparator enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(COMP4EN_A::Enabled)
}
}
#[doc = "Field `COMP4INMSEL` reader - Comparator 4 inverting input selection"]
pub type COMP4INMSEL_R = crate::FieldReader<COMP4INMSEL_A>;
#[doc = "Comparator 4 inverting input selection\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum COMP4INMSEL_A {
#[doc = "0: 1/4 of VRefint"]
OneQuarterVref = 0,
#[doc = "1: 1/2 of VRefint"]
OneHalfVref = 1,
#[doc = "2: 3/4 of VRefint"]
ThreeQuarterVref = 2,
#[doc = "3: VRefint"]
Vref = 3,
#[doc = "4: PA4 or DAC1_CH1 output if enabled"]
Pa4Dac1Ch1 = 4,
#[doc = "5: DAC1_CH2"]
Dac1Ch2 = 5,
#[doc = "7: PB2"]
Pb2 = 7,
}
impl From<COMP4INMSEL_A> for u8 {
#[inline(always)]
fn from(variant: COMP4INMSEL_A) -> Self {
variant as _
}
}
impl crate::FieldSpec for COMP4INMSEL_A {
type Ux = u8;
}
impl COMP4INMSEL_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<COMP4INMSEL_A> {
match self.bits {
0 => Some(COMP4INMSEL_A::OneQuarterVref),
1 => Some(COMP4INMSEL_A::OneHalfVref),
2 => Some(COMP4INMSEL_A::ThreeQuarterVref),
3 => Some(COMP4INMSEL_A::Vref),
4 => Some(COMP4INMSEL_A::Pa4Dac1Ch1),
5 => Some(COMP4INMSEL_A::Dac1Ch2),
7 => Some(COMP4INMSEL_A::Pb2),
_ => None,
}
}
#[doc = "1/4 of VRefint"]
#[inline(always)]
pub fn is_one_quarter_vref(&self) -> bool {
*self == COMP4INMSEL_A::OneQuarterVref
}
#[doc = "1/2 of VRefint"]
#[inline(always)]
pub fn is_one_half_vref(&self) -> bool {
*self == COMP4INMSEL_A::OneHalfVref
}
#[doc = "3/4 of VRefint"]
#[inline(always)]
pub fn is_three_quarter_vref(&self) -> bool {
*self == COMP4INMSEL_A::ThreeQuarterVref
}
#[doc = "VRefint"]
#[inline(always)]
pub fn is_vref(&self) -> bool {
*self == COMP4INMSEL_A::Vref
}
#[doc = "PA4 or DAC1_CH1 output if enabled"]
#[inline(always)]
pub fn is_pa4_dac1_ch1(&self) -> bool {
*self == COMP4INMSEL_A::Pa4Dac1Ch1
}
#[doc = "DAC1_CH2"]
#[inline(always)]
pub fn is_dac1_ch2(&self) -> bool {
*self == COMP4INMSEL_A::Dac1Ch2
}
#[doc = "PB2"]
#[inline(always)]
pub fn is_pb2(&self) -> bool {
*self == COMP4INMSEL_A::Pb2
}
}
#[doc = "Field `COMP4INMSEL` writer - Comparator 4 inverting input selection"]
pub type COMP4INMSEL_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 3, O, COMP4INMSEL_A>;
impl<'a, REG, const O: u8> COMP4INMSEL_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
REG::Ux: From<u8>,
{
#[doc = "1/4 of VRefint"]
#[inline(always)]
pub fn one_quarter_vref(self) -> &'a mut crate::W<REG> {
self.variant(COMP4INMSEL_A::OneQuarterVref)
}
#[doc = "1/2 of VRefint"]
#[inline(always)]
pub fn one_half_vref(self) -> &'a mut crate::W<REG> {
self.variant(COMP4INMSEL_A::OneHalfVref)
}
#[doc = "3/4 of VRefint"]
#[inline(always)]
pub fn three_quarter_vref(self) -> &'a mut crate::W<REG> {
self.variant(COMP4INMSEL_A::ThreeQuarterVref)
}
#[doc = "VRefint"]
#[inline(always)]
pub fn vref(self) -> &'a mut crate::W<REG> {
self.variant(COMP4INMSEL_A::Vref)
}
#[doc = "PA4 or DAC1_CH1 output if enabled"]
#[inline(always)]
pub fn pa4_dac1_ch1(self) -> &'a mut crate::W<REG> {
self.variant(COMP4INMSEL_A::Pa4Dac1Ch1)
}
#[doc = "DAC1_CH2"]
#[inline(always)]
pub fn dac1_ch2(self) -> &'a mut crate::W<REG> {
self.variant(COMP4INMSEL_A::Dac1Ch2)
}
#[doc = "PB2"]
#[inline(always)]
pub fn pb2(self) -> &'a mut crate::W<REG> {
self.variant(COMP4INMSEL_A::Pb2)
}
}
#[doc = "Field `COMP4OUTSEL` reader - Comparator 4 output selection"]
pub type COMP4OUTSEL_R = crate::FieldReader<COMP4OUTSEL_A>;
#[doc = "Comparator 4 output selection\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum COMP4OUTSEL_A {
#[doc = "0: No selection"]
NoSelection = 0,
#[doc = "1: Timer 1 break input"]
Timer1breakInput = 1,
#[doc = "2: Timer 1 break input 2"]
Timer1breakInput2 = 2,
#[doc = "6: Timer 3 input capture 3"]
Timer3inputCapture3 = 6,
#[doc = "8: Timer 15 input capture 2"]
Timer15inputCapture2 = 8,
#[doc = "10: Timer 15 OCREF_CLR input"]
Timer15ocrefClearInput = 10,
#[doc = "11: Timer 3 OCREF_CLR input"]
Timer3ocrefClearInput = 11,
}
impl From<COMP4OUTSEL_A> for u8 {
#[inline(always)]
fn from(variant: COMP4OUTSEL_A) -> Self {
variant as _
}
}
impl crate::FieldSpec for COMP4OUTSEL_A {
type Ux = u8;
}
impl COMP4OUTSEL_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<COMP4OUTSEL_A> {
match self.bits {
0 => Some(COMP4OUTSEL_A::NoSelection),
1 => Some(COMP4OUTSEL_A::Timer1breakInput),
2 => Some(COMP4OUTSEL_A::Timer1breakInput2),
6 => Some(COMP4OUTSEL_A::Timer3inputCapture3),
8 => Some(COMP4OUTSEL_A::Timer15inputCapture2),
10 => Some(COMP4OUTSEL_A::Timer15ocrefClearInput),
11 => Some(COMP4OUTSEL_A::Timer3ocrefClearInput),
_ => None,
}
}
#[doc = "No selection"]
#[inline(always)]
pub fn is_no_selection(&self) -> bool {
*self == COMP4OUTSEL_A::NoSelection
}
#[doc = "Timer 1 break input"]
#[inline(always)]
pub fn is_timer1break_input(&self) -> bool {
*self == COMP4OUTSEL_A::Timer1breakInput
}
#[doc = "Timer 1 break input 2"]
#[inline(always)]
pub fn is_timer1break_input2(&self) -> bool {
*self == COMP4OUTSEL_A::Timer1breakInput2
}
#[doc = "Timer 3 input capture 3"]
#[inline(always)]
pub fn is_timer3input_capture3(&self) -> bool {
*self == COMP4OUTSEL_A::Timer3inputCapture3
}
#[doc = "Timer 15 input capture 2"]
#[inline(always)]
pub fn is_timer15input_capture2(&self) -> bool {
*self == COMP4OUTSEL_A::Timer15inputCapture2
}
#[doc = "Timer 15 OCREF_CLR input"]
#[inline(always)]
pub fn is_timer15ocref_clear_input(&self) -> bool {
*self == COMP4OUTSEL_A::Timer15ocrefClearInput
}
#[doc = "Timer 3 OCREF_CLR input"]
#[inline(always)]
pub fn is_timer3ocref_clear_input(&self) -> bool {
*self == COMP4OUTSEL_A::Timer3ocrefClearInput
}
}
#[doc = "Field `COMP4OUTSEL` writer - Comparator 4 output selection"]
pub type COMP4OUTSEL_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 4, O, COMP4OUTSEL_A>;
impl<'a, REG, const O: u8> COMP4OUTSEL_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
REG::Ux: From<u8>,
{
#[doc = "No selection"]
#[inline(always)]
pub fn no_selection(self) -> &'a mut crate::W<REG> {
self.variant(COMP4OUTSEL_A::NoSelection)
}
#[doc = "Timer 1 break input"]
#[inline(always)]
pub fn timer1break_input(self) -> &'a mut crate::W<REG> {
self.variant(COMP4OUTSEL_A::Timer1breakInput)
}
#[doc = "Timer 1 break input 2"]
#[inline(always)]
pub fn timer1break_input2(self) -> &'a mut crate::W<REG> {
self.variant(COMP4OUTSEL_A::Timer1breakInput2)
}
#[doc = "Timer 3 input capture 3"]
#[inline(always)]
pub fn timer3input_capture3(self) -> &'a mut crate::W<REG> {
self.variant(COMP4OUTSEL_A::Timer3inputCapture3)
}
#[doc = "Timer 15 input capture 2"]
#[inline(always)]
pub fn timer15input_capture2(self) -> &'a mut crate::W<REG> {
self.variant(COMP4OUTSEL_A::Timer15inputCapture2)
}
#[doc = "Timer 15 OCREF_CLR input"]
#[inline(always)]
pub fn timer15ocref_clear_input(self) -> &'a mut crate::W<REG> {
self.variant(COMP4OUTSEL_A::Timer15ocrefClearInput)
}
#[doc = "Timer 3 OCREF_CLR input"]
#[inline(always)]
pub fn timer3ocref_clear_input(self) -> &'a mut crate::W<REG> {
self.variant(COMP4OUTSEL_A::Timer3ocrefClearInput)
}
}
#[doc = "Field `COMP4POL` reader - Comparator 4 output polarity"]
pub type COMP4POL_R = crate::BitReader<COMP4POL_A>;
#[doc = "Comparator 4 output polarity\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum COMP4POL_A {
#[doc = "0: Output is not inverted"]
NotInverted = 0,
#[doc = "1: Output is inverted"]
Inverted = 1,
}
impl From<COMP4POL_A> for bool {
#[inline(always)]
fn from(variant: COMP4POL_A) -> Self {
variant as u8 != 0
}
}
impl COMP4POL_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> COMP4POL_A {
match self.bits {
false => COMP4POL_A::NotInverted,
true => COMP4POL_A::Inverted,
}
}
#[doc = "Output is not inverted"]
#[inline(always)]
pub fn is_not_inverted(&self) -> bool {
*self == COMP4POL_A::NotInverted
}
#[doc = "Output is inverted"]
#[inline(always)]
pub fn is_inverted(&self) -> bool {
*self == COMP4POL_A::Inverted
}
}
#[doc = "Field `COMP4POL` writer - Comparator 4 output polarity"]
pub type COMP4POL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, COMP4POL_A>;
impl<'a, REG, const O: u8> COMP4POL_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Output is not inverted"]
#[inline(always)]
pub fn not_inverted(self) -> &'a mut crate::W<REG> {
self.variant(COMP4POL_A::NotInverted)
}
#[doc = "Output is inverted"]
#[inline(always)]
pub fn inverted(self) -> &'a mut crate::W<REG> {
self.variant(COMP4POL_A::Inverted)
}
}
#[doc = "Field `COMP4_BLANKING` reader - Comparator 4 blanking source"]
pub type COMP4_BLANKING_R = crate::FieldReader<COMP4_BLANKING_A>;
#[doc = "Comparator 4 blanking source\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum COMP4_BLANKING_A {
#[doc = "0: No blanking"]
NoBlanking = 0,
#[doc = "1: TIM3 OC4 selected as blanking source"]
Tim3oc4 = 1,
#[doc = "3: TIM15 OC1 selected as blanking source"]
Tim15oc1 = 3,
}
impl From<COMP4_BLANKING_A> for u8 {
#[inline(always)]
fn from(variant: COMP4_BLANKING_A) -> Self {
variant as _
}
}
impl crate::FieldSpec for COMP4_BLANKING_A {
type Ux = u8;
}
impl COMP4_BLANKING_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<COMP4_BLANKING_A> {
match self.bits {
0 => Some(COMP4_BLANKING_A::NoBlanking),
1 => Some(COMP4_BLANKING_A::Tim3oc4),
3 => Some(COMP4_BLANKING_A::Tim15oc1),
_ => None,
}
}
#[doc = "No blanking"]
#[inline(always)]
pub fn is_no_blanking(&self) -> bool {
*self == COMP4_BLANKING_A::NoBlanking
}
#[doc = "TIM3 OC4 selected as blanking source"]
#[inline(always)]
pub fn is_tim3oc4(&self) -> bool {
*self == COMP4_BLANKING_A::Tim3oc4
}
#[doc = "TIM15 OC1 selected as blanking source"]
#[inline(always)]
pub fn is_tim15oc1(&self) -> bool {
*self == COMP4_BLANKING_A::Tim15oc1
}
}
#[doc = "Field `COMP4_BLANKING` writer - Comparator 4 blanking source"]
pub type COMP4_BLANKING_W<'a, REG, const O: u8> =
crate::FieldWriter<'a, REG, 3, O, COMP4_BLANKING_A>;
impl<'a, REG, const O: u8> COMP4_BLANKING_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
REG::Ux: From<u8>,
{
#[doc = "No blanking"]
#[inline(always)]
pub fn no_blanking(self) -> &'a mut crate::W<REG> {
self.variant(COMP4_BLANKING_A::NoBlanking)
}
#[doc = "TIM3 OC4 selected as blanking source"]
#[inline(always)]
pub fn tim3oc4(self) -> &'a mut crate::W<REG> {
self.variant(COMP4_BLANKING_A::Tim3oc4)
}
#[doc = "TIM15 OC1 selected as blanking source"]
#[inline(always)]
pub fn tim15oc1(self) -> &'a mut crate::W<REG> {
self.variant(COMP4_BLANKING_A::Tim15oc1)
}
}
#[doc = "Field `COMP4INMSEL3` reader - Comparator 4 inverting input selection"]
pub type COMP4INMSEL3_R = crate::BitReader;
#[doc = "Field `COMP4INMSEL3` writer - Comparator 4 inverting input selection"]
pub type COMP4INMSEL3_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `COMP4OUT` reader - Comparator 4 output"]
pub type COMP4OUT_R = crate::BitReader<COMP4OUT_A>;
#[doc = "Comparator 4 output\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum COMP4OUT_A {
#[doc = "0: Non-inverting input below inverting input"]
Low = 0,
#[doc = "1: Non-inverting input above inverting input"]
High = 1,
}
impl From<COMP4OUT_A> for bool {
#[inline(always)]
fn from(variant: COMP4OUT_A) -> Self {
variant as u8 != 0
}
}
impl COMP4OUT_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> COMP4OUT_A {
match self.bits {
false => COMP4OUT_A::Low,
true => COMP4OUT_A::High,
}
}
#[doc = "Non-inverting input below inverting input"]
#[inline(always)]
pub fn is_low(&self) -> bool {
*self == COMP4OUT_A::Low
}
#[doc = "Non-inverting input above inverting input"]
#[inline(always)]
pub fn is_high(&self) -> bool {
*self == COMP4OUT_A::High
}
}
#[doc = "Field `COMP4LOCK` reader - Comparator 4 lock"]
pub type COMP4LOCK_R = crate::BitReader<COMP4LOCK_A>;
#[doc = "Comparator 4 lock\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum COMP4LOCK_A {
#[doc = "0: Comparator CSR bits are read-write"]
Unlocked = 0,
#[doc = "1: Comparator CSR bits are read-only"]
Locked = 1,
}
impl From<COMP4LOCK_A> for bool {
#[inline(always)]
fn from(variant: COMP4LOCK_A) -> Self {
variant as u8 != 0
}
}
impl COMP4LOCK_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> COMP4LOCK_A {
match self.bits {
false => COMP4LOCK_A::Unlocked,
true => COMP4LOCK_A::Locked,
}
}
#[doc = "Comparator CSR bits are read-write"]
#[inline(always)]
pub fn is_unlocked(&self) -> bool {
*self == COMP4LOCK_A::Unlocked
}
#[doc = "Comparator CSR bits are read-only"]
#[inline(always)]
pub fn is_locked(&self) -> bool {
*self == COMP4LOCK_A::Locked
}
}
#[doc = "Field `COMP4LOCK` writer - Comparator 4 lock"]
pub type COMP4LOCK_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, COMP4LOCK_A>;
impl<'a, REG, const O: u8> COMP4LOCK_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Comparator CSR bits are read-write"]
#[inline(always)]
pub fn unlocked(self) -> &'a mut crate::W<REG> {
self.variant(COMP4LOCK_A::Unlocked)
}
#[doc = "Comparator CSR bits are read-only"]
#[inline(always)]
pub fn locked(self) -> &'a mut crate::W<REG> {
self.variant(COMP4LOCK_A::Locked)
}
}
impl R {
#[doc = "Bit 0 - Comparator 4 enable"]
#[inline(always)]
pub fn comp4en(&self) -> COMP4EN_R {
COMP4EN_R::new((self.bits & 1) != 0)
}
#[doc = "Bits 4:6 - Comparator 4 inverting input selection"]
#[inline(always)]
pub fn comp4inmsel(&self) -> COMP4INMSEL_R {
COMP4INMSEL_R::new(((self.bits >> 4) & 7) as u8)
}
#[doc = "Bits 10:13 - Comparator 4 output selection"]
#[inline(always)]
pub fn comp4outsel(&self) -> COMP4OUTSEL_R {
COMP4OUTSEL_R::new(((self.bits >> 10) & 0x0f) as u8)
}
#[doc = "Bit 15 - Comparator 4 output polarity"]
#[inline(always)]
pub fn comp4pol(&self) -> COMP4POL_R {
COMP4POL_R::new(((self.bits >> 15) & 1) != 0)
}
#[doc = "Bits 18:20 - Comparator 4 blanking source"]
#[inline(always)]
pub fn comp4_blanking(&self) -> COMP4_BLANKING_R {
COMP4_BLANKING_R::new(((self.bits >> 18) & 7) as u8)
}
#[doc = "Bit 22 - Comparator 4 inverting input selection"]
#[inline(always)]
pub fn comp4inmsel3(&self) -> COMP4INMSEL3_R {
COMP4INMSEL3_R::new(((self.bits >> 22) & 1) != 0)
}
#[doc = "Bit 30 - Comparator 4 output"]
#[inline(always)]
pub fn comp4out(&self) -> COMP4OUT_R {
COMP4OUT_R::new(((self.bits >> 30) & 1) != 0)
}
#[doc = "Bit 31 - Comparator 4 lock"]
#[inline(always)]
pub fn comp4lock(&self) -> COMP4LOCK_R {
COMP4LOCK_R::new(((self.bits >> 31) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - Comparator 4 enable"]
#[inline(always)]
#[must_use]
pub fn comp4en(&mut self) -> COMP4EN_W<COMP4_CSR_SPEC, 0> {
COMP4EN_W::new(self)
}
#[doc = "Bits 4:6 - Comparator 4 inverting input selection"]
#[inline(always)]
#[must_use]
pub fn comp4inmsel(&mut self) -> COMP4INMSEL_W<COMP4_CSR_SPEC, 4> {
COMP4INMSEL_W::new(self)
}
#[doc = "Bits 10:13 - Comparator 4 output selection"]
#[inline(always)]
#[must_use]
pub fn comp4outsel(&mut self) -> COMP4OUTSEL_W<COMP4_CSR_SPEC, 10> {
COMP4OUTSEL_W::new(self)
}
#[doc = "Bit 15 - Comparator 4 output polarity"]
#[inline(always)]
#[must_use]
pub fn comp4pol(&mut self) -> COMP4POL_W<COMP4_CSR_SPEC, 15> {
COMP4POL_W::new(self)
}
#[doc = "Bits 18:20 - Comparator 4 blanking source"]
#[inline(always)]
#[must_use]
pub fn comp4_blanking(&mut self) -> COMP4_BLANKING_W<COMP4_CSR_SPEC, 18> {
COMP4_BLANKING_W::new(self)
}
#[doc = "Bit 22 - Comparator 4 inverting input selection"]
#[inline(always)]
#[must_use]
pub fn comp4inmsel3(&mut self) -> COMP4INMSEL3_W<COMP4_CSR_SPEC, 22> {
COMP4INMSEL3_W::new(self)
}
#[doc = "Bit 31 - Comparator 4 lock"]
#[inline(always)]
#[must_use]
pub fn comp4lock(&mut self) -> COMP4LOCK_W<COMP4_CSR_SPEC, 31> {
COMP4LOCK_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "control and status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`comp4_csr::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 [`comp4_csr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct COMP4_CSR_SPEC;
impl crate::RegisterSpec for COMP4_CSR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`comp4_csr::R`](R) reader structure"]
impl crate::Readable for COMP4_CSR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`comp4_csr::W`](W) writer structure"]
impl crate::Writable for COMP4_CSR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets COMP4_CSR to value 0"]
impl crate::Resettable for COMP4_CSR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use std::io::{self};
pub fn readline(mut input: String) -> String {
io::stdin().read_line(&mut input).unwrap();
input
}
pub fn parse_all<T>(s: &str) -> Vec<T>
where
T: std::str::FromStr,
<T as std::str::FromStr>::Err: std::fmt::Debug,
{
let v: Vec<&str> = s.split(" ").collect();
v.into_iter().map(|x| parse(x)).collect()
}
pub fn parse<T>(s: &str) -> T
where
T: std::str::FromStr,
<T as std::str::FromStr>::Err: std::fmt::Debug,
{
s.trim_end_matches('\n').parse::<T>().unwrap()
}
pub fn check_duplicate<T>(mut v: Vec<T>, n: T) -> Vec<T>
where
T: std::clone::Clone + std::cmp::PartialEq,
{
if !v.contains(&n) {
v.push(n);
}
v.to_vec()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_check_duplicate1() {
assert_eq!(check_duplicate(vec![1, 2, 3], 2), vec![1, 2, 3])
}
#[test]
fn test_check_duplicate2() {
assert_eq!(check_duplicate(vec![1, 2, 3], 4), vec![1, 2, 3, 4])
}
#[test]
fn test_check_duplicate3() {
assert_eq!(
check_duplicate(vec!["1", "2", "3"], "2"),
vec!["1", "2", "3"]
)
}
#[test]
fn test_parse() {
assert_eq!(parse::<i32>("123"), 123)
}
}
|
use reqwest::Certificate;
use std::{fs::File, io::Read, path::Path};
const SERVICE_CA_CERT: &str = "/var/run/secrets/kubernetes.io/serviceaccount/service-ca.crt";
pub fn add_service_cert(
mut client: reqwest::ClientBuilder,
) -> anyhow::Result<reqwest::ClientBuilder> {
let cert = Path::new(SERVICE_CA_CERT);
if cert.exists() {
log::info!("Adding root certificate: {:?}", cert);
let mut file = File::open(cert)?;
let mut buf = Vec::new();
file.read_to_end(&mut buf)?;
let pems = pem::parse_many(buf);
let pems = pems
.into_iter()
.map(|pem| {
Certificate::from_pem(&pem::encode(&pem).into_bytes()).map_err(|err| err.into())
})
.collect::<anyhow::Result<Vec<_>>>()?;
log::info!("Found {} certificates", pems.len());
// we need rustls for adding root certificates
client = client.use_rustls_tls();
for pem in pems {
log::info!("Adding root certificate: {:?}", pem);
client = client.add_root_certificate(pem);
}
} else {
log::info!(
"Service CA certificate does not exist, skipping! ({:?})",
cert
);
}
Ok(client)
}
#[cfg(feature = "rustls")]
mod rustls {
use rust_tls::{
internal::msgs::handshake::DigitallySignedStruct, Certificate, ClientConfig,
HandshakeSignatureValid, RootCertStore, ServerCertVerified, ServerCertVerifier, TLSError,
};
use webpki::DNSNameRef;
struct NoVerifier;
impl ServerCertVerifier for NoVerifier {
fn verify_server_cert(
&self,
_roots: &RootCertStore,
_presented_certs: &[Certificate],
_dns_name: DNSNameRef,
_ocsp_response: &[u8],
) -> Result<ServerCertVerified, TLSError> {
Ok(ServerCertVerified::assertion())
}
fn verify_tls12_signature(
&self,
_message: &[u8],
_cert: &Certificate,
_dss: &DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, TLSError> {
Ok(HandshakeSignatureValid::assertion())
}
fn verify_tls13_signature(
&self,
_message: &[u8],
_cert: &Certificate,
_dss: &DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, TLSError> {
Ok(HandshakeSignatureValid::assertion())
}
}
pub fn make_insecure(client: reqwest::ClientBuilder) -> reqwest::ClientBuilder {
log::warn!("Disabling TLS verification for client. Do not use this in production!");
let mut tls = ClientConfig::new();
tls.dangerous()
.set_certificate_verifier(std::sync::Arc::new(NoVerifier));
client.use_preconfigured_tls(tls)
}
}
#[cfg(feature = "rustls")]
pub use rustls::*;
|
use std::ops::{Add, Div, Mul, Neg, Sub};
use crate::prelude::*;
#[derive(Debug, Copy, Clone)]
pub struct Tuple {
pub x: f32,
pub y: f32,
pub z: f32,
pub w: f32,
}
impl Tuple {
pub const fn new(x: f32, y: f32, z: f32, w: f32) -> Self {
Self { x, y, z, w }
}
pub fn from_point(x: f32, y: f32, z: f32) -> Self {
Self { x, y, z, w: 1.0 }
}
pub fn from_vector(x: f32, y: f32, z: f32) -> Self {
Self { x, y, z, w: 0.0 }
}
pub fn is_point(&self) -> bool {
self.w == 1.0
}
pub fn is_vector(&self) -> bool {
self.w == 0.0
}
pub fn magnitude(&self) -> f32 {
(self.x.powi(2) + self.y.powi(2) + self.z.powi(2) + self.w.powi(2)).sqrt()
}
pub fn normalize(&self) -> Self {
let magnitude = self.magnitude();
Self {
x: self.x / magnitude,
y: self.y / magnitude,
z: self.z / magnitude,
w: self.w / magnitude,
}
}
pub fn dot(&self, rhs: &Self) -> f32 {
self.x * rhs.x + self.y * rhs.y + self.z * rhs.z + self.w * rhs.w
}
pub fn cross(&self, rhs: &Self) -> Self {
// FIXME: having a proper type would be much better.
assert!(self.is_vector() && rhs.is_vector());
Self {
x: self.y * rhs.z - self.z * rhs.y,
y: self.z * rhs.x - self.x * rhs.z,
z: self.x * rhs.y - self.y * rhs.x,
w: 0.0,
}
}
}
impl PartialEq for Tuple {
fn eq(&self, other: &Self) -> bool {
is_approx(self.x, other.x, None)
&& is_approx(self.y, other.y, None)
&& is_approx(self.z, other.z, None)
&& is_approx(self.w, other.w, None)
}
}
impl Add for Tuple {
type Output = Self;
fn add(self, rhs: Self) -> Self::Output {
Self {
x: self.x + rhs.x,
y: self.y + rhs.y,
z: self.z + rhs.z,
w: self.w + rhs.w,
}
}
}
impl Sub for Tuple {
type Output = Self;
fn sub(self, rhs: Self) -> Self::Output {
Self {
x: self.x - rhs.x,
y: self.y - rhs.y,
z: self.z - rhs.z,
w: self.w - rhs.w,
}
}
}
impl Neg for Tuple {
type Output = Self;
fn neg(self) -> Self::Output {
Self {
x: -self.x,
y: -self.y,
z: -self.z,
w: -self.w,
}
}
}
impl Mul<f32> for Tuple {
type Output = Self;
fn mul(self, rhs: f32) -> Self::Output {
Self {
x: self.x * rhs,
y: self.y * rhs,
z: self.z * rhs,
w: self.w * rhs,
}
}
}
impl Div<f32> for Tuple {
type Output = Self;
fn div(self, rhs: f32) -> Self::Output {
Self {
x: self.x / rhs,
y: self.y / rhs,
z: self.z / rhs,
w: self.w / rhs,
}
}
}
#[cfg(test)]
mod tests {
use crate::prelude::*;
//Scenario: A tuple with w=1.0 is a point
// Given a ← tuple(4.3, -4.2, 3.1, 1.0)
// Then a.x = 4.3
// And a.y = -4.2
// And a.z = 3.1
// And a.w = 1.0
// And a is a point
// And a is not a vector
#[test]
fn tuple_with_w_1_is_a_point() {
let a = Tuple::new(4.3, -4.2, 3.1, 1.0);
assert_eq!(a.x, 4.3);
assert_eq!(a.y, -4.2);
assert_eq!(a.z, 3.1);
assert_eq!(a.w, 1.0);
assert_eq!(a.is_point(), true);
assert_eq!(a.is_vector(), false);
}
//Scenario: A tuple with w=0 is a vector
// Given a ← tuple(4.3, -4.2, 3.1, 0.0)
// Then a.x = 4.3
// And a.y = -4.2
// And a.z = 3.1
// And a.w = 0.0
// And a is not a point
// And a is a vector
#[test]
fn tuple_with_w_0_is_a_vector() {
let a = Tuple::new(4.3, -4.2, 3.1, 0.0);
assert_eq!(a.x, 4.3);
assert_eq!(a.y, -4.2);
assert_eq!(a.z, 3.1);
assert_eq!(a.w, 0.0);
assert_eq!(a.is_point(), false);
assert_eq!(a.is_vector(), true);
}
#[test]
fn is_approx_with_tuples() {
let t1 = Tuple::new(1.0, -1.0, 2.3, 4.5);
let t2 = Tuple::new(1.000001, -1.00005, 2.30003, 4.500005);
assert_eq!(t1, t2);
}
// Scenario: point() creates tuples with w=1
// Given p ← point(4, -4, 3)
// Then p = tuple(4, -4, 3, 1)}
#[test]
fn point_creates_tuple_with_w_1() {
let p = Tuple::from_point(4.0, -4.0, 3.0);
let expected = Tuple::new(4.0, -4.0, 3.0, 1.0);
assert_eq!(p, expected);
}
// Scenario: vector() creates tuples with w=0
// Given v ← vector(4, -4, 3)
// Then v = tuple(4, -4, 3, 0)
#[test]
fn vector_creates_tuple_with_w_0() {
let v = Tuple::from_vector(4.0, -4.0, 3.0);
let expected = Tuple::new(4.0, -4.0, 3.0, 0.0);
assert_eq!(v, expected);
}
// Scenario: Adding two tuples
// Given a1 ← tuple(3, -2, 5, 1)
// And a2 ← tuple(-2, 3, 1, 0)
// Then a1 + a2 = tuple(1, 1, 6, 1)
#[test]
fn adding_two_tuples() {
let a1 = Tuple::new(3.0, -2.0, 5.0, 1.0);
let a2 = Tuple::new(-2.0, 3.0, 1.0, 0.0);
let expected = Tuple::new(1.0, 1.0, 6.0, 1.0);
assert_eq!(a1 + a2, expected);
}
// Scenario: Subtracting two points
// Given p1 ← point(3, 2, 1)
// And p2 ← point(5, 6, 7)
// Then p1 - p2 = vector(-2, -4, -6)
#[test]
fn subtracting_two_points() {
let a1 = Tuple::from_point(3.0, 2.0, 1.0);
let a2 = Tuple::from_point(5.0, 6.0, 7.0);
let expected = Tuple::from_vector(-2.0, -4.0, -6.0);
assert_eq!(a1 - a2, expected);
}
// Scenario: Subtracting a vector from a point
// Given p ← point(3, 2, 1)
// And v ← vector(5, 6, 7)
// Then p - v = point(-2, -4, -6)
#[test]
fn subtracting_vector_from_point() {
let p = Tuple::from_point(3.0, 2.0, 1.0);
let v = Tuple::from_vector(5.0, 6.0, 7.0);
let expected = Tuple::from_point(-2.0, -4.0, -6.0);
assert_eq!(p - v, expected);
}
// Scenario: Subtracting two vectors
// Given v1 ← vector(3, 2, 1)
// And v2 ← vector(5, 6, 7)
// Then v1 - v2 = vector(-2, -4, -6)
#[test]
fn subtracting_two_vectors() {
let v1 = Tuple::from_vector(3.0, 2.0, 1.0);
let v2 = Tuple::from_vector(5.0, 6.0, 7.0);
let expected = Tuple::from_vector(-2.0, -4.0, -6.0);
assert_eq!(v1 - v2, expected);
}
// Scenario: Subtracting a vector from the zero vector
// Given zero ← vector(0, 0, 0)
// And v ← vector(1, -2, 3)
// Then zero - v = vector(-1, 2, -3)
#[test]
fn subtracting_vector_from_zero_vector() {
let zero = Tuple::from_vector(0.0, 0.0, 0.0);
let v = Tuple::from_vector(1.0, -2.0, 3.0);
let expected = Tuple::from_vector(-1.0, 2.0, -3.0);
assert_eq!(zero - v, expected);
}
// Scenario: Negating a tuple
// Given a ← tuple(1, -2, 3, -4)
// Then -a = tuple(-1, 2, -3, 4)
#[test]
fn negating_tuple() {
let a = Tuple::new(1.0, -2.0, 3.0, -4.0);
let expected = Tuple::new(-1.0, 2.0, -3.0, 4.0);
assert_eq!(-a, expected);
}
// Scenario: Multiplying a tuple by a scalar
// Given a ← tuple(1, -2, 3, -4)
// Then a * 3.5 = tuple(3.5, -7, 10.5, -14)
#[test]
fn multiplying_tuple_by_scalar() {
let a = Tuple::new(1.0, -2.0, 3.0, -4.0);
let s: f32 = 3.5;
let expected = Tuple::new(3.5, -7.0, 10.5, -14.0);
assert_eq!(a * s, expected);
}
// Scenario: Multiplying a tuple by a fraction
// Given a ← tuple(1, -2, 3, -4)
// Then a * 0.5 = tuple(0.5, -1, 1.5, -2)
#[test]
fn multiplying_tuple_by_fraction() {
let a = Tuple::new(1.0, -2.0, 3.0, -4.0);
let s: f32 = 0.5;
let expected = Tuple::new(0.5, -1.0, 1.5, -2.0);
assert_eq!(a * s, expected);
}
// Scenario: Dividing a tuple by a scalar
// Given a ← tuple(1, -2, 3, -4)
// Then a / 2 = tuple(0.5, -1, 1.5, -2)
#[test]
fn dividing_tuple_by_scalar() {
let a = Tuple::new(1.0, -2.0, 3.0, -4.0);
let s: f32 = 2.0;
let expected = Tuple::new(0.5, -1.0, 1.5, -2.0);
assert_eq!(a / s, expected);
}
// Scenario: Computing the magnitude of vector(1, 0, 0)
// Given v ← vector(1, 0, 0)
// Then magnitude(v) = 1
#[test]
fn computing_magnitude_of_vector_ex() {
let v = Tuple::from_vector(1.0, 0.0, 0.0);
let expected = 1.0;
assert_eq!(v.magnitude(), expected);
}
// Scenario: Computing the magnitude of vector(0, 1, 0)
// Given v ← vector(0, 1, 0)
// Then magnitude(v) = 1
#[test]
fn computing_magnitude_of_vector_ey() {
let v = Tuple::from_vector(0.0, 1.0, 0.0);
let expected = 1.0;
assert_eq!(v.magnitude(), expected);
}
// Scenario: Computing the magnitude of vector(0, 0, 1)
// Given v ← vector(0, 0, 1)
// Then magnitude(v) = 1
#[test]
fn computing_magnitude_of_vector_ez() {
let v = Tuple::from_vector(0.0, 0.0, 1.0);
let expected = 1.0;
assert_eq!(v.magnitude(), expected);
}
// Scenario: Computing the magnitude of vector(1, 2, 3)
// Given v ← vector(1, 2, 3)
// Then magnitude(v) = √14
#[test]
fn computing_magnitude_of_vector_pos() {
let v = Tuple::from_vector(1.0, 2.0, 3.0);
let expected = (14.0f32).sqrt();
assert_eq!(v.magnitude(), expected);
}
// Scenario: Computing the magnitude of vector(-1, -2, -3)
// Given v ← vector(-1, -2, -3)
// Then magnitude(v) = √14
#[test]
fn computing_magnitude_of_vector_neg() {
let v = Tuple::from_vector(-1.0, -2.0, -3.0);
let expected = (14.0f32).sqrt();
assert_eq!(v.magnitude(), expected);
}
// Scenario: Normalizing vector(4, 0, 0) gives (1, 0, 0)
// Given v ← vector(4, 0, 0)
// Then normalize(v) = vector(1, 0, 0)
#[test]
fn normalizing_vector_gives_ex() {
let v = Tuple::from_vector(4.0, 0.0, 0.0);
let expected = Tuple::from_vector(1.0, 0.0, 0.0);
assert_eq!(v.normalize(), expected);
}
// Scenario: Normalizing vector(1, 2, 3)
// Given v ← vector(1, 2, 3)
// Then normalize(v) = approximately vector(0.26726, 0.53452, 0.80178)
#[test]
fn normalizing_vector() {
let v = Tuple::from_vector(1.0, 2.0, 3.0);
let expected = Tuple::from_vector(0.26726, 0.53452, 0.80178);
assert_eq!(v.normalize(), expected);
}
// Scenario: The magnitude of a normalized vector
// Given v ← vector(1, 2, 3)
// When norm ← normalize(v)
// Then magnitude(norm) = 1
#[test]
fn magnitude_of_normalized_vector() {
let v = Tuple::from_vector(1.0, 2.0, 3.0);
let n = v.normalize();
let expected = 1.0;
assert!(is_approx(n.magnitude(), expected, None));
}
// Scenario: The dot product of two tuples
// Given a ← vector(1, 2, 3)
// And b ← vector(2, 3, 4)
// Then dot(a, b) = 20
#[test]
fn dot_product_of_two_tuples() {
let a = Tuple::from_vector(1.0, 2.0, 3.0);
let b = Tuple::from_vector(2.0, 3.0, 4.0);
let expected = 20.0;
assert_eq!(a.dot(&b), expected);
}
// Scenario: The cross product of two vectors
// Given a ← vector(1, 2, 3)
// And b ← vector(2, 3, 4)
// Then cross(a, b) = vector(-1, 2, -1)
// And cross(b, a) = vector(1, -2, 1)
#[test]
fn cross_product_of_two_vectors() {
let a = Tuple::from_vector(1.0, 2.0, 3.0);
let b = Tuple::from_vector(2.0, 3.0, 4.0);
let expected_ab = Tuple::from_vector(-1.0, 2.0, -1.0);
let expected_ba = Tuple::from_vector(1.0, -2.0, 1.0);
assert_eq!(a.cross(&b), expected_ab);
assert_eq!(b.cross(&a), expected_ba);
}
}
|
#![doc(html_root_url = "https://spetex.github.io/spacesim/")]
//! # Spacesim Library
//! Hobby library for simulating celestial mechanics
pub mod datatypes;
pub mod calculations;
pub mod objects {
use datatypes::Coordinates;
/// Celestial is a generic object for everything that can reside in the space.
pub struct Celestial {
pub id: i32,
pub location: Coordinates,
}
impl Celestial {
/// Celestial constructor - creates new celestial object
pub fn new(id: i32) -> Celestial {
Celestial {
id: id,
location: Coordinates::new_default(),
}
}
}
/// The Universe - Every interaction takes place in the relation to the universe.
pub struct Universe {
id: i8,
num_objects: i32,
epoch: i32,
celestials: Vec<Celestial>,
}
impl Universe {
/// Universe constructor - creates single universe containing 1 celestial.
pub fn new(id: i8) -> Universe {
Universe {
id: id,
num_objects: 0,
epoch: 0,
celestials: Vec::new(),
}
}
/// Returns id of the universe.
pub fn get_id(&self) -> i8 {
self.id
}
/// Spawns a celestial in the origin.
pub fn spawn(&mut self) {
self.celestials.push(Celestial::new(self.num_objects));
self.num_objects = self.num_objects + 1;
}
/// Returns a count of all celestials in the given universe.
pub fn get_celestial_count(&self) -> i32 {
self.celestials.len() as i32
}
/// Returns reference to the celestial with given id.
pub fn get_celestial(&self, id: i32) -> &Celestial {
&self.celestials[id as usize]
}
/// Moves celestial by id to a given position.
pub fn set_position(&mut self, id: i32, point: Coordinates) {
self.celestials[id as usize].location = point;
}
}
}
mod tests;
|
//! Various utils to implement `fumio` that are not actually specific to it.
#![doc(html_root_url = "https://docs.rs/fumio-utils/0.1.0")]
#![warn(
missing_debug_implementations,
missing_docs,
nonstandard_style,
rust_2018_idioms,
clippy::pedantic,
clippy::nursery,
clippy::cargo,
)]
#![allow(
clippy::module_name_repetitions, // often hidden modules and reexported
clippy::if_not_else, // `... != 0` is a positive condition
clippy::multiple_crate_versions, // not useful
)]
#[doc(hidden)]
pub mod mpsc;
#[doc(hidden)]
pub mod local_dl_list;
pub mod current;
pub mod park;
|
use std::error as rust_error;
use std::fmt;
use std::str::Utf8Error;
/// An error type for libpcap operations.
#[derive(Debug)]
pub struct Error {
inner: Inner,
}
#[derive(Debug)]
enum Inner {
Pcap(String),
Utf8(Utf8Error),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match self.inner {
Inner::Pcap(ref text) => f.write_str(&text),
Inner::Utf8(ref err) => err.fmt(f),
}
}
}
impl rust_error::Error for Error {
fn description(&self) -> &str {
match self.inner {
Inner::Pcap(ref text) => text,
Inner::Utf8(ref err) => err.description(),
}
}
fn cause(&self) -> Option<&rust_error::Error> {
match self.inner {
Inner::Pcap(_) => None,
Inner::Utf8(ref err) => Some(err),
}
}
}
impl From<String> for Error {
fn from(err: String) -> Error {
Error { inner: Inner::Pcap(err) }
}
}
impl From<Utf8Error> for Error {
fn from(err: Utf8Error) -> Error {
Error { inner: Inner::Utf8(err) }
}
}
|
/// Disclaimer: The lexer is basically spaghetti. What did you expect?
#[derive(Clone, Debug, PartialEq)]
pub enum Token {
// Words
Select, From, Where, Group, Having, By, Limit,
Distinct,
Order, Asc, Desc,
As, Join, Inner, Outer, Left, Right, On,
Insert, Into, Values, Update, Delete,
Create, Table, Index, Constraint,
Primary, Key, Unique, References,
And, Or,
Between, In,
Is, Not, Null,
Explain,
// Non-letter tokens
Equal,
NotEqual,
LessThan, LessThanOrEqual,
GreaterThan, GreaterThanOrEqual,
Plus, Minus,
LeftParen, RightParen,
LeftBracket, RightBracket,
Dot, Comma, Semicolon,
Ampersand, Pipe, ForwardSlash,
/// ||, the concatenate operator
DoublePipe,
/// *, the wildcard for SELECT
Asterisk,
/// ?, the prepared statement placeholder
PreparedStatementPlaceholder,
// Tokens with values
Number(String),
Ident(String),
StringLiteral(String)
}
fn character_to_token(c: char) -> Option<Token> {
use self::Token::*;
Some(match c {
'=' => Equal,
'<' => LessThan,
'>' => GreaterThan,
'+' => Plus,
'-' => Minus,
'(' => LeftParen,
')' => RightParen,
'[' => LeftBracket,
']' => RightBracket,
'.' => Dot,
',' => Comma,
';' => Semicolon,
'&' => Ampersand,
'|' => Pipe,
'*' => Asterisk,
'/' => ForwardSlash,
'?' => PreparedStatementPlaceholder,
_ => return None
})
}
fn word_to_token(word: String) -> Token {
use self::Token::*;
// Make all letters lowercase for comparison
let word_cmp: String = word.chars().flat_map( |c| c.to_lowercase() ).collect();
match word_cmp.as_ref() {
"select" => Select,
"from" => From,
"where" => Where,
"group" => Group,
"having" => Having,
"by" => By,
"limit" => Limit,
"distinct" => Distinct,
"order" => Order,
"asc" => Asc,
"desc" => Desc,
"as" => As,
"join" => Join,
"inner" => Inner,
"outer" => Outer,
"left" => Left,
"right" => Right,
"on" => On,
"insert" => Insert,
"into" => Into,
"values" => Values,
"update" => Update,
"delete" => Delete,
"create" => Create,
"table" => Table,
"index" => Index,
"constraint" => Constraint,
"primary" => Primary,
"key" => Key,
"unique" => Unique,
"references" => References,
"and" => And,
"or" => Or,
"between" => Between,
"in" => In,
"is" => Is,
"not" => Not,
"null" => Null,
"explain" => Explain,
_ => Ident(word)
}
}
enum LexerState {
NoState,
Word,
Backtick,
Apostrophe { escaping: bool },
Number { decimal: bool },
/// Disambiguate an operator sequence.
OperatorDisambiguate { first: char },
LineComment,
BlockComment { was_prev_char_asterisk: bool }
}
pub struct Lexer {
pub tokens: Vec<Token>,
state: LexerState,
string_buffer: String
}
impl Lexer {
pub fn new() -> Lexer {
Lexer {
tokens: Vec::new(),
state: LexerState::NoState,
string_buffer: String::new()
}
}
pub fn is_no_state(&self) -> bool {
match self.state {
LexerState::NoState => true,
_ => false
}
}
fn no_state(&mut self, c: char) -> Result<LexerState, char> {
match c {
'a'...'z' | 'A'...'Z' | '_' => {
self.string_buffer.push(c);
Ok(LexerState::Word)
},
'`' => {
Ok(LexerState::Backtick)
}
'\'' => {
// string literal
Ok(LexerState::Apostrophe { escaping: false })
},
'0'...'9' => {
self.string_buffer.push(c);
Ok(LexerState::Number { decimal: false })
},
' ' | '\t' | '\n' | '\r' => {
// whitespace
Ok(LexerState::NoState)
},
c => {
use self::Token::*;
match character_to_token(c) {
Some(LessThan) | Some(GreaterThan) | Some(Minus) | Some(Pipe) | Some(ForwardSlash) => {
Ok(LexerState::OperatorDisambiguate { first: c })
},
Some(token) => {
self.tokens.push(token);
Ok(LexerState::NoState)
},
None => {
// unknown character
Err(c)
}
}
}
}
}
fn move_string_buffer(&mut self) -> String {
use std::mem;
mem::replace(&mut self.string_buffer, String::new())
}
pub fn feed_character(&mut self, c: Option<char>) {
self.state = match self.state {
LexerState::NoState => {
match c {
Some(c) => self.no_state(c).unwrap(),
None => LexerState::NoState
}
},
LexerState::Word => {
match c {
Some(c) => match c {
'a'...'z' | 'A'...'Z' | '_' | '0'...'9' => {
self.string_buffer.push(c);
LexerState::Word
}
c => {
let buffer = self.move_string_buffer();
self.tokens.push(word_to_token(buffer));
self.no_state(c).unwrap()
}
},
None => {
let buffer = self.move_string_buffer();
self.tokens.push(word_to_token(buffer));
LexerState::NoState
}
}
},
LexerState::Backtick => {
match c {
Some('`') => {
let buffer = self.move_string_buffer();
self.tokens.push(Token::Ident(buffer));
LexerState::NoState
},
Some(c) => {
self.string_buffer.push(c);
LexerState::Backtick
},
None => {
// error: backtick did not finish
unimplemented!()
}
}
},
LexerState::Apostrophe { escaping } => {
if let Some(c) = c {
match (escaping, c) {
(false, '\'') => {
// unescaped apostrophe
let buffer = self.move_string_buffer();
self.tokens.push(Token::StringLiteral(buffer));
LexerState::NoState
},
(false, '\\') => {
// unescaped backslash
LexerState::Apostrophe { escaping: true }
},
(true, _) | _ => {
self.string_buffer.push(c);
LexerState::Apostrophe { escaping: false }
}
}
} else {
// error: apostrophe did not finish
unimplemented!()
}
},
LexerState::Number { decimal } => {
if let Some(c) = c {
match c {
'0'...'9' => {
self.string_buffer.push(c);
LexerState::Number { decimal: decimal }
},
'.' if !decimal => {
// Add a decimal point. None has been added yet.
self.string_buffer.push(c);
LexerState::Number { decimal: true }
},
c => {
let buffer = self.move_string_buffer();
self.tokens.push(Token::Number(buffer));
self.no_state(c).unwrap()
}
}
} else {
let buffer = self.move_string_buffer();
self.tokens.push(Token::Number(buffer));
LexerState::NoState
}
},
LexerState::OperatorDisambiguate { first } => {
use self::Token::*;
if let Some(c) = c {
match (first, c) {
('<', '>') => {
self.tokens.push(NotEqual);
LexerState::NoState
},
('<', '=') => {
self.tokens.push(LessThanOrEqual);
LexerState::NoState
},
('>', '=') => {
self.tokens.push(GreaterThanOrEqual);
LexerState::NoState
},
('|', '|') => {
self.tokens.push(DoublePipe);
LexerState::NoState
},
('-', '-') => {
LexerState::LineComment
},
('/', '*') => {
LexerState::BlockComment { was_prev_char_asterisk: false }
},
_ => {
self.tokens.push(character_to_token(first).unwrap());
self.no_state(c).unwrap()
}
}
} else {
self.tokens.push(character_to_token(first).unwrap());
LexerState::NoState
}
},
LexerState::LineComment => {
match c {
Some('\n') => LexerState::NoState,
_ => LexerState::LineComment
}
},
LexerState::BlockComment { was_prev_char_asterisk } => {
if was_prev_char_asterisk && c == Some('/') {
LexerState::NoState
} else {
LexerState::BlockComment { was_prev_char_asterisk: c == Some('*') }
}
}
};
}
pub fn feed_characters<I>(&mut self, iter: I)
where I: Iterator<Item=char>
{
for c in iter {
self.feed_character(Some(c));
}
}
}
pub fn parse(sql: &str) -> Vec<Token> {
let mut lexer = Lexer::new();
lexer.feed_characters(sql.chars());
lexer.feed_character(None);
lexer.tokens
}
#[cfg(test)]
mod test {
use super::parse;
fn id(value: &str) -> super::Token {
super::Token::Ident(value.to_string())
}
fn number(value: &str) -> super::Token {
super::Token::Number(value.to_string())
}
#[test]
fn test_sql_lexer_dontconfuseidentswithkeywords() {
use super::Token::*;
// Not: AS, Ident("df")
assert_eq!(parse("asdf"), vec![Ident("asdf".to_string())]);
}
#[test]
fn test_sql_lexer_escape() {
use super::Token::*;
// Escaped apostrophe
assert_eq!(parse(r"'\''"), vec![StringLiteral("'".to_string())]);
}
#[test]
fn test_sql_lexer_numbers() {
use super::Token::*;
assert_eq!(parse("12345"), vec![number("12345")]);
assert_eq!(parse("0.25"), vec![number("0.25")]);
assert_eq!(parse("0.25 + -0.25"), vec![number("0.25"), Plus, Minus, number("0.25")]);
assert_eq!(parse("-0.25 + 0.25"), vec![Minus, number("0.25"), Plus, number("0.25")]);
assert_eq!(parse("- 0.25 - -0.25"), vec![Minus, number("0.25"), Minus, Minus, number("0.25")]);
assert_eq!(parse("- 0.25 --0.25"), vec![Minus, number("0.25")]);
assert_eq!(parse("0.25 -0.25"), vec![number("0.25"), Minus, number("0.25")]);
}
#[test]
fn test_sql_lexer_query1() {
use super::Token::*;
assert_eq!(parse(" SeLECT a, b as alias1 , c alias2, d ` alias three ` fRoM table1 WHERE a='Hello World'; "),
vec![
Select, id("a"), Comma, id("b"), As, id("alias1"), Comma,
id("c"), id("alias2"), Comma, id("d"), id(" alias three "),
From, id("table1"),
Where, id("a"), Equal, StringLiteral("Hello World".to_string()), Semicolon
]
);
}
#[test]
fn test_sql_lexer_query2() {
use super::Token::*;
let query = r"
-- Get employee count from each department
SELECT d.id departmentId, count(e.id) employeeCount
FROM department d
LEFT JOIN employee e ON e.departmentId = d.id
GROUP BY departmentId;
";
assert_eq!(parse(query), vec![
Select, id("d"), Dot, id("id"), id("departmentId"), Comma, id("count"), LeftParen, id("e"), Dot, id("id"), RightParen, id("employeeCount"),
From, id("department"), id("d"),
Left, Join, id("employee"), id("e"), On, id("e"), Dot, id("departmentId"), Equal, id("d"), Dot, id("id"),
Group, By, id("departmentId"), Semicolon
]);
}
#[test]
fn test_sql_lexer_operators() {
use super::Token::*;
assert_eq!(parse("> = >=< =><"),
vec![
GreaterThan, Equal, GreaterThanOrEqual, LessThan, Equal, GreaterThan, LessThan
]
);
assert_eq!(parse(" ><>> >< >"),
vec![
GreaterThan, NotEqual, GreaterThan, GreaterThan, LessThan, GreaterThan
]
);
}
#[test]
fn test_sql_lexer_blockcomment() {
use super::Token::*;
assert_eq!(parse("hello/*/a/**/,/*there, */world"), vec![
id("hello"), Comma, id("world")
]);
assert_eq!(parse("/ */"), vec![ForwardSlash, Asterisk, ForwardSlash]);
assert_eq!(parse("/**/"), vec![]);
assert_eq!(parse("a/* test\ntest** /\nb*/c"), vec![id("a"), id("c")]);
}
}
|
use std::{borrow::Cow, collections::HashMap};
use crate::{Program, TacFunc};
use anymap::AnyMap;
pub mod sanity_checker;
/// Represents a single pass inside the compilation pipeline.
///
/// A `Pass` should be constructible from an [`OptimizeEnvironment`], which
/// supplies external data needed for this pass.
#[allow(unused_variables)]
pub trait Pass {
/// Returns the name of this pass.
fn name(&self) -> Cow<str>;
/// Whether this pass edits the program. This method should correctly
/// represent the function of [`optimize_program`], since mutable references
/// are given anyway.
fn edits_program(&self) -> bool;
/// Optimize at program level.
fn optimize_program(&mut self, env: &mut OptimizeEnvironment, program: &mut Program);
}
pub trait FunctionOptimizer {
/// Returns the name of this pass.
fn name(&self) -> Cow<str>;
/// Whether this pass edits the program. This method should correctly
/// represent the function of [`optimize_program`], since mutable references
/// are given anyway.
fn edits_program(&self) -> bool;
/// Reset this instance for optimizing another function.
fn reset(&mut self) {}
/// Optimize a single function.
fn optimize_func(&mut self, env: &mut OptimizeEnvironment, func: &mut TacFunc);
/// Perform initialization before any functions are processed.
fn do_initialization(&mut self, _env: &mut OptimizeEnvironment, _prog: &Program) {}
/// Perform finalization after all functions are processed.
fn do_finalization(&mut self, _env: &mut OptimizeEnvironment, _prog: &Program) {}
/// Transform this optimizer into a pass. You should not overwrite this method
/// in most cases.
fn make_pass(self) -> FunctionOptimizerPass<Self>
where
Self: Sized,
{
FunctionOptimizerPass(self)
}
}
/// A simple wrapper over a [`FunctionOptimizer`] to create a pass.
pub struct FunctionOptimizerPass<F: ?Sized>(pub F);
impl<F> Pass for FunctionOptimizerPass<F>
where
F: FunctionOptimizer,
{
fn name(&self) -> Cow<str> {
self.0.name()
}
fn edits_program(&self) -> bool {
self.0.edits_program()
}
fn optimize_program(&mut self, env: &mut OptimizeEnvironment, program: &mut Program) {
self.0.do_initialization(env, program);
for func in program.functions.values_mut() {
self.0.reset();
self.0.optimize_func(env, func);
}
self.0.do_finalization(env, program);
}
}
/// The environment of an optimization pass. All data inside this struct will be
/// preserved between passes, allowing passes to retain states here.
#[non_exhaustive]
pub struct OptimizeEnvironment {
/// External data that passes could save, read or modify.
pub data: AnyMap,
}
pub struct Pipeline {
env: OptimizeEnvironment,
passes: HashMap<String, Box<dyn Pass>>,
}
impl Default for Pipeline {
fn default() -> Self {
Self::new()
}
}
impl Pipeline {
pub fn new() -> Pipeline {
Pipeline {
env: OptimizeEnvironment {
data: AnyMap::new(),
},
passes: HashMap::new(),
}
}
pub fn add_pass<P: Pass + 'static>(&mut self, pass: P) {
self.passes.insert(pass.name().into_owned(), Box::new(pass));
}
pub fn add_func_optimizer<F: FunctionOptimizer + 'static>(&mut self, pass: F) {
self.passes.insert(
pass.name().into_owned(),
Box::new(FunctionOptimizerPass(pass)),
);
}
pub fn add_pass_boxed(&mut self, pass: Box<dyn Pass>) {
self.passes.insert(pass.name().into_owned(), pass);
}
pub fn list_passes(&self) -> impl Iterator<Item = &str> {
self.passes.keys().map(|k| k.as_str())
}
pub fn run_pass(&mut self, program: &mut Program, pass: impl AsRef<str>) -> bool {
let pass = self.passes.get_mut(pass.as_ref());
if let Some(pass) = pass {
pass.optimize_program(&mut self.env, program);
true
} else {
false
}
}
}
|
use std::process::Command;
use std::process::Stdio;
fn main() {
//let trsh_id = get_random_string("32");
//let trsh_key = get_random_string("32");
//let trsh_iv = get_random_string("8");
let trsh_id = "ohpie2naiwoo1lah6aeteexi5beiRas7";
let trsh_key = "Fahm9Oruet8zahcoFahm9Oruet8zahco";
let trsh_iv = "biTh0eoY";
println!("cargo:rustc-env=TRSH_ID={}", trsh_id);
println!("cargo:rustc-env=TRSH_KEY={}", trsh_key);
println!("cargo:rustc-env=TRSH_IV={}", trsh_iv);
}
fn get_random_string(length: &str) -> String {
let mut cat_child = Command::new("head")
.args(&["-c", "1024", "/dev/urandom"])
.stdout(Stdio::piped())
.spawn()
.unwrap();
cat_child.wait().unwrap();
if let Some(cat_output) = cat_child.stdout.take() {
let mut tr_child = Command::new("tr")
.arg("-dc")
.arg("[:alnum:]")
.stdin(cat_output)
.stdout(Stdio::piped())
.spawn()
.unwrap();
if let Some(tr_output) = tr_child.stdout.take() {
let head_output_child = Command::new("head")
.args(&["-c", length])
.stdin(tr_output)
.stdout(Stdio::piped())
.spawn()
.unwrap();
let head_stdout = head_output_child.wait_with_output().unwrap();
return String::from_utf8(head_stdout.stdout).unwrap();
}
}
return "".to_string();
}
|
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - Control register"]
pub cr: CR,
#[doc = "0x04 - Configuration register"]
pub cfr: CFR,
#[doc = "0x08 - Status register"]
pub sr: SR,
}
#[doc = "CR (rw) register accessor: Control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cr::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cr`]
module"]
pub type CR = crate::Reg<cr::CR_SPEC>;
#[doc = "Control register"]
pub mod cr;
#[doc = "CFR (rw) register accessor: Configuration register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cfr::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 [`cfr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cfr`]
module"]
pub type CFR = crate::Reg<cfr::CFR_SPEC>;
#[doc = "Configuration register"]
pub mod cfr;
#[doc = "SR (rw) register accessor: Status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`sr::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 [`sr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`sr`]
module"]
pub type SR = crate::Reg<sr::SR_SPEC>;
#[doc = "Status register"]
pub mod sr;
|
use std::collections::hash_map::Entry as HmEntry;
use std::collections::{btree_map::Entry, BTreeMap, HashMap};
use std::path::{Path, PathBuf};
use failure::{Error, Fail};
use itertools::Itertools;
use morton::interleave_morton;
use rocksdb::{Options, DB};
use smallvec::{smallvec, SmallVec};
use crate::gridstore::common::*;
use crate::gridstore::gridstore_format;
type BuilderEntry = HashMap<u8, HashMap<u32, SmallVec<[u32; 4]>>>;
pub struct GridStoreBuilder {
path: PathBuf,
data: BTreeMap<GridKey, BuilderEntry>,
bin_boundaries: Vec<u32>,
}
/// Extends a BuildEntry with the given values.
fn extend_entries(builder_entry: &mut BuilderEntry, values: Vec<GridEntry>) -> () {
for (rs, rs_values) in somewhat_eager_groupby(values.into_iter(), |value| {
(relev_float_to_int(value.relev) << 4) | value.score
}) {
let rs_entry =
builder_entry.entry(rs).or_insert_with(|| HashMap::with_capacity(rs_values.len()));
for (zcoord, zc_values) in
&rs_values.into_iter().group_by(|value| interleave_morton(value.x, value.y))
{
let id_phrases =
zc_values.map(|value| (value.id << 8) | (value.source_phrase_hash as u32));
match rs_entry.entry(zcoord) {
HmEntry::Vacant(e) => {
e.insert(id_phrases.collect());
}
HmEntry::Occupied(mut e) => {
e.get_mut().extend(id_phrases);
}
}
}
}
}
fn copy_entries(source_entry: &BuilderEntry, destination_entry: &mut BuilderEntry) -> () {
for (rs, values) in source_entry.iter() {
let rs_entry = destination_entry.entry(*rs).or_insert_with(|| HashMap::new());
for (zcoord, values) in values.iter() {
let zcoord_entry = rs_entry.entry(*zcoord).or_insert_with(|| SmallVec::new());
zcoord_entry.extend(values.iter().cloned());
}
}
}
fn get_encoded_value(value: BuilderEntry) -> Result<Vec<u8>, Error> {
let mut builder = gridstore_format::Writer::new();
let mut items: Vec<(_, _)> = value.into_iter().collect();
items.sort_by(|(relevance_score_a, _), (relevance_score_b, _)| {
relevance_score_b.cmp(&relevance_score_a)
});
let mut relevance_scores: Vec<_> = Vec::with_capacity(items.len());
let mut id_lists: HashMap<_, gridstore_format::FixedVecOffset<u32>> = HashMap::new();
for (relevance_score, coord_group) in items.into_iter() {
let mut inner_items: Vec<(_, _)> = coord_group.into_iter().collect();
inner_items.sort_by(|(coord_a, _), (coord_b, _)| coord_b.cmp(&coord_a));
let mut coords: Vec<_> = Vec::with_capacity(inner_items.len());
for (coord, mut ids) in inner_items.into_iter() {
// reverse sort
ids.sort_by(|id_a, id_b| id_b.cmp(id_a));
ids.dedup();
let encoded_ids =
id_lists.entry(ids.clone()).or_insert_with(|| builder.write_fixed_vec(&ids));
let encoded_coord = gridstore_format::Coord { coord, ids: encoded_ids.clone() };
coords.push(encoded_coord);
}
let encoded_coords = builder.write_uniform_vec(&coords);
let encoded_relevance_score =
gridstore_format::RelevScore { relev_score: relevance_score, coords: encoded_coords };
relevance_scores.push(encoded_relevance_score);
}
let encoded_relevance_scores = builder.write_var_vec(&relevance_scores);
let record = gridstore_format::PhraseRecord { relev_scores: encoded_relevance_scores };
builder.write_fixed_scalar(record);
Ok(builder.finish())
}
impl GridStoreBuilder {
/// Makes a new GridStoreBuilder with a particular filename.
pub fn new<P: AsRef<Path>>(path: P) -> Result<Self, Error> {
Ok(GridStoreBuilder {
path: path.as_ref().to_owned(),
data: BTreeMap::new(),
bin_boundaries: Vec::new(),
})
}
/// Inserts a new GridStore entry with the given values.
pub fn insert(&mut self, key: &GridKey, values: Vec<GridEntry>) -> Result<(), Error> {
let mut to_insert = BuilderEntry::new();
extend_entries(&mut to_insert, values);
self.data.insert(key.to_owned(), to_insert);
Ok(())
}
/// Appends a values to and existing GridStore entry.
pub fn append(&mut self, key: &GridKey, values: Vec<GridEntry>) -> Result<(), Error> {
let mut to_append = self.data.entry(key.to_owned()).or_insert_with(|| BuilderEntry::new());
extend_entries(&mut to_append, values);
Ok(())
}
pub fn compact_append(
&mut self,
key: &GridKey,
relev: f64,
score: u8,
id: u32,
source_phrase_hash: u8,
coords: &[(u16, u16)],
) {
let to_append =
self.data.entry(key.to_owned()).or_insert_with(|| BuilderEntry::with_capacity(1));
let relev_score = (relev_float_to_int(relev) << 4) | score;
let id_hash = smallvec![(id << 8) | (source_phrase_hash as u32)];
let relevance_score_entry =
to_append.entry(relev_score).or_insert_with(|| HashMap::with_capacity(coords.len()));
for pair in coords {
let zcoord = interleave_morton(pair.0, pair.1);
match relevance_score_entry.entry(zcoord) {
HmEntry::Vacant(e) => {
e.insert(id_hash.clone());
}
HmEntry::Occupied(mut e) => {
e.get_mut().extend_from_slice(&id_hash);
}
}
}
}
/// In situations under which data has been inserted using temporary phrase IDs, renumber
/// the data in the index to use final phrase IDs, given a temporary-to-final-ID mapping
pub fn renumber(&mut self, tmp_phrase_ids_to_ids: &[u32]) -> Result<(), Error> {
let mut old_data: BTreeMap<GridKey, BuilderEntry> = BTreeMap::new();
std::mem::swap(&mut old_data, &mut self.data);
for (key, value) in old_data.into_iter() {
let new_phrase_id = tmp_phrase_ids_to_ids
.get(key.phrase_id as usize)
.ok_or_else(|| BuildError::OutOfBoundsRenumberEntry { tmp_id: key.phrase_id })?;
let new_key = GridKey { phrase_id: *new_phrase_id, ..key };
match self.data.entry(new_key) {
Entry::Vacant(v) => {
v.insert(value);
}
Entry::Occupied(_) => {
return Err(Error::from(BuildError::DuplicateRenumberEntry {
target_id: *new_phrase_id,
}))
}
};
}
Ok(())
}
pub fn load_bin_boundaries(&mut self, bin_boundaries: Vec<u32>) -> Result<(), Error> {
self.bin_boundaries = bin_boundaries;
Ok(())
}
/// Writes data to disk.
pub fn finish(self) -> Result<(), Error> {
let mut opts = Options::default();
opts.set_disable_auto_compactions(true);
opts.create_if_missing(true);
let db = DB::open(&opts, &self.path)?;
let mut db_key: Vec<u8> = Vec::with_capacity(MAX_KEY_LENGTH);
let mut bin_seq = self.bin_boundaries.iter().cloned().peekable();
let mut current_bin = None;
let mut next_boundary = 0u32;
let grouped = somewhat_eager_groupby(self.data.into_iter(), |(key, _value)| {
while key.phrase_id >= next_boundary {
current_bin = bin_seq.next();
next_boundary = *(bin_seq.peek().unwrap_or(&std::u32::MAX));
}
current_bin
});
for (group_id, group_value) in grouped {
let mut lang_set_map: HashMap<u128, BuilderEntry> = HashMap::new();
for (grid_key, value) in group_value.into_iter() {
// figure out the key
db_key.clear();
grid_key.write_to(TypeMarker::SinglePhrase, &mut db_key)?;
let mut grouped_entry =
lang_set_map.entry(grid_key.lang_set).or_insert_with(|| BuilderEntry::new());
copy_entries(&value, &mut grouped_entry);
// figure out the value
let db_data = get_encoded_value(value)?;
db.put(&db_key, &db_data)?;
}
if let Some(group_id) = group_id {
for (lang_set, builder_entry) in lang_set_map.into_iter() {
db_key.clear();
let group_key = GridKey { phrase_id: group_id, lang_set };
group_key.write_to(TypeMarker::PrefixBin, &mut db_key)?;
let grouped_db_data = get_encoded_value(builder_entry)?;
db.put(&db_key, &grouped_db_data)?;
}
}
}
// bake the prefix boundaries
let mut encoded_boundaries: Vec<u8> = Vec::with_capacity(self.bin_boundaries.len() * 4);
for boundary in self.bin_boundaries {
encoded_boundaries.extend_from_slice(&boundary.to_le_bytes());
}
db.put("~BOUNDS", &encoded_boundaries)?;
db.compact_range(None::<&[u8]>, None::<&[u8]>);
drop(db);
Ok(())
}
}
#[cfg(test)]
use tempfile;
#[test]
fn extend_entry_test() {
let mut entry = BuilderEntry::new();
extend_entries(
&mut entry,
vec![GridEntry { id: 1, x: 1, y: 1, relev: 1., score: 7, source_phrase_hash: 2 }],
);
// relev 3 (0011) with score 7 (0111) -> 55
let grids = entry.get(&55);
assert_ne!(grids, None, "Retrieve grids based on relev and score");
// x:1, y:1 -> z-order 3
let vals = grids.unwrap().get(&3);
assert_ne!(vals, None, "Retrieve entries based on z-order");
// id 1 (1 << 8 == 256) with phrase 2 => 258
assert_eq!(vals.unwrap()[0], 258, "TODO");
}
#[test]
fn insert_test() {
let directory: tempfile::TempDir = tempfile::tempdir().unwrap();
let mut builder = GridStoreBuilder::new(directory.path()).unwrap();
let key = GridKey { phrase_id: 1, lang_set: 1 };
builder
.insert(
&key,
vec![
GridEntry { id: 2, x: 2, y: 2, relev: 0.8, score: 3, source_phrase_hash: 0 },
GridEntry { id: 3, x: 3, y: 3, relev: 1., score: 1, source_phrase_hash: 1 },
GridEntry { id: 1, x: 1, y: 1, relev: 1., score: 7, source_phrase_hash: 2 },
],
)
.expect("Unable to insert record");
assert_ne!(builder.path.to_str(), None);
assert_eq!(builder.data.len(), 1, "Gridstore has one entry");
let entry = builder.data.get(&key);
assert_ne!(entry, None);
assert_eq!(entry.unwrap().len(), 3, "Entry contains three grids");
builder.finish().unwrap();
}
#[test]
fn append_test() {
let directory: tempfile::TempDir = tempfile::tempdir().unwrap();
let mut builder = GridStoreBuilder::new(directory.path()).unwrap();
let key = GridKey { phrase_id: 1, lang_set: 1 };
builder
.insert(
&key,
vec![GridEntry { id: 2, x: 2, y: 2, relev: 0.8, score: 3, source_phrase_hash: 0 }],
)
.expect("Unable to insert record");
builder
.append(
&key,
vec![
GridEntry { id: 3, x: 3, y: 3, relev: 1., score: 1, source_phrase_hash: 1 },
GridEntry { id: 1, x: 1, y: 1, relev: 1., score: 7, source_phrase_hash: 2 },
],
)
.expect("Unable to append grids");
assert_ne!(builder.path.to_str(), None);
assert_eq!(builder.data.len(), 1, "Gridstore has one entry");
let entry = builder.data.get(&key);
assert_ne!(entry, None);
assert_eq!(entry.unwrap().len(), 3, "Entry contains three grids");
builder.finish().unwrap();
}
#[test]
fn compact_append_test() {
let directory: tempfile::TempDir = tempfile::tempdir().unwrap();
let mut builder = GridStoreBuilder::new(directory.path()).unwrap();
let key = GridKey { phrase_id: 1, lang_set: 1 };
builder
.insert(
&key,
vec![GridEntry { id: 2, x: 2, y: 2, relev: 1., score: 1, source_phrase_hash: 0 }],
)
.expect("Unable to insert record");
builder.compact_append(&key, 1., 1, 2, 0, &[(0, 0)]);
let entry = builder.data.get(&key);
assert_ne!(entry, None);
assert_eq!(entry.unwrap().len(), 1);
builder.finish().unwrap();
}
#[derive(Debug, Fail)]
enum BuildError {
#[fail(display = "duplicate rename entry: {}", target_id)]
DuplicateRenumberEntry { target_id: u32 },
#[fail(display = "out of bounds: {}", tmp_id)]
OutOfBoundsRenumberEntry { tmp_id: u32 },
}
|
#[doc = "Register `FMC_CSQISR` reader"]
pub type R = crate::R<FMC_CSQISR_SPEC>;
#[doc = "Register `FMC_CSQISR` writer"]
pub type W = crate::W<FMC_CSQISR_SPEC>;
#[doc = "Field `TCF` reader - TCF"]
pub type TCF_R = crate::BitReader;
#[doc = "Field `TCF` writer - TCF"]
pub type TCF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `SCF` reader - SCF"]
pub type SCF_R = crate::BitReader;
#[doc = "Field `SCF` writer - SCF"]
pub type SCF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `SEF` reader - SEF"]
pub type SEF_R = crate::BitReader;
#[doc = "Field `SEF` writer - SEF"]
pub type SEF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `SUEF` reader - SUEF"]
pub type SUEF_R = crate::BitReader;
#[doc = "Field `SUEF` writer - SUEF"]
pub type SUEF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CMDTCF` reader - CMDTCF"]
pub type CMDTCF_R = crate::BitReader;
#[doc = "Field `CMDTCF` writer - CMDTCF"]
pub type CMDTCF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bit 0 - TCF"]
#[inline(always)]
pub fn tcf(&self) -> TCF_R {
TCF_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - SCF"]
#[inline(always)]
pub fn scf(&self) -> SCF_R {
SCF_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 2 - SEF"]
#[inline(always)]
pub fn sef(&self) -> SEF_R {
SEF_R::new(((self.bits >> 2) & 1) != 0)
}
#[doc = "Bit 3 - SUEF"]
#[inline(always)]
pub fn suef(&self) -> SUEF_R {
SUEF_R::new(((self.bits >> 3) & 1) != 0)
}
#[doc = "Bit 4 - CMDTCF"]
#[inline(always)]
pub fn cmdtcf(&self) -> CMDTCF_R {
CMDTCF_R::new(((self.bits >> 4) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - TCF"]
#[inline(always)]
#[must_use]
pub fn tcf(&mut self) -> TCF_W<FMC_CSQISR_SPEC, 0> {
TCF_W::new(self)
}
#[doc = "Bit 1 - SCF"]
#[inline(always)]
#[must_use]
pub fn scf(&mut self) -> SCF_W<FMC_CSQISR_SPEC, 1> {
SCF_W::new(self)
}
#[doc = "Bit 2 - SEF"]
#[inline(always)]
#[must_use]
pub fn sef(&mut self) -> SEF_W<FMC_CSQISR_SPEC, 2> {
SEF_W::new(self)
}
#[doc = "Bit 3 - SUEF"]
#[inline(always)]
#[must_use]
pub fn suef(&mut self) -> SUEF_W<FMC_CSQISR_SPEC, 3> {
SUEF_W::new(self)
}
#[doc = "Bit 4 - CMDTCF"]
#[inline(always)]
#[must_use]
pub fn cmdtcf(&mut self) -> CMDTCF_W<FMC_CSQISR_SPEC, 4> {
CMDTCF_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "FMC NAND Command Sequencer Interrupt Status Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`fmc_csqisr::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`fmc_csqisr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct FMC_CSQISR_SPEC;
impl crate::RegisterSpec for FMC_CSQISR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`fmc_csqisr::R`](R) reader structure"]
impl crate::Readable for FMC_CSQISR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`fmc_csqisr::W`](W) writer structure"]
impl crate::Writable for FMC_CSQISR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets FMC_CSQISR to value 0"]
impl crate::Resettable for FMC_CSQISR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use shorthand::ShortHand;
use std::vec::Vec;
#[derive(ShortHand, Default)]
#[shorthand(enable(collection_magic))]
struct Example {
vec: Vec<&'static str>,
irrelevant_field: usize,
}
fn main() { let _: &mut Example = Example::default().push_vec("value"); }
|
#[doc = "Register `MEMRM` reader"]
pub type R = crate::R<MEMRM_SPEC>;
#[doc = "Register `MEMRM` writer"]
pub type W = crate::W<MEMRM_SPEC>;
#[doc = "Field `MEM_MODE` reader - Memory mapping selection"]
pub type MEM_MODE_R = crate::FieldReader;
#[doc = "Field `MEM_MODE` writer - Memory mapping selection"]
pub type MEM_MODE_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 3, O>;
#[doc = "Field `FB_MODE` reader - Flash bank mode selection"]
pub type FB_MODE_R = crate::BitReader;
#[doc = "Field `FB_MODE` writer - Flash bank mode selection"]
pub type FB_MODE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `SWP_FMC` reader - FMC memory mapping swap"]
pub type SWP_FMC_R = crate::FieldReader;
#[doc = "Field `SWP_FMC` writer - FMC memory mapping swap"]
pub type SWP_FMC_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>;
impl R {
#[doc = "Bits 0:2 - Memory mapping selection"]
#[inline(always)]
pub fn mem_mode(&self) -> MEM_MODE_R {
MEM_MODE_R::new((self.bits & 7) as u8)
}
#[doc = "Bit 8 - Flash bank mode selection"]
#[inline(always)]
pub fn fb_mode(&self) -> FB_MODE_R {
FB_MODE_R::new(((self.bits >> 8) & 1) != 0)
}
#[doc = "Bits 10:11 - FMC memory mapping swap"]
#[inline(always)]
pub fn swp_fmc(&self) -> SWP_FMC_R {
SWP_FMC_R::new(((self.bits >> 10) & 3) as u8)
}
}
impl W {
#[doc = "Bits 0:2 - Memory mapping selection"]
#[inline(always)]
#[must_use]
pub fn mem_mode(&mut self) -> MEM_MODE_W<MEMRM_SPEC, 0> {
MEM_MODE_W::new(self)
}
#[doc = "Bit 8 - Flash bank mode selection"]
#[inline(always)]
#[must_use]
pub fn fb_mode(&mut self) -> FB_MODE_W<MEMRM_SPEC, 8> {
FB_MODE_W::new(self)
}
#[doc = "Bits 10:11 - FMC memory mapping swap"]
#[inline(always)]
#[must_use]
pub fn swp_fmc(&mut self) -> SWP_FMC_W<MEMRM_SPEC, 10> {
SWP_FMC_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 = "memory remap register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`memrm::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 [`memrm::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct MEMRM_SPEC;
impl crate::RegisterSpec for MEMRM_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`memrm::R`](R) reader structure"]
impl crate::Readable for MEMRM_SPEC {}
#[doc = "`write(|w| ..)` method takes [`memrm::W`](W) writer structure"]
impl crate::Writable for MEMRM_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets MEMRM to value 0"]
impl crate::Resettable for MEMRM_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
//
extern crate rand;
pub mod vec3;
pub mod ray;
pub mod material;
pub mod hitable;
pub mod camera;
use std::io::Write;
use std::fs::File;
use std::path::Path;
use std::f32;
use vec3::*;
use ray::*;
use material::*;
use hitable::*;
use camera::*;
#[allow(dead_code)]
fn random_spheres(world: &mut HitableList, clear: Vec3, dist:f32) {
for a in -11 .. 11 {
for b in -11 .. 11 {
let choose_mat = rand();
let centre = Vec3::new(a as f32 + 0.9*rand(), 0.2, b as f32 + 0.9 * rand());
if (centre - clear).length() > dist {
if choose_mat < 0.7 {
// Diffuse
world.push(Box::new(Sphere::new(centre, 0.2,
Box::new(Lambertian::new(Vec3::new(rand()*rand(),
rand()*rand(),
rand()*rand()))))));
} else if choose_mat < 0.85 {
// Metal
world.push(Box::new(Sphere::new(centre, 0.2,
Box::new(Metal::new(Vec3::new(0.5*(1.0+rand()),
0.5*(1.0+rand()),
0.5*(1.0+rand())),
0.5*rand())))));
} else {
// Glass
world.push(Box::new(Sphere::new(centre, 0.2,Box::new(Dielectric::new(1.5)))));
}
}
}
}
}
#[allow(dead_code)]
fn random_scene(aspect: f32) -> (HitableList, Camera) {
let mut h = HitableList::new(Vec::new());
h.push(Box::new(Sphere::new(Vec3::new(0.0, -1000.0, 0.0), 1000.0, Box::new(Lambertian::new(Vec3::new(0.5, 0.5, 0.5))))));
random_spheres(&mut h, Vec3::new(4.0, 0.2, 0.0), 0.9);
h.push(Box::new(Sphere::new(Vec3::new(0.0,1.0,0.0), 1.0, Box::new(Dielectric::new(1.5)))));
h.push(Box::new(Sphere::new(Vec3::new(-4.0,1.0,0.0), 1.0, Box::new(Lambertian::new(Vec3::new(0.4, 0.2, 0.1))))));
h.push(Box::new(Sphere::new(Vec3::new(4.0,1.0,0.0), 1.0, Box::new(Metal::new(Vec3::new(0.7, 0.6, 0.5), 0.0)))));
let lookfrom = Vec3::new(14.0, 2.0, 3.0);
let lookat = Vec3::new(0.0, 0.0, 0.0);
let dist_to_focus = (lookfrom - lookat).length();
let aperture = 0.05;
let cam = Camera::new(lookfrom, lookat, Vec3::new(0.0,1.0,0.0), 20.0, aspect, aperture, dist_to_focus);
(h,cam)
}
#[allow(dead_code)]
fn test_scene(aspect: f32) -> (HitableList, Camera) {
let h = HitableList::new(vec!(
Box::new(Sphere::new(Vec3::new(0.0, 0.0, -1.0), 0.5, Box::new(Lambertian::new(Vec3::new(0.1, 0.2, 0.5))))),
Box::new(Sphere::new(Vec3::new(0.0, -100.5, -1.0), 100.0, Box::new(Lambertian::new(Vec3::new(0.8, 0.8, 0.0))))),
Box::new(Sphere::new(Vec3::new(1.0, 0.0, -1.0), 0.5, Box::new(Metal::new(Vec3::new(0.8, 0.6, 0.2), 0.4)))),
Box::new(Sphere::new(Vec3::new(-1.0, 0.0, -1.0), 0.5, Box::new(Dielectric::new(1.5)))),
Box::new(Sphere::new(Vec3::new(-1.0, 0.0, -1.0), -0.45, Box::new(Dielectric::new(1.5))))
));
let lookfrom = Vec3::new(14.0, 2.0, 3.0);
let lookat = Vec3::new(0.0, 0.0, 0.0);
let dist_to_focus = (lookfrom - lookat).length();
let aperture = 0.2;
let cam = Camera::new(lookfrom, lookat, Vec3::new(0.0,1.0,0.0), 20.0, aspect, aperture, dist_to_focus);
(h,cam)
}
#[allow(dead_code)]
fn juggler_scene(aspect: f32) -> (HitableList, Camera) {
let mut h = HitableList::new(vec!(
// Ground
Box::new(Sphere::new(Vec3::new(0.0, -1000.0, 0.0), 1000.0, Box::new(Lambertian::new(Vec3::new(0.5, 0.8, 0.5))))),
// Juggler
Box::new(Sphere::new(Vec3::new(-0.225, 1.325, -0.525), 0.150, Box::new(Metal::new(Vec3::new(0.90, 0.90, 0.90), 0.0)))),
Box::new(Sphere::new(Vec3::new(-0.275, 1.475, 0.475), 0.150, Box::new(Metal::new(Vec3::new(0.90, 0.90, 0.90), 0.0)))),
Box::new(Sphere::new(Vec3::new(-0.100, 1.700, -0.300), 0.150, Box::new(Metal::new(Vec3::new(0.90, 0.90, 0.90), 0.0)))),
Box::new(Sphere::new(Vec3::new(0.000, 1.525, 0.000), 0.125, Box::new(Metal::new(Vec3::new(1.00, 0.70, 0.70), 0.6)))),
Box::new(Sphere::new(Vec3::new(0.005, 1.530, 0.000), 0.125, Box::new(Metal::new(Vec3::new(0.20, 0.10, 0.10), 0.6)))),
Box::new(Sphere::new(Vec3::new(-0.100, 1.525, 0.050), 0.037, Box::new(Metal::new(Vec3::new(0.10, 0.10, 1.00), 0.6)))),
Box::new(Sphere::new(Vec3::new(-0.100, 1.525, -0.050), 0.037, Box::new(Metal::new(Vec3::new(0.10, 0.10, 1.00), 0.6)))),
Box::new(Sphere::new(Vec3::new(0.000, 1.375, 0.000), 0.050, Box::new(Metal::new(Vec3::new(1.00, 0.70, 0.70), 0.6)))),
Box::new(Sphere::new(Vec3::new(0.000, 1.150, 0.000), 0.200, Box::new(Metal::new(Vec3::new(1.00, 0.10, 0.10), 0.6)))),
Box::new(Sphere::new(Vec3::new(0.000, 1.085, 0.000), 0.190, Box::new(Metal::new(Vec3::new(1.00, 0.10, 0.10), 0.6)))),
Box::new(Sphere::new(Vec3::new(0.000, 1.020, 0.000), 0.180, Box::new(Metal::new(Vec3::new(1.00, 0.10, 0.10), 0.6)))),
Box::new(Sphere::new(Vec3::new(0.000, 0.955, 0.000), 0.170, Box::new(Metal::new(Vec3::new(1.00, 0.10, 0.10), 0.6)))),
Box::new(Sphere::new(Vec3::new(0.000, 0.890, 0.000), 0.160, Box::new(Metal::new(Vec3::new(1.00, 0.10, 0.10), 0.6)))),
Box::new(Sphere::new(Vec3::new(0.000, 0.825, 0.000), 0.150, Box::new(Metal::new(Vec3::new(1.00, 0.10, 0.10), 0.6)))),
Box::new(Sphere::new(Vec3::new(0.000, 0.725, 0.150), 0.050, Box::new(Metal::new(Vec3::new(1.00, 0.70, 0.70), 0.6)))),
Box::new(Sphere::new(Vec3::new(-0.025, 0.671, 0.150), 0.050, Box::new(Metal::new(Vec3::new(1.00, 0.70, 0.70), 0.6)))),
Box::new(Sphere::new(Vec3::new(-0.050, 0.617, 0.150), 0.050, Box::new(Metal::new(Vec3::new(1.00, 0.70, 0.70), 0.6)))),
Box::new(Sphere::new(Vec3::new(-0.075, 0.562, 0.150), 0.050, Box::new(Metal::new(Vec3::new(1.00, 0.70, 0.70), 0.6)))),
Box::new(Sphere::new(Vec3::new(-0.100, 0.508, 0.150), 0.050, Box::new(Metal::new(Vec3::new(1.00, 0.70, 0.70), 0.6)))),
Box::new(Sphere::new(Vec3::new(-0.125, 0.454, 0.150), 0.050, Box::new(Metal::new(Vec3::new(1.00, 0.70, 0.70), 0.6)))),
Box::new(Sphere::new(Vec3::new(-0.150, 0.400, 0.150), 0.050, Box::new(Metal::new(Vec3::new(1.00, 0.70, 0.70), 0.6)))),
Box::new(Sphere::new(Vec3::new(-0.143, 0.343, 0.150), 0.046, Box::new(Metal::new(Vec3::new(1.00, 0.70, 0.70), 0.6)))),
Box::new(Sphere::new(Vec3::new(-0.136, 0.286, 0.150), 0.043, Box::new(Metal::new(Vec3::new(1.00, 0.70, 0.70), 0.6)))),
Box::new(Sphere::new(Vec3::new(-0.129, 0.229, 0.150), 0.039, Box::new(Metal::new(Vec3::new(1.00, 0.70, 0.70), 0.6)))),
Box::new(Sphere::new(Vec3::new(-0.121, 0.171, 0.150), 0.036, Box::new(Metal::new(Vec3::new(1.00, 0.70, 0.70), 0.6)))),
Box::new(Sphere::new(Vec3::new(-0.114, 0.114, 0.150), 0.032, Box::new(Metal::new(Vec3::new(1.00, 0.70, 0.70), 0.6)))),
Box::new(Sphere::new(Vec3::new(-0.107, 0.057, 0.150), 0.029, Box::new(Metal::new(Vec3::new(1.00, 0.70, 0.70), 0.6)))),
Box::new(Sphere::new(Vec3::new(-0.100, 0.000, 0.150), 0.025, Box::new(Metal::new(Vec3::new(1.00, 0.70, 0.70), 0.6)))),
Box::new(Sphere::new(Vec3::new(0.000, 0.725, -0.150), 0.050, Box::new(Metal::new(Vec3::new(1.00, 0.70, 0.70), 0.6)))),
Box::new(Sphere::new(Vec3::new(0.008, 0.671, -0.150), 0.050, Box::new(Metal::new(Vec3::new(1.00, 0.70, 0.70), 0.6)))),
Box::new(Sphere::new(Vec3::new(0.017, 0.617, -0.150), 0.050, Box::new(Metal::new(Vec3::new(1.00, 0.70, 0.70), 0.6)))),
Box::new(Sphere::new(Vec3::new(0.025, 0.562, -0.150), 0.050, Box::new(Metal::new(Vec3::new(1.00, 0.70, 0.70), 0.6)))),
Box::new(Sphere::new(Vec3::new(0.033, 0.508, -0.150), 0.050, Box::new(Metal::new(Vec3::new(1.00, 0.70, 0.70), 0.6)))),
Box::new(Sphere::new(Vec3::new(0.042, 0.454, -0.150), 0.050, Box::new(Metal::new(Vec3::new(1.00, 0.70, 0.70), 0.6)))),
Box::new(Sphere::new(Vec3::new(0.050, 0.400, -0.150), 0.050, Box::new(Metal::new(Vec3::new(1.00, 0.70, 0.70), 0.6)))),
Box::new(Sphere::new(Vec3::new(0.057, 0.343, -0.150), 0.046, Box::new(Metal::new(Vec3::new(1.00, 0.70, 0.70), 0.6)))),
Box::new(Sphere::new(Vec3::new(0.064, 0.286, -0.150), 0.043, Box::new(Metal::new(Vec3::new(1.00, 0.70, 0.70), 0.6)))),
Box::new(Sphere::new(Vec3::new(0.071, 0.229, -0.150), 0.039, Box::new(Metal::new(Vec3::new(1.00, 0.70, 0.70), 0.6)))),
Box::new(Sphere::new(Vec3::new(0.079, 0.171, -0.150), 0.036, Box::new(Metal::new(Vec3::new(1.00, 0.70, 0.70), 0.6)))),
Box::new(Sphere::new(Vec3::new(0.086, 0.114, -0.150), 0.032, Box::new(Metal::new(Vec3::new(1.00, 0.70, 0.70), 0.6)))),
Box::new(Sphere::new(Vec3::new(0.093, 0.057, -0.150), 0.029, Box::new(Metal::new(Vec3::new(1.00, 0.70, 0.70), 0.6)))),
Box::new(Sphere::new(Vec3::new(0.100, 0.000, -0.150), 0.025, Box::new(Metal::new(Vec3::new(1.00, 0.70, 0.70), 0.6)))),
Box::new(Sphere::new(Vec3::new(0.000, 1.275, -0.175), 0.050, Box::new(Metal::new(Vec3::new(1.00, 0.70, 0.70), 0.6)))),
Box::new(Sphere::new(Vec3::new(-0.008, 1.238, -0.196), 0.050, Box::new(Metal::new(Vec3::new(1.00, 0.70, 0.70), 0.6)))),
Box::new(Sphere::new(Vec3::new(-0.017, 1.200, -0.217), 0.050, Box::new(Metal::new(Vec3::new(1.00, 0.70, 0.70), 0.6)))),
Box::new(Sphere::new(Vec3::new(-0.025, 1.163, -0.237), 0.050, Box::new(Metal::new(Vec3::new(1.00, 0.70, 0.70), 0.6)))),
Box::new(Sphere::new(Vec3::new(-0.033, 1.125, -0.258), 0.050, Box::new(Metal::new(Vec3::new(1.00, 0.70, 0.70), 0.6)))),
Box::new(Sphere::new(Vec3::new(-0.042, 1.087, -0.279), 0.050, Box::new(Metal::new(Vec3::new(1.00, 0.70, 0.70), 0.6)))),
Box::new(Sphere::new(Vec3::new(-0.050, 1.050, -0.300), 0.050, Box::new(Metal::new(Vec3::new(1.00, 0.70, 0.70), 0.6)))),
Box::new(Sphere::new(Vec3::new(-0.082, 1.046, -0.329), 0.046, Box::new(Metal::new(Vec3::new(1.00, 0.70, 0.70), 0.6)))),
Box::new(Sphere::new(Vec3::new(-0.114, 1.043, -0.357), 0.043, Box::new(Metal::new(Vec3::new(1.00, 0.70, 0.70), 0.6)))),
Box::new(Sphere::new(Vec3::new(-0.146, 1.039, -0.386), 0.039, Box::new(Metal::new(Vec3::new(1.00, 0.70, 0.70), 0.6)))),
Box::new(Sphere::new(Vec3::new(-0.179, 1.036, -0.414), 0.036, Box::new(Metal::new(Vec3::new(1.00, 0.70, 0.70), 0.6)))),
Box::new(Sphere::new(Vec3::new(-0.211, 1.032, -0.443), 0.032, Box::new(Metal::new(Vec3::new(1.00, 0.70, 0.70), 0.6)))),
Box::new(Sphere::new(Vec3::new(-0.243, 1.029, -0.471), 0.029, Box::new(Metal::new(Vec3::new(1.00, 0.70, 0.70), 0.6)))),
Box::new(Sphere::new(Vec3::new(-0.275, 1.025, -0.500), 0.025, Box::new(Metal::new(Vec3::new(1.00, 0.70, 0.70), 0.6)))),
Box::new(Sphere::new(Vec3::new(0.000, 1.275, 0.175), 0.050, Box::new(Metal::new(Vec3::new(1.00, 0.70, 0.70), 0.6)))),
Box::new(Sphere::new(Vec3::new(-0.008, 1.238, 0.196), 0.050, Box::new(Metal::new(Vec3::new(1.00, 0.70, 0.70), 0.6)))),
Box::new(Sphere::new(Vec3::new(-0.017, 1.200, 0.217), 0.050, Box::new(Metal::new(Vec3::new(1.00, 0.70, 0.70), 0.6)))),
Box::new(Sphere::new(Vec3::new(-0.025, 1.163, 0.237), 0.050, Box::new(Metal::new(Vec3::new(1.00, 0.70, 0.70), 0.6)))),
Box::new(Sphere::new(Vec3::new(-0.033, 1.125, 0.258), 0.050, Box::new(Metal::new(Vec3::new(1.00, 0.70, 0.70), 0.6)))),
Box::new(Sphere::new(Vec3::new(-0.042, 1.087, 0.279), 0.050, Box::new(Metal::new(Vec3::new(1.00, 0.70, 0.70), 0.6)))),
Box::new(Sphere::new(Vec3::new(-0.050, 1.050, 0.300), 0.050, Box::new(Metal::new(Vec3::new(1.00, 0.70, 0.70), 0.6)))),
Box::new(Sphere::new(Vec3::new(-0.079, 1.071, 0.325), 0.046, Box::new(Metal::new(Vec3::new(1.00, 0.70, 0.70), 0.6)))),
Box::new(Sphere::new(Vec3::new(-0.107, 1.093, 0.350), 0.043, Box::new(Metal::new(Vec3::new(1.00, 0.70, 0.70), 0.6)))),
Box::new(Sphere::new(Vec3::new(-0.136, 1.114, 0.375), 0.039, Box::new(Metal::new(Vec3::new(1.00, 0.70, 0.70), 0.6)))),
Box::new(Sphere::new(Vec3::new(-0.164, 1.136, 0.400), 0.036, Box::new(Metal::new(Vec3::new(1.00, 0.70, 0.70), 0.6)))),
Box::new(Sphere::new(Vec3::new(-0.193, 1.157, 0.425), 0.032, Box::new(Metal::new(Vec3::new(1.00, 0.70, 0.70), 0.6)))),
Box::new(Sphere::new(Vec3::new(-0.221, 1.179, 0.450), 0.029, Box::new(Metal::new(Vec3::new(1.00, 0.70, 0.70), 0.6)))),
Box::new(Sphere::new(Vec3::new(-0.250, 1.200, 0.475), 0.025, Box::new(Metal::new(Vec3::new(1.00, 0.70, 0.70), 0.6)))),
));
random_spheres(&mut h, Vec3::new(0.0, 0.2, 0.0), 1.1);
let lookfrom = Vec3::new(-3.75, 1.375, 1.5);
let lookat = Vec3::new(0.0, 1.0, 0.0);
let dist_to_focus = (lookfrom - lookat).length();
let aperture = 0.1;
let cam = Camera::new(lookfrom, lookat, Vec3::new(0.0,1.0,0.0), 30.0, aspect, aperture, dist_to_focus);
(h, cam)
}
fn colour(r: &Ray, world: &Hitable, depth: i32) -> Vec3 {
match world.hit(r, 0.001, f32::MAX) {
Some(rec) => {
if depth > 50 {
Vec3::zero()
} else {
match rec.m.scatter(r, &rec) {
Some(s) => s.attenuation * colour(&s.scattered, world, depth+1),
None => Vec3::zero()
}
}
}
None => {
// Sky
let unit_direction = unit_vector(r.direction());
let t = 0.5 * (unit_direction.y() + 1.0);
(1.0 - t) * Vec3::new(1.0, 1.0, 1.0) + t * Vec3::new(0.5, 0.7, 1.0)
}
}
}
fn main() {
let nx = 200;
let ny = 150;
let ns = 100;
let (world, cam) = random_scene(nx as f32 / ny as f32);
let mut file = File::create(Path::new("out.ppm")).expect("can't open");
write!(file, "P6\n{width} {height}\n255\n", width=nx, height=ny).expect("can't write");
for j in (0..ny).rev() {
for i in 0..nx {
let mut col = Vec3::zero();
for _s in 0..ns {
let u = (i as f32 + rand()) / nx as f32;
let v = (j as f32 +rand()) / ny as f32;
let r = cam.get_ray(u,v);
col += colour(&r, &world, 0);
}
col *= 1.0 / ns as f32;
col = Vec3::new(col.r().sqrt(), col.g().sqrt(), col.b().sqrt());
let ia = [(255.99 * col.r()) as u8, (255.99 * col.g()) as u8, (255.99 * col.b()) as u8];
file.write(&ia).expect("can't write");
}
}
}
|
#[macro_export]
macro_rules! lua_multi {
[] => { $crate::LNil };
[$head: expr] => { $crate::LCons($head, $crate::LNil) };
[$head: expr, $($tail: expr), *] => { $crate::LCons($head, lua_multi![$($tail), *]) };
[$head: expr, $($tail: expr), *,] => { $crate::LCons($head, lua_multi![$($tail), *]) };
}
#[macro_export]
macro_rules! lua_multi_pat {
[] => { $crate::LNil{} };
[$head: pat] => { $crate::LCons($head, $crate::LNil{}) };
[$head: pat, $($tail: pat), *] => { $crate::LCons($head, lua_multi_pat![$($tail), *]) };
[$head: pat, $($tail: pat), *,] => { $crate::LCons($head, lua_multi_pat![$($tail), *]) };
}
#[macro_export]
macro_rules! LuaMulti {
[] => { $crate::LNil };
[$head: ty] => { $crate::LCons<$head, $crate::LNil> };
[$head: ty, $($tail: ty), *] => { $crate::LCons<$head, LuaMulti![$($tail), *]> };
[$head: ty, $($tail: ty), *,] => { $crate::LCons<$head, LuaMulti![$($tail), *]> };
}
#[macro_export]
macro_rules! lua_cstr {
($s:expr) => (
concat!($s, "\0") as *const str as *const [c_char] as *const c_char
);
}
|
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
_reserved0: [u8; 0x04],
#[doc = "0x04 - RI input capture register"]
pub icr: ICR,
#[doc = "0x08 - RI analog switches control register 1"]
pub ascr1: ASCR1,
#[doc = "0x0c - RI analog switches control register 2"]
pub ascr2: ASCR2,
#[doc = "0x10 - RI hysteresis control register 1"]
pub hyscr1: HYSCR1,
#[doc = "0x14 - RI hysteresis control register 2"]
pub hyscr2: HYSCR2,
#[doc = "0x18 - RI hysteresis control register 3"]
pub hyscr3: HYSCR3,
#[doc = "0x1c - Hysteresis control register"]
pub hyscr4: HYSCR4,
}
#[doc = "ICR (rw) register accessor: RI input capture register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`icr::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 [`icr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`icr`]
module"]
pub type ICR = crate::Reg<icr::ICR_SPEC>;
#[doc = "RI input capture register"]
pub mod icr;
#[doc = "ASCR1 (rw) register accessor: RI analog switches control register 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ascr1::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 [`ascr1::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`ascr1`]
module"]
pub type ASCR1 = crate::Reg<ascr1::ASCR1_SPEC>;
#[doc = "RI analog switches control register 1"]
pub mod ascr1;
#[doc = "ASCR2 (rw) register accessor: RI analog switches control register 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ascr2::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 [`ascr2::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`ascr2`]
module"]
pub type ASCR2 = crate::Reg<ascr2::ASCR2_SPEC>;
#[doc = "RI analog switches control register 2"]
pub mod ascr2;
#[doc = "HYSCR1 (rw) register accessor: RI hysteresis control register 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`hyscr1::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 [`hyscr1::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`hyscr1`]
module"]
pub type HYSCR1 = crate::Reg<hyscr1::HYSCR1_SPEC>;
#[doc = "RI hysteresis control register 1"]
pub mod hyscr1;
#[doc = "HYSCR2 (rw) register accessor: RI hysteresis control register 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`hyscr2::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 [`hyscr2::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`hyscr2`]
module"]
pub type HYSCR2 = crate::Reg<hyscr2::HYSCR2_SPEC>;
#[doc = "RI hysteresis control register 2"]
pub mod hyscr2;
#[doc = "HYSCR3 (rw) register accessor: RI hysteresis control register 3\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`hyscr3::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 [`hyscr3::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`hyscr3`]
module"]
pub type HYSCR3 = crate::Reg<hyscr3::HYSCR3_SPEC>;
#[doc = "RI hysteresis control register 3"]
pub mod hyscr3;
#[doc = "HYSCR4 (rw) register accessor: Hysteresis control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`hyscr4::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 [`hyscr4::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`hyscr4`]
module"]
pub type HYSCR4 = crate::Reg<hyscr4::HYSCR4_SPEC>;
#[doc = "Hysteresis control register"]
pub mod hyscr4;
|
//! Endpoint types.
//!
//! These types are transparent, short-lived wrappers around `Client`. They avoid having an
//! enormous number of methods on the `Client` itself. They can be created from methods on
//! `Client`, so you generally won't ever need to name them.
//!
//! # Common Parameters
//!
//! These are some common parameters used in endpoint functions.
//!
//! | Parameter | Use |
//! | --- | --- |
//! | `id(s)` | The [Spotify ID(s)](https://developer.spotify.com/documentation/web-api/#spotify-uris-and-ids) of the required resource. |
//! | `country` | Limits the request to one particular country, so that resources not available in the country will not appear in the results. |
//! | `market` | Limits the request to one particular country, and applies [Track Relinking](https://developer.spotify.com/documentation/general/guides/track-relinking-guide/). |
//! | `locale` | The language of the response. It consists of an ISO-639 language code and an ISO-3166 country code (for, example, En and GBR is British English). |
//! | `limit` | When the function returns a [`Page`](crate::Page), [`CursorPage`](crate::CursorPage) or [`TwoWayCursorPage`](crate::TwoWayCursorPage), this determines the maximum length of the page. |
//! | `offset` | When the function returns a [`Page`](crate::Page), this determines what index in the larger list the page starts at. |
//! | `cursor`, `before` and `after` | When the function returns a [`CursorPage`](crate::CursorPage) or [`TwoWayCursorPage`](crate::TwoWayCursorPage), this determines to give the next (`cursor` or `after`) or previous (`before`) page. |
#![allow(clippy::missing_errors_doc)]
use std::future::Future;
use std::iter;
use std::time::Instant;
use futures_util::stream::{FuturesOrdered, FuturesUnordered, StreamExt, TryStreamExt};
use isocountry::CountryCode;
use crate::{Client, Error, Response};
pub use albums::*;
pub use artists::*;
pub use browse::*;
pub use episodes::*;
pub use follow::*;
pub use library::*;
pub use personalization::*;
pub use player::*;
pub use playlists::*;
pub use search::*;
pub use shows::*;
pub use tracks::*;
pub use users_profile::*;
macro_rules! endpoint {
($path:literal) => {
concat!("https://api.spotify.com", $path)
};
($path:literal, $($fmt:tt)*) => {
&format!(endpoint!($path), $($fmt)*)
};
}
mod albums;
mod artists;
mod browse;
mod episodes;
mod follow;
mod library;
mod personalization;
mod player;
mod playlists;
mod search;
mod shows;
mod tracks;
mod users_profile;
/// Endpoint function namespaces.
impl Client {
/// Album-related endpoints.
#[must_use]
pub const fn albums(&self) -> Albums<'_> {
Albums(self)
}
/// Artist-related endpoints.
#[must_use]
pub const fn artists(&self) -> Artists<'_> {
Artists(self)
}
/// Endpoint functions related to categories, featured playlists, recommendations, and new
/// releases.
#[must_use]
pub const fn browse(&self) -> Browse<'_> {
Browse(self)
}
/// Episode-related endpoints.
#[must_use]
pub const fn episodes(&self) -> Episodes<'_> {
Episodes(self)
}
/// Endpoint functions related to following and unfollowing artists, users and playlists.
#[must_use]
pub const fn follow(&self) -> Follow<'_> {
Follow(self)
}
/// Endpoints relating to saving albums and tracks.
#[must_use]
pub const fn library(&self) -> Library<'_> {
Library(self)
}
/// Endpoint functions relating to a user's top artists and tracks.
#[must_use]
pub const fn personalization(&self) -> Personalization<'_> {
Personalization(self)
}
/// Endpoint functions related to controlling what is playing on the current user's Spotify
/// account. (Beta)
#[must_use]
pub const fn player(&self) -> Player<'_> {
Player(self)
}
/// Endpoint functions related to playlists.
#[must_use]
pub const fn playlists(&self) -> Playlists<'_> {
Playlists(self)
}
/// Endpoint functions related to searches.
#[must_use]
pub const fn search(&self) -> Search<'_> {
Search(self)
}
/// Endpoint functions related to shows.
#[must_use]
pub const fn shows(&self) -> Shows<'_> {
Shows(self)
}
/// Endpoint functions related to tracks and audio analysis.
#[must_use]
pub const fn tracks(&self) -> Tracks<'_> {
Tracks(self)
}
/// Endpoint functions related to users' profiles.
#[must_use]
pub const fn users_profile(&self) -> UsersProfile<'_> {
UsersProfile(self)
}
}
/// A market in which to limit the request to.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Market {
/// A country code.
Country(CountryCode),
/// Deduce the current country from the access token. Requires `user-read-private`.
FromToken,
}
impl Market {
fn as_str(self) -> &'static str {
match self {
Market::Country(code) => code.alpha2(),
Market::FromToken => "from_token",
}
}
fn query(self) -> (&'static str, &'static str) {
("market", self.as_str())
}
}
/// A time range from which to calculate the response.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum TimeRange {
/// Use approximately the last 4 weeks of data.
Short,
/// Use approximately the last 6 months of data.
Medium,
/// Use several years of data.
Long,
}
impl TimeRange {
fn as_str(self) -> &'static str {
match self {
Self::Long => "long_term",
Self::Medium => "medium_term",
Self::Short => "short_term",
}
}
}
type Chunk<'a, I> = iter::Take<&'a mut iter::Peekable<I>>;
async fn chunked_sequence<I: IntoIterator, Fut, T>(
items: I,
chunk_size: usize,
mut f: impl FnMut(Chunk<'_, I::IntoIter>) -> Fut,
) -> Result<Response<Vec<T>>, Error>
where
Fut: Future<Output = Result<Response<Vec<T>>, Error>>,
{
let mut items = items.into_iter().peekable();
let mut futures = FuturesOrdered::new();
while items.peek().is_some() {
futures.push(f(items.by_ref().take(chunk_size)));
}
let mut response = Response {
data: Vec::new(),
expires: Instant::now(),
};
while let Some(mut r) = futures.next().await.transpose()? {
response.data.append(&mut r.data);
response.expires = r.expires;
}
Ok(response)
}
async fn chunked_requests<I: IntoIterator, Fut>(
items: I,
chunk_size: usize,
mut f: impl FnMut(Chunk<'_, I::IntoIter>) -> Fut,
) -> Result<(), Error>
where
Fut: Future<Output = Result<(), Error>>,
{
let mut items = items.into_iter().peekable();
let futures = FuturesUnordered::new();
while items.peek().is_some() {
futures.push(f(items.by_ref().take(chunk_size)));
}
futures.try_collect().await
}
#[cfg(test)]
fn client() -> crate::Client {
dotenv::dotenv().unwrap();
let mut client = crate::Client::with_refresh(
crate::ClientCredentials::from_env().unwrap(),
std::fs::read_to_string(".refresh_token").unwrap(),
);
client.debug = true;
client
}
|
use ansi_term::{ANSIString, ANSIStrings, Colour, Style};
#[cfg(feature = "crossterm")]
use crossterm::{cursor, terminal, ClearType, InputEvent, KeyEvent, RawScreen};
use std::io::Write;
use sublime_fuzzy::best_match;
pub enum SelectionResult {
Selected(String),
Edit(String),
NoSelection,
}
pub fn interactive_fuzzy_search(lines: &Vec<&str>, max_results: usize) -> SelectionResult {
#[derive(PartialEq)]
enum State {
Selecting,
Quit,
Selected(String),
Edit(String),
}
let mut state = State::Selecting;
#[cfg(feature = "crossterm")]
{
if let Ok(_raw) = RawScreen::into_raw_mode() {
// User input for search
let mut searchinput = String::new();
let mut selected = 0;
let mut cursor = cursor();
let _ = cursor.hide();
let input = crossterm::input();
let mut sync_stdin = input.read_sync();
while state == State::Selecting {
let mut selected_lines = fuzzy_search(&searchinput, &lines, max_results);
let num_lines = selected_lines.len();
paint_selection_list(&selected_lines, selected);
if let Some(ev) = sync_stdin.next() {
match ev {
InputEvent::Keyboard(k) => match k {
KeyEvent::Esc | KeyEvent::Ctrl('c') => {
state = State::Quit;
}
KeyEvent::Up => {
if selected > 0 {
selected -= 1;
}
}
KeyEvent::Down => {
if selected + 1 < selected_lines.len() {
selected += 1;
}
}
KeyEvent::Char('\n') => {
state = if selected_lines.len() > 0 {
State::Selected(selected_lines.remove(selected).text)
} else {
State::Edit("".to_string())
};
}
KeyEvent::Char('\t') | KeyEvent::Right => {
state = if selected_lines.len() > 0 {
State::Edit(selected_lines.remove(selected).text)
} else {
State::Edit("".to_string())
};
}
KeyEvent::Char(ch) => {
searchinput.push(ch);
selected = 0;
}
KeyEvent::Backspace => {
searchinput.pop();
selected = 0;
}
_ => {
// println!("OTHER InputEvent: {:?}", k);
}
},
_ => {}
}
}
if num_lines > 0 {
cursor.move_up(num_lines as u16);
}
}
let (_x, y) = cursor.pos();
let _ = cursor.goto(0, y - 1);
let _ = cursor.show();
let _ = RawScreen::disable_raw_mode();
}
terminal().clear(ClearType::FromCursorDown).unwrap();
}
match state {
State::Selected(line) => SelectionResult::Selected(line),
State::Edit(line) => SelectionResult::Edit(line),
_ => SelectionResult::NoSelection,
}
}
pub struct Match {
text: String,
char_matches: Vec<(usize, usize)>,
}
pub fn fuzzy_search(searchstr: &str, lines: &Vec<&str>, max_results: usize) -> Vec<Match> {
if searchstr.is_empty() {
return lines
.iter()
.take(max_results)
.map(|line| Match {
text: line.to_string(),
char_matches: Vec::new(),
})
.collect();
}
let mut matches = lines
.iter()
.enumerate()
.map(|(idx, line)| (idx, best_match(&searchstr, line)))
.filter(|(_i, m)| m.is_some())
.map(|(i, m)| (i, m.unwrap()))
.collect::<Vec<_>>();
matches.sort_by(|a, b| b.1.score().cmp(&a.1.score()));
let results: Vec<Match> = matches
.iter()
.take(max_results)
.map(|(i, m)| Match {
text: lines[*i].to_string(),
char_matches: m.continuous_matches(),
})
.collect();
results
}
#[cfg(feature = "crossterm")]
fn highlight(textmatch: &Match, normal: Style, highlighted: Style) -> Vec<ANSIString> {
let text = &textmatch.text;
let mut ansi_strings = vec![];
let mut idx = 0;
for (match_idx, len) in &textmatch.char_matches {
ansi_strings.push(normal.paint(&text[idx..*match_idx]));
idx = match_idx + len;
ansi_strings.push(highlighted.paint(&text[*match_idx..idx]));
}
if idx < text.len() {
ansi_strings.push(normal.paint(&text[idx..text.len()]));
}
ansi_strings
}
#[cfg(feature = "crossterm")]
fn paint_selection_list(lines: &Vec<Match>, selected: usize) {
let terminal = terminal();
let size = terminal.terminal_size();
let width = size.0 as usize;
let cursor = cursor();
let (_x, y) = cursor.pos();
for (i, line) in lines.iter().enumerate() {
let _ = cursor.goto(0, y + (i as u16));
let (style, highlighted) = if selected == i {
(Colour::White.normal(), Colour::Cyan.normal())
} else {
(Colour::White.dimmed(), Colour::Cyan.normal())
};
let mut ansi_strings = highlight(line, style, highlighted);
for _ in line.text.len()..width {
ansi_strings.push(style.paint(' '.to_string()));
}
println!("{}", ANSIStrings(&ansi_strings));
}
let _ = cursor.goto(0, y + (lines.len() as u16));
print!(
"{}",
Colour::Blue.paint("[ESC to quit, Enter to execute, Tab to edit]")
);
let _ = std::io::stdout().flush();
// Clear additional lines from previous selection
terminal.clear(ClearType::FromCursorDown).unwrap();
}
#[test]
fn fuzzy_match() {
let matches = fuzzy_search("cb", &vec!["abc", "cargo build"], 1);
assert_eq!(matches[0].text, "cargo build");
}
|
use approx::ApproxEq;
use alga::general::{AbstractMagma, AbstractGroup, AbstractLoop, AbstractMonoid, AbstractQuasigroup,
AbstractSemigroup, Field, Real, Inverse, Multiplicative, Identity};
use alga::linear::{Transformation, ProjectiveTransformation};
use core::{Scalar, ColumnVector};
use core::dimension::{DimNameSum, DimNameAdd, U1};
use core::storage::OwnedStorage;
use core::allocator::{Allocator, OwnedAllocator};
use geometry::{PointBase, TransformBase, TCategory, SubTCategoryOf, TProjective};
/*
*
* Algebraic structures.
*
*/
impl<N, D: DimNameAdd<U1>, S, C> Identity<Multiplicative> for TransformBase<N, D, S, C>
where N: Scalar + Field,
S: OwnedStorage<N, DimNameSum<D, U1>, DimNameSum<D, U1>>,
C: TCategory,
S::Alloc: OwnedAllocator<N, DimNameSum<D, U1>, DimNameSum<D, U1>, S> {
#[inline]
fn identity() -> Self {
Self::identity()
}
}
impl<N, D: DimNameAdd<U1>, S, C> Inverse<Multiplicative> for TransformBase<N, D, S, C>
where N: Scalar + Field + ApproxEq,
S: OwnedStorage<N, DimNameSum<D, U1>, DimNameSum<D, U1>>,
C: SubTCategoryOf<TProjective>,
S::Alloc: OwnedAllocator<N, DimNameSum<D, U1>, DimNameSum<D, U1>, S> {
#[inline]
fn inverse(&self) -> Self {
self.clone().inverse()
}
#[inline]
fn inverse_mut(&mut self) {
self.inverse_mut()
}
}
impl<N, D: DimNameAdd<U1>, S, C> AbstractMagma<Multiplicative> for TransformBase<N, D, S, C>
where N: Scalar + Field,
S: OwnedStorage<N, DimNameSum<D, U1>, DimNameSum<D, U1>>,
C: TCategory,
S::Alloc: OwnedAllocator<N, DimNameSum<D, U1>, DimNameSum<D, U1>, S> {
#[inline]
fn operate(&self, rhs: &Self) -> Self {
self * rhs
}
}
macro_rules! impl_multiplicative_structures(
($($marker: ident<$operator: ident>),* $(,)*) => {$(
impl<N, D: DimNameAdd<U1>, S, C> $marker<$operator> for TransformBase<N, D, S, C>
where N: Scalar + Field,
S: OwnedStorage<N, DimNameSum<D, U1>, DimNameSum<D, U1>>,
C: TCategory,
S::Alloc: OwnedAllocator<N, DimNameSum<D, U1>, DimNameSum<D, U1>, S> { }
)*}
);
macro_rules! impl_inversible_multiplicative_structures(
($($marker: ident<$operator: ident>),* $(,)*) => {$(
impl<N, D: DimNameAdd<U1>, S, C> $marker<$operator> for TransformBase<N, D, S, C>
where N: Scalar + Field + ApproxEq,
S: OwnedStorage<N, DimNameSum<D, U1>, DimNameSum<D, U1>>,
C: SubTCategoryOf<TProjective>,
S::Alloc: OwnedAllocator<N, DimNameSum<D, U1>, DimNameSum<D, U1>, S> { }
)*}
);
impl_multiplicative_structures!(
AbstractSemigroup<Multiplicative>,
AbstractMonoid<Multiplicative>,
);
impl_inversible_multiplicative_structures!(
AbstractQuasigroup<Multiplicative>,
AbstractLoop<Multiplicative>,
AbstractGroup<Multiplicative>
);
/*
*
* Transformation groups.
*
*/
impl<N, D: DimNameAdd<U1>, SA, SB, C> Transformation<PointBase<N, D, SB>> for TransformBase<N, D, SA, C>
where N: Real,
SA: OwnedStorage<N, DimNameSum<D, U1>, DimNameSum<D, U1>>,
SB: OwnedStorage<N, D, U1, Alloc = SA::Alloc>,
C: TCategory,
SA::Alloc: OwnedAllocator<N, DimNameSum<D, U1>, DimNameSum<D, U1>, SA> +
Allocator<N, D, D> +
Allocator<N, D, U1> +
Allocator<N, U1, D>,
SB::Alloc: OwnedAllocator<N, D, U1, SB> {
#[inline]
fn transform_point(&self, pt: &PointBase<N, D, SB>) -> PointBase<N, D, SB> {
self * pt
}
#[inline]
fn transform_vector(&self, v: &ColumnVector<N, D, SB>) -> ColumnVector<N, D, SB> {
self * v
}
}
impl<N, D: DimNameAdd<U1>, SA, SB, C> ProjectiveTransformation<PointBase<N, D, SB>> for TransformBase<N, D, SA, C>
where N: Real,
SA: OwnedStorage<N, DimNameSum<D, U1>, DimNameSum<D, U1>>,
SB: OwnedStorage<N, D, U1, Alloc = SA::Alloc>,
C: SubTCategoryOf<TProjective>,
SA::Alloc: OwnedAllocator<N, DimNameSum<D, U1>, DimNameSum<D, U1>, SA> +
Allocator<N, D, D> +
Allocator<N, D, U1> +
Allocator<N, U1, D>,
SB::Alloc: OwnedAllocator<N, D, U1, SB> {
#[inline]
fn inverse_transform_point(&self, pt: &PointBase<N, D, SB>) -> PointBase<N, D, SB> {
self.inverse() * pt
}
#[inline]
fn inverse_transform_vector(&self, v: &ColumnVector<N, D, SB>) -> ColumnVector<N, D, SB> {
self.inverse() * v
}
}
// FIXME: we need to implement an SVD for this.
//
// impl<N, D: DimNameAdd<U1>, SA, SB, C> AffineTransformation<PointBase<N, D, SB>> for TransformBase<N, D, SA, C>
// where N: Real,
// SA: OwnedStorage<N, DimNameSum<D, U1>, DimNameSum<D, U1>>,
// SB: OwnedStorage<N, D, U1, Alloc = SA::Alloc>,
// C: SubTCategoryOf<TAffine>,
// SA::Alloc: OwnedAllocator<N, DimNameSum<D, U1>, DimNameSum<D, U1>, SA> +
// Allocator<N, D, D> +
// Allocator<N, D, U1> +
// Allocator<N, U1, D>,
// SB::Alloc: OwnedAllocator<N, D, U1, SB> {
// type PreRotation = OwnedRotation<N, D, SA::Alloc>;
// type NonUniformScaling = OwnedColumnVector<N, D, SA::Alloc>;
// type PostRotation = OwnedRotation<N, D, SA::Alloc>;
// type Translation = OwnedTranslation<N, D, SA::Alloc>;
//
// #[inline]
// fn decompose(&self) -> (Self::Translation, Self::PostRotation, Self::NonUniformScaling, Self::PreRotation) {
// unimplemented!()
// }
// }
|
//! # 48. 旋转图像
//! https://leetcode-cn.com/problems/rotate-image/
//! 给定一个 n × n 的二维矩阵表示一个图像。
//! 将图像顺时针旋转 90 度。
//! 说明:
//! 你必须在原地旋转图像,这意味着你需要直接修改输入的二维矩阵。请不要使用另一个矩阵来旋转图像。
//! # 解题思路
//! 从外层往内层递归旋转 最外层旋转规律(0<=i<n) [0,i]->[i,n]->[n,n-i]->[n-i,0]->[0,i]
pub struct Solution;
impl Solution {
pub fn rotate(matrix: &mut Vec<Vec<i32>>) {
Self::rotate_recursive(matrix, 0, 0, matrix.len())
}
pub fn rotate_recursive(matrix: &mut Vec<Vec<i32>>, x: usize, y: usize, len: usize) {
if len <= 1 {
return;
}
for i in 0..len - 1 {
//[0,i]->[i,n]->[n,n-i]->[n-i,0]->[0,i]
let v = matrix[y][i + x];
matrix[y][i + x] = matrix[len - 1 - i + y][x]; //[n-i,0]
matrix[len - 1 - i + y][x] = matrix[len - 1 + y][len - 1 - i + x]; //[n,n-i]
matrix[len - 1 + y][len - 1 - i + x] = matrix[i + y][len - 1 + x]; //[i,n]
matrix[i + y][len - 1 + x] = v; //[0,i]
}
Self::rotate_recursive(matrix, x + 1, y + 1, len - 2)
}
}
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
let mut v = [[1, 2, 3].into(), [4, 5, 6].into(), [7, 8, 9].into()].into();
super::Solution::rotate(&mut v);
assert_eq!(2 + 2, 4);
}
}
|
$NetBSD: patch-vendor_libc-0.2.144_src_unix_bsd_netbsdlike_netbsd_mod.rs,v 1.1 2023/07/05 20:33:42 he Exp $
Add riscv64.
--- ../vendor/libc-0.2.144/src/unix/bsd/netbsdlike/netbsd/mod.rs.orig 1973-11-29 21:33:09.000000000 +0000
+++ ../vendor/libc-0.2.144/src/unix/bsd/netbsdlike/netbsd/mod.rs
@@ -2807,6 +2807,9 @@ cfg_if! {
} else if #[cfg(target_arch = "x86")] {
mod x86;
pub use self::x86::*;
+ } else if #[cfg(target_arch = "riscv64")] {
+ mod riscv64;
+ pub use self::riscv64::*;
} else {
// Unknown target_arch
}
|
//! An audio module that enables basic audio output in Amethyst
//!
//! Based on [`rodio`], this crate provides audio output that works out of the box not only
//! on many mainstream platforms, but supports different backends (e.g. Alsa and Jack on Linux).
//!
//! [rodio]: https://docs.rs/rodio/0.14.0/rodio/index.html
//!
//! # How to use
//!
//! **Make sure you have enabled Amethyst's "audio" feature in your game!**
//!
//! For basic audio output, you can:
//! - Add an [`AudioBundle`] to your dispatcher.
//! - Create audio [`SourceHandle`] by loading a file as an asset using the [`Loader`].
//! - Access the [`Output`] resource in your system and play the sound from it directly or spawn a
//! sink for more control.
//!
//! [`Output`]: output/struct.Output.html
//! [`Loader`]: ../amethyst_assets/trait.Loader.html
#![doc(
html_logo_url = "https://amethyst.rs/brand/logo-standard.svg",
html_root_url = "https://docs.amethyst.rs/stable"
)]
#![deny(
missing_debug_implementations,
missing_docs,
rust_2018_idioms,
rust_2018_compatibility,
clippy::all
)]
#![warn(clippy::pedantic)]
#![allow(clippy::new_without_default, clippy::module_name_repetitions)]
use std::{
error::Error,
fmt::{Display, Formatter, Result as FmtResult},
};
pub use self::{
bundle::AudioBundle,
components::*,
formats::{FlacFormat, Mp3Format, OggFormat, WavFormat},
sink::Sink,
source::{Source, SourceHandle},
systems::*,
};
pub mod output;
mod bundle;
mod components;
mod end_signal;
mod formats;
mod sink;
mod source;
mod systems;
/// An error occurred while decoding the source.
#[derive(Debug)]
pub struct DecoderError;
impl Display for DecoderError {
fn fmt(&self, formatter: &mut Formatter<'_>) -> FmtResult {
formatter.write_str("DecoderError")
}
}
impl Error for DecoderError {
fn description(&self) -> &str {
"An error occurred while decoding sound data."
}
fn cause(&self) -> Option<&dyn Error> {
None
}
}
impl From<rodio::decoder::DecoderError> for DecoderError {
fn from(_: rodio::decoder::DecoderError) -> Self {
DecoderError
}
}
|
/// CreateIssueOption options to create one issue
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct CreateIssueOption {
/// username of assignee
pub assignee: Option<String>,
pub assignees: Option<Vec<String>>,
pub body: Option<String>,
pub closed: Option<bool>,
pub due_date: Option<String>,
/// list of label ids
pub labels: Option<Vec<i64>>,
/// milestone id
pub milestone: Option<i64>,
pub title: String,
}
impl CreateIssueOption {
/// Create a builder for this object.
#[inline]
pub fn builder() -> CreateIssueOptionBuilder<crate::generics::MissingTitle> {
CreateIssueOptionBuilder {
body: Default::default(),
_title: core::marker::PhantomData,
}
}
#[inline]
pub fn issue_create_issue() -> CreateIssueOptionPostBuilder<crate::generics::MissingOwner, crate::generics::MissingRepo, crate::generics::MissingTitle> {
CreateIssueOptionPostBuilder {
inner: Default::default(),
_param_owner: core::marker::PhantomData,
_param_repo: core::marker::PhantomData,
_title: core::marker::PhantomData,
}
}
}
impl Into<CreateIssueOption> for CreateIssueOptionBuilder<crate::generics::TitleExists> {
fn into(self) -> CreateIssueOption {
self.body
}
}
impl Into<CreateIssueOption> for CreateIssueOptionPostBuilder<crate::generics::OwnerExists, crate::generics::RepoExists, crate::generics::TitleExists> {
fn into(self) -> CreateIssueOption {
self.inner.body
}
}
/// Builder for [`CreateIssueOption`](./struct.CreateIssueOption.html) object.
#[derive(Debug, Clone)]
pub struct CreateIssueOptionBuilder<Title> {
body: self::CreateIssueOption,
_title: core::marker::PhantomData<Title>,
}
impl<Title> CreateIssueOptionBuilder<Title> {
/// username of assignee
#[inline]
pub fn assignee(mut self, value: impl Into<String>) -> Self {
self.body.assignee = Some(value.into());
self
}
#[inline]
pub fn assignees(mut self, value: impl Iterator<Item = impl Into<String>>) -> Self {
self.body.assignees = Some(value.map(|value| value.into()).collect::<Vec<_>>().into());
self
}
#[inline]
pub fn body(mut self, value: impl Into<String>) -> Self {
self.body.body = Some(value.into());
self
}
#[inline]
pub fn closed(mut self, value: impl Into<bool>) -> Self {
self.body.closed = Some(value.into());
self
}
#[inline]
pub fn due_date(mut self, value: impl Into<String>) -> Self {
self.body.due_date = Some(value.into());
self
}
/// list of label ids
#[inline]
pub fn labels(mut self, value: impl Iterator<Item = impl Into<i64>>) -> Self {
self.body.labels = Some(value.map(|value| value.into()).collect::<Vec<_>>().into());
self
}
/// milestone id
#[inline]
pub fn milestone(mut self, value: impl Into<i64>) -> Self {
self.body.milestone = Some(value.into());
self
}
#[inline]
pub fn title(mut self, value: impl Into<String>) -> CreateIssueOptionBuilder<crate::generics::TitleExists> {
self.body.title = value.into();
unsafe { std::mem::transmute(self) }
}
}
/// Builder created by [`CreateIssueOption::issue_create_issue`](./struct.CreateIssueOption.html#method.issue_create_issue) method for a `POST` operation associated with `CreateIssueOption`.
#[repr(transparent)]
#[derive(Debug, Clone)]
pub struct CreateIssueOptionPostBuilder<Owner, Repo, Title> {
inner: CreateIssueOptionPostBuilderContainer,
_param_owner: core::marker::PhantomData<Owner>,
_param_repo: core::marker::PhantomData<Repo>,
_title: core::marker::PhantomData<Title>,
}
#[derive(Debug, Default, Clone)]
struct CreateIssueOptionPostBuilderContainer {
body: self::CreateIssueOption,
param_owner: Option<String>,
param_repo: Option<String>,
}
impl<Owner, Repo, Title> CreateIssueOptionPostBuilder<Owner, Repo, Title> {
/// owner of the repo
#[inline]
pub fn owner(mut self, value: impl Into<String>) -> CreateIssueOptionPostBuilder<crate::generics::OwnerExists, Repo, Title> {
self.inner.param_owner = Some(value.into());
unsafe { std::mem::transmute(self) }
}
/// name of the repo
#[inline]
pub fn repo(mut self, value: impl Into<String>) -> CreateIssueOptionPostBuilder<Owner, crate::generics::RepoExists, Title> {
self.inner.param_repo = Some(value.into());
unsafe { std::mem::transmute(self) }
}
/// username of assignee
#[inline]
pub fn assignee(mut self, value: impl Into<String>) -> Self {
self.inner.body.assignee = Some(value.into());
self
}
#[inline]
pub fn assignees(mut self, value: impl Iterator<Item = impl Into<String>>) -> Self {
self.inner.body.assignees = Some(value.map(|value| value.into()).collect::<Vec<_>>().into());
self
}
#[inline]
pub fn body(mut self, value: impl Into<String>) -> Self {
self.inner.body.body = Some(value.into());
self
}
#[inline]
pub fn closed(mut self, value: impl Into<bool>) -> Self {
self.inner.body.closed = Some(value.into());
self
}
#[inline]
pub fn due_date(mut self, value: impl Into<String>) -> Self {
self.inner.body.due_date = Some(value.into());
self
}
/// list of label ids
#[inline]
pub fn labels(mut self, value: impl Iterator<Item = impl Into<i64>>) -> Self {
self.inner.body.labels = Some(value.map(|value| value.into()).collect::<Vec<_>>().into());
self
}
/// milestone id
#[inline]
pub fn milestone(mut self, value: impl Into<i64>) -> Self {
self.inner.body.milestone = Some(value.into());
self
}
#[inline]
pub fn title(mut self, value: impl Into<String>) -> CreateIssueOptionPostBuilder<Owner, Repo, crate::generics::TitleExists> {
self.inner.body.title = value.into();
unsafe { std::mem::transmute(self) }
}
}
impl<Client: crate::client::ApiClient + Sync + 'static> crate::client::Sendable<Client> for CreateIssueOptionPostBuilder<crate::generics::OwnerExists, crate::generics::RepoExists, crate::generics::TitleExists> {
type Output = crate::issue::Issue;
const METHOD: http::Method = http::Method::POST;
fn rel_path(&self) -> std::borrow::Cow<'static, str> {
format!("/repos/{owner}/{repo}/issues", owner=self.inner.param_owner.as_ref().expect("missing parameter owner?"), repo=self.inner.param_repo.as_ref().expect("missing parameter repo?")).into()
}
fn modify(&self, req: Client::Request) -> Result<Client::Request, crate::client::ApiError<Client::Response>> {
use crate::client::Request;
Ok(req
.json(&self.inner.body))
}
}
impl crate::client::ResponseWrapper<crate::issue::Issue, CreateIssueOptionPostBuilder<crate::generics::OwnerExists, crate::generics::RepoExists, crate::generics::TitleExists>> {
#[inline]
pub fn message(&self) -> Option<String> {
self.headers.get("message").and_then(|v| String::from_utf8_lossy(v.as_ref()).parse().ok())
}
#[inline]
pub fn url(&self) -> Option<String> {
self.headers.get("url").and_then(|v| String::from_utf8_lossy(v.as_ref()).parse().ok())
}
}
|
//! `const fn` implementation of the SHA-2 family of hash functions.
//!
//! This crate allows you to use the SHA-2 hash functions as constant
//! expressions in Rust. For all other usages, the [`sha2`] crate includes more
//! optimized implementations of these hash functions.
//!
//! [`sha2`]: https://crates.io/crates/sha2
//!
//! # Examples
//!
//! Compute the SHA-256 hash of the Bitcoin genesis block at compile time:
//!
//! ```rust
//! # use sha2_const::Sha256;
//! const VERSION: u32 = 1;
//! const HASH_PREV_BLOCK: [u8; 32] = [0; 32];
//! const HASH_MERKLE_ROOT: [u8; 32] = [
//! 0x3b, 0xa3, 0xed, 0xfd, 0x7a, 0x7b, 0x12, 0xb2, 0x7a, 0xc7, 0x2c, 0x3e, 0x67, 0x76, 0x8f,
//! 0x61, 0x7f, 0xc8, 0x1b, 0xc3, 0x88, 0x8a, 0x51, 0x32, 0x3a, 0x9f, 0xb8, 0xaa, 0x4b, 0x1e,
//! 0x5e, 0x4a,
//! ];
//! const TIME: u32 = 1231006505;
//! const BITS: u32 = 0x1d00ffff;
//! const NONCE: u32 = 0x7c2bac1d;
//!
//! const BLOCK_HASH: [u8; 32] = Sha256::new()
//! .update(
//! &Sha256::new()
//! .update(&VERSION.to_le_bytes())
//! .update(&HASH_PREV_BLOCK)
//! .update(&HASH_MERKLE_ROOT)
//! .update(&TIME.to_le_bytes())
//! .update(&BITS.to_le_bytes())
//! .update(&NONCE.to_le_bytes())
//! .finalize(),
//! )
//! .finalize();
//!
//! assert_eq!(
//! hex::encode(&BLOCK_HASH[..]),
//! "6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000"
//! );
//! ```
#![feature(const_mut_refs)]
#![no_std]
mod constants;
mod sha;
mod util;
use constants::{H224, H256, H384, H512, H512_224, H512_256};
use util::memcpy;
macro_rules! sha {
(
$(#[$doc:meta])* $name:ident,
$size:literal,
$inner:ty,
$iv:ident
) => {
$(#[$doc])*
#[derive(Clone)]
pub struct $name {
inner: $inner,
}
impl $name {
/// The internal block size of the hash function.
pub const BLOCK_SIZE: usize = <$inner>::BLOCK_SIZE;
/// The digest size of the hash function.
pub const DIGEST_SIZE: usize = $size;
/// Construct a new instance.
pub const fn new() -> Self {
Self {
inner: <$inner>::new($iv),
}
}
/// Add input data to the hash context.
#[must_use]
pub const fn update(mut self, input: &[u8]) -> Self {
self.inner.update(&input);
self
}
/// Finalize the context and compute the digest.
#[must_use]
pub const fn finalize(self) -> [u8; Self::DIGEST_SIZE] {
let digest = self.inner.finalize();
let mut truncated = [0; Self::DIGEST_SIZE];
memcpy(&mut truncated, 0, &digest, 0, Self::DIGEST_SIZE);
truncated
}
}
};
}
sha!(
/// The SHA-224 hash function.
///
/// The SHA-256 algorithm with the SHA-224 initialization vector, truncated
/// to 224 bits.
///
/// # Examples
///
/// ```rust
/// # use sha2_const::Sha224;
/// const DIGEST: [u8; 28] = Sha224::new()
/// .update(b"The quick brown fox ")
/// .update(b"jumps over the lazy dog")
/// .finalize();
///
/// assert_eq!(
/// hex::encode(&DIGEST[..]),
/// "730e109bd7a8a32b1cb9d9a09aa2325d2430587ddbc0c38bad911525"
/// );
/// ```
Sha224,
28,
sha::Sha256,
H224
);
sha!(
/// The SHA-256 hash function.
///
/// # Examples
///
/// ```rust
/// # use sha2_const::Sha256;
/// const DIGEST: [u8; 32] = Sha256::new()
/// .update(b"The quick brown fox ")
/// .update(b"jumps over the lazy dog")
/// .finalize();
///
/// assert_eq!(
/// hex::encode(&DIGEST[..]),
/// "d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592"
/// );
/// ```
Sha256,
32,
sha::Sha256,
H256
);
sha!(
/// The SHA-384 hash function.
///
/// The SHA-512 algorithm with the SHA-384 initialization vector, truncated
/// to 384 bits.
///
/// # Examples
///
/// ```rust
/// # use sha2_const::Sha384;
/// const DIGEST: [u8; 48] = Sha384::new()
/// .update(b"The quick brown fox ")
/// .update(b"jumps over the lazy dog")
/// .finalize();
///
/// assert_eq!(
/// hex::encode(&DIGEST[..]),
/// concat!(
/// "ca737f1014a48f4c0b6dd43cb177b0afd9e5169367544c49",
/// "4011e3317dbf9a509cb1e5dc1e85a941bbee3d7f2afbc9b1"
/// )
/// );
/// ```
Sha384,
48,
sha::Sha512,
H384
);
sha!(
/// The SHA-512 hash function.
///
/// # Examples
///
/// ```rust
/// # use sha2_const::Sha512;
/// const DIGEST: [u8; 64] = Sha512::new()
/// .update(b"The quick brown fox ")
/// .update(b"jumps over the lazy dog")
/// .finalize();
///
/// assert_eq!(
/// hex::encode(&DIGEST[..]),
/// concat!(
/// "07e547d9586f6a73f73fbac0435ed76951218fb7d0c8d788a309d785436bbb64",
/// "2e93a252a954f23912547d1e8a3b5ed6e1bfd7097821233fa0538f3db854fee6"
/// )
/// );
/// ```
Sha512,
64,
sha::Sha512,
H512
);
sha!(
/// The SHA-512/224 hash function.
///
/// The SHA-512 algorithm with the SHA-512/224 initialization vector,
/// truncated to 224 bits.
///
/// # Examples
///
/// ```rust
/// # use sha2_const::Sha512_224;
/// const DIGEST: [u8; 28] = Sha512_224::new()
/// .update(b"The quick brown fox ")
/// .update(b"jumps over the lazy dog")
/// .finalize();
///
/// assert_eq!(
/// hex::encode(&DIGEST[..]),
/// "944cd2847fb54558d4775db0485a50003111c8e5daa63fe722c6aa37"
/// );
/// ```
Sha512_224,
28,
sha::Sha512,
H512_224
);
sha!(
/// The SHA-512/256 hash function.
///
/// The SHA-512 algorithm with the SHA-512/256 initialization vector,
/// truncated to 256 bits.
///
/// # Examples
///
/// ```rust
/// # use sha2_const::Sha512_256;
/// const DIGEST: [u8; 32] = Sha512_256::new()
/// .update(b"The quick brown fox ")
/// .update(b"jumps over the lazy dog")
/// .finalize();
///
/// assert_eq!(
/// hex::encode(&DIGEST[..]),
/// "dd9d67b371519c339ed8dbd25af90e976a1eeefd4ad3d889005e532fc5bef04d"
/// );
/// ```
Sha512_256,
32,
sha::Sha512,
H512_256
);
|
//! Defines various views to use when creating the layout.
#[macro_use]
mod view_wrapper;
// Essentials components
mod position;
mod view_path;
// Helper bases
mod scroll;
// Views
mod box_view;
mod button;
mod dialog;
mod edit_view;
mod full_view;
mod id_view;
mod key_event_view;
mod linear_layout;
mod menu_popup;
mod shadow_view;
mod select_view;
mod sized_view;
mod stack_view;
mod text_view;
mod tracked_view;
use std::any::Any;
use event::{Event, EventResult};
use vec::Vec2;
use printer::Printer;
pub use self::position::{Offset, Position};
pub use self::scroll::ScrollBase;
pub use self::id_view::IdView;
pub use self::box_view::BoxView;
pub use self::button::Button;
pub use self::dialog::Dialog;
pub use self::edit_view::EditView;
pub use self::full_view::FullView;
pub use self::key_event_view::KeyEventView;
pub use self::linear_layout::LinearLayout;
pub use self::menu_popup::MenuPopup;
pub use self::view_path::ViewPath;
pub use self::select_view::SelectView;
pub use self::shadow_view::ShadowView;
pub use self::stack_view::StackView;
pub use self::text_view::TextView;
pub use self::tracked_view::TrackedView;
pub use self::sized_view::SizedView;
pub use self::view_wrapper::ViewWrapper;
/// Main trait defining a view behaviour.
pub trait View {
/// Called when a key was pressed. Default implementation just ignores it.
fn on_event(&mut self, Event) -> EventResult {
EventResult::Ignored
}
/// Returns the minimum size the view requires with the given restrictions.
fn get_min_size(&mut self, Vec2) -> Vec2 {
Vec2::new(1, 1)
}
/// Called once the size for this view has been decided, so it can
/// propagate the information to its children.
fn layout(&mut self, Vec2) {}
/// Draws the view with the given printer (includes bounds) and focus.
fn draw(&mut self, printer: &Printer);
/// Finds the view pointed to by the given path.
/// Returns None if the path doesn't lead to a view.
fn find(&mut self, &Selector) -> Option<&mut Any> {
None
}
/// This view is offered focus. Will it take it?
fn take_focus(&mut self) -> bool {
false
}
}
/// Selects a single view (if any) in the tree.
pub enum Selector<'a> {
/// Selects a view from its ID
Id(&'a str),
/// Selects a view from its path
Path(&'a ViewPath),
}
|
use anyhow::{anyhow, Result};
use clap::{ArgMatches, Values};
use rpassword;
use std::path::PathBuf;
use crate::icore::arg::{Arg, OverwriteStrategy, SendArg, RecvArg};
pub fn parse_input(m: &ArgMatches) -> Result<Arg> {
let arg = match (m.occurrences_of("send"), m.occurrences_of("receive")) {
(1, 0) => parse_send_arg(m)?,
(0, 1) => parse_recv_arg(m)?,
_ => return Err(anyhow!("Unknow client type")),
};
Ok(arg)
}
fn parse_send_arg(m: &ArgMatches) -> Result<Arg> {
let send_arg = SendArg {
expire: parse_expire(m),
files: parse_sending_files(m),
msg: parse_msg(m),
password: parse_password(m),
};
if send_arg.msg.is_some() || send_arg.files.is_some() {
Ok(Arg::S(send_arg))
} else {
Err(anyhow!("Invalid arguments format"))
}
}
fn parse_recv_arg(m: &ArgMatches) -> Result<Arg> {
let code = parse_code(m)?;
let dir = match parse_dir(m) {
Some(d) => d,
None => std::env::current_dir().expect("Cannot get current dir"),
};
let recv_arg = RecvArg {
code,
dir,
expire: parse_expire(m),
overwrite: parse_overwrite(m),
password: parse_password(m),
};
Ok(Arg::R(recv_arg))
}
fn parse_password(m: &ArgMatches) -> Option<String> {
if m.occurrences_of("password") > 0 {
loop {
let pw = rpassword::read_password_from_tty(Some("Please enter the password: ")).unwrap();
let pw_str = pw.trim();
if pw_str.len() > 0 && pw_str.len() <= 255{
return Some(String::from(pw_str));
} else {
println!("Invalid password length");
}
}
}
None
}
fn parse_expire(m: &ArgMatches) -> u8 {
if let Some(e) = m.value_of("expire") {
match e.parse() {
Ok(e_num) => return e_num,
Err(_) => {
eprintln!("Invalid expire number. Should be in range 1 to 255");
}
}
}
// Test use: default expire time 2 minute.
2
}
fn parse_msg(m: &ArgMatches) -> Option<String> {
match m.value_of("message") {
Some(v) => Some(String::from(v)),
None => None,
}
}
fn parse_sending_files(m: &ArgMatches) -> Option<Vec<PathBuf>> {
match m.values_of("INPUT") {
Some(mut fs) => parse_files(&mut fs),
None => None,
}
}
fn parse_files(fs: &mut Values) -> Option<Vec<PathBuf>> {
let mut files: Vec<_> = Vec::new();
while let Some(f) = fs.next() {
let path = PathBuf::from(f);
if path.is_file() || path.is_dir() {
files.push(path);
} else {
eprintln!("Invalid path: {}", f);
std::process::exit(1);
}
}
if files.len() > 0 { Some(files) } else { None }
}
fn parse_code(m: &ArgMatches) -> Result<u16> {
match m.values_of("INPUT") {
Some(mut inputs) => parse_code_from_inputs(&mut inputs),
None => Err(anyhow!("No code input")),
}
}
fn parse_code_from_inputs(inputs: &mut Values) -> Result<u16> {
if inputs.len() != 1 {
return Err(anyhow!("Only one code input allowed"));
}
match inputs.next() {
Some(v) => {
match u16::from_str_radix(v, 10) {
Ok(port) => Ok(port),
Err(_) => Err(anyhow!("Invalid code format")),
}
}
None => Err(anyhow!("Error parsing code from input")),
}
}
fn parse_dir(m: &ArgMatches) -> Option<PathBuf> {
match m.value_of("dir") {
Some(dir) => {
let path = PathBuf::from(dir);
if path.is_dir() {Some(path)} else {None}
},
None => None,
}
}
fn parse_overwrite(m: &ArgMatches) -> OverwriteStrategy {
log::debug!("Parsing overwirte");
match m.value_of("overwrite") {
Some("o") | Some("O") => OverwriteStrategy::Overwrite,
Some("r") | Some("R") => OverwriteStrategy::Rename,
Some("s") | Some("S") => OverwriteStrategy::Skip,
_ => OverwriteStrategy::Ask,
}
} |
//! Module related to the user struct.
use crate::{
auth::Auth,
client::{route::Route, Client},
error::Error,
model::{misc::Fullname, misc::Params, usersubreddit::UserSubreddit},
};
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Serialize, Deserialize)]
/// The struct representing a reddit user.
pub struct User {
/// The comment karma of the user.
pub comment_karma: i64,
/// When the user was created, local timezone.
pub created: f64,
/// When the user was created, normalized to UTC.
pub created_utc: f64,
/// If the user has a verified email.
pub has_verified_email: bool,
/// If the user should be hidden from robots.
pub hide_from_robots: bool,
/// Link to the image of the user's icon.
pub icon_img: String,
/// The API ID of the user.
pub id: Fullname,
/// If the user is an employee of Reddit.
pub is_employee: bool,
/// If the user is added as a friend.
pub is_friend: bool,
/// If the user currently has gold.
pub is_gold: bool,
/// If the user is a global moderator.
pub is_mod: bool,
/// The link karma of the user.
pub link_karma: i64,
/// The name of the user.
pub name: String,
/// The user's subreddit.
pub subreddit: UserSubreddit,
/// If the user is verified.
pub verified: bool,
}
impl User {
/// Reports the User to the reddit admins.
pub async fn block<T: Auth + Send + Sync>(&self, client: &Client<T>) -> Result<(), Error> {
client
.post(
Route::BlockUser,
&Params::new()
.add("name", &self.name)
.add("account_id", self.id.as_ref())
.add("api_type", "json"),
)
.await
.and(Ok(()))
}
/// Adds the User to friends.
pub async fn friend<T: Auth + Send + Sync>(
&self,
client: &Client<T>,
note: Option<&str>,
) -> Result<(), Error> {
client
.put(
Route::Friends(self.name.clone()),
&Params::new()
.add("name", &self.name)
.add("note", note.unwrap_or("")),
)
.await
.and(Ok(()))
}
/// Removes a User from your friends.
pub async fn unfriend<T: Auth + Send + Sync>(&self, client: &Client<T>) -> Result<(), Error> {
client
.delete(Route::Friends(self.name.clone()))
.await
.and(Ok(()))
}
/// Reports the User to the reddit admins.
pub async fn report<T: Auth + Send + Sync>(
&self,
client: &Client<T>,
reason: Option<&str>,
) -> Result<(), Error> {
client
.post(
Route::ReportUser,
&Params::new()
.add("user", &self.name)
.add("reason", reason.unwrap_or("")),
)
.await
.and(Ok(()))
}
}
|
#[doc = "Reader of register SLEEP_EN1"]
pub type R = crate::R<u32, super::SLEEP_EN1>;
#[doc = "Writer for register SLEEP_EN1"]
pub type W = crate::W<u32, super::SLEEP_EN1>;
#[doc = "Register SLEEP_EN1 `reset()`'s with value 0x7fff"]
impl crate::ResetValue for super::SLEEP_EN1 {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0x7fff
}
}
#[doc = "Reader of field `clk_sys_xosc`"]
pub type CLK_SYS_XOSC_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `clk_sys_xosc`"]
pub struct CLK_SYS_XOSC_W<'a> {
w: &'a mut W,
}
impl<'a> CLK_SYS_XOSC_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 14)) | (((value as u32) & 0x01) << 14);
self.w
}
}
#[doc = "Reader of field `clk_sys_xip`"]
pub type CLK_SYS_XIP_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `clk_sys_xip`"]
pub struct CLK_SYS_XIP_W<'a> {
w: &'a mut W,
}
impl<'a> CLK_SYS_XIP_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 13)) | (((value as u32) & 0x01) << 13);
self.w
}
}
#[doc = "Reader of field `clk_sys_watchdog`"]
pub type CLK_SYS_WATCHDOG_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `clk_sys_watchdog`"]
pub struct CLK_SYS_WATCHDOG_W<'a> {
w: &'a mut W,
}
impl<'a> CLK_SYS_WATCHDOG_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 12)) | (((value as u32) & 0x01) << 12);
self.w
}
}
#[doc = "Reader of field `clk_usb_usbctrl`"]
pub type CLK_USB_USBCTRL_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `clk_usb_usbctrl`"]
pub struct CLK_USB_USBCTRL_W<'a> {
w: &'a mut W,
}
impl<'a> CLK_USB_USBCTRL_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 11)) | (((value as u32) & 0x01) << 11);
self.w
}
}
#[doc = "Reader of field `clk_sys_usbctrl`"]
pub type CLK_SYS_USBCTRL_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `clk_sys_usbctrl`"]
pub struct CLK_SYS_USBCTRL_W<'a> {
w: &'a mut W,
}
impl<'a> CLK_SYS_USBCTRL_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 10)) | (((value as u32) & 0x01) << 10);
self.w
}
}
#[doc = "Reader of field `clk_sys_uart1`"]
pub type CLK_SYS_UART1_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `clk_sys_uart1`"]
pub struct CLK_SYS_UART1_W<'a> {
w: &'a mut W,
}
impl<'a> CLK_SYS_UART1_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 9)) | (((value as u32) & 0x01) << 9);
self.w
}
}
#[doc = "Reader of field `clk_peri_uart1`"]
pub type CLK_PERI_UART1_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `clk_peri_uart1`"]
pub struct CLK_PERI_UART1_W<'a> {
w: &'a mut W,
}
impl<'a> CLK_PERI_UART1_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8);
self.w
}
}
#[doc = "Reader of field `clk_sys_uart0`"]
pub type CLK_SYS_UART0_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `clk_sys_uart0`"]
pub struct CLK_SYS_UART0_W<'a> {
w: &'a mut W,
}
impl<'a> CLK_SYS_UART0_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 7)) | (((value as u32) & 0x01) << 7);
self.w
}
}
#[doc = "Reader of field `clk_peri_uart0`"]
pub type CLK_PERI_UART0_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `clk_peri_uart0`"]
pub struct CLK_PERI_UART0_W<'a> {
w: &'a mut W,
}
impl<'a> CLK_PERI_UART0_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 6)) | (((value as u32) & 0x01) << 6);
self.w
}
}
#[doc = "Reader of field `clk_sys_timer`"]
pub type CLK_SYS_TIMER_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `clk_sys_timer`"]
pub struct CLK_SYS_TIMER_W<'a> {
w: &'a mut W,
}
impl<'a> CLK_SYS_TIMER_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5);
self.w
}
}
#[doc = "Reader of field `clk_sys_tbman`"]
pub type CLK_SYS_TBMAN_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `clk_sys_tbman`"]
pub struct CLK_SYS_TBMAN_W<'a> {
w: &'a mut W,
}
impl<'a> CLK_SYS_TBMAN_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4);
self.w
}
}
#[doc = "Reader of field `clk_sys_sysinfo`"]
pub type CLK_SYS_SYSINFO_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `clk_sys_sysinfo`"]
pub struct CLK_SYS_SYSINFO_W<'a> {
w: &'a mut W,
}
impl<'a> CLK_SYS_SYSINFO_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3);
self.w
}
}
#[doc = "Reader of field `clk_sys_syscfg`"]
pub type CLK_SYS_SYSCFG_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `clk_sys_syscfg`"]
pub struct CLK_SYS_SYSCFG_W<'a> {
w: &'a mut W,
}
impl<'a> CLK_SYS_SYSCFG_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2);
self.w
}
}
#[doc = "Reader of field `clk_sys_sram5`"]
pub type CLK_SYS_SRAM5_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `clk_sys_sram5`"]
pub struct CLK_SYS_SRAM5_W<'a> {
w: &'a mut W,
}
impl<'a> CLK_SYS_SRAM5_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1);
self.w
}
}
#[doc = "Reader of field `clk_sys_sram4`"]
pub type CLK_SYS_SRAM4_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `clk_sys_sram4`"]
pub struct CLK_SYS_SRAM4_W<'a> {
w: &'a mut W,
}
impl<'a> CLK_SYS_SRAM4_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01);
self.w
}
}
impl R {
#[doc = "Bit 14"]
#[inline(always)]
pub fn clk_sys_xosc(&self) -> CLK_SYS_XOSC_R {
CLK_SYS_XOSC_R::new(((self.bits >> 14) & 0x01) != 0)
}
#[doc = "Bit 13"]
#[inline(always)]
pub fn clk_sys_xip(&self) -> CLK_SYS_XIP_R {
CLK_SYS_XIP_R::new(((self.bits >> 13) & 0x01) != 0)
}
#[doc = "Bit 12"]
#[inline(always)]
pub fn clk_sys_watchdog(&self) -> CLK_SYS_WATCHDOG_R {
CLK_SYS_WATCHDOG_R::new(((self.bits >> 12) & 0x01) != 0)
}
#[doc = "Bit 11"]
#[inline(always)]
pub fn clk_usb_usbctrl(&self) -> CLK_USB_USBCTRL_R {
CLK_USB_USBCTRL_R::new(((self.bits >> 11) & 0x01) != 0)
}
#[doc = "Bit 10"]
#[inline(always)]
pub fn clk_sys_usbctrl(&self) -> CLK_SYS_USBCTRL_R {
CLK_SYS_USBCTRL_R::new(((self.bits >> 10) & 0x01) != 0)
}
#[doc = "Bit 9"]
#[inline(always)]
pub fn clk_sys_uart1(&self) -> CLK_SYS_UART1_R {
CLK_SYS_UART1_R::new(((self.bits >> 9) & 0x01) != 0)
}
#[doc = "Bit 8"]
#[inline(always)]
pub fn clk_peri_uart1(&self) -> CLK_PERI_UART1_R {
CLK_PERI_UART1_R::new(((self.bits >> 8) & 0x01) != 0)
}
#[doc = "Bit 7"]
#[inline(always)]
pub fn clk_sys_uart0(&self) -> CLK_SYS_UART0_R {
CLK_SYS_UART0_R::new(((self.bits >> 7) & 0x01) != 0)
}
#[doc = "Bit 6"]
#[inline(always)]
pub fn clk_peri_uart0(&self) -> CLK_PERI_UART0_R {
CLK_PERI_UART0_R::new(((self.bits >> 6) & 0x01) != 0)
}
#[doc = "Bit 5"]
#[inline(always)]
pub fn clk_sys_timer(&self) -> CLK_SYS_TIMER_R {
CLK_SYS_TIMER_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 4"]
#[inline(always)]
pub fn clk_sys_tbman(&self) -> CLK_SYS_TBMAN_R {
CLK_SYS_TBMAN_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 3"]
#[inline(always)]
pub fn clk_sys_sysinfo(&self) -> CLK_SYS_SYSINFO_R {
CLK_SYS_SYSINFO_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 2"]
#[inline(always)]
pub fn clk_sys_syscfg(&self) -> CLK_SYS_SYSCFG_R {
CLK_SYS_SYSCFG_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 1"]
#[inline(always)]
pub fn clk_sys_sram5(&self) -> CLK_SYS_SRAM5_R {
CLK_SYS_SRAM5_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 0"]
#[inline(always)]
pub fn clk_sys_sram4(&self) -> CLK_SYS_SRAM4_R {
CLK_SYS_SRAM4_R::new((self.bits & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 14"]
#[inline(always)]
pub fn clk_sys_xosc(&mut self) -> CLK_SYS_XOSC_W {
CLK_SYS_XOSC_W { w: self }
}
#[doc = "Bit 13"]
#[inline(always)]
pub fn clk_sys_xip(&mut self) -> CLK_SYS_XIP_W {
CLK_SYS_XIP_W { w: self }
}
#[doc = "Bit 12"]
#[inline(always)]
pub fn clk_sys_watchdog(&mut self) -> CLK_SYS_WATCHDOG_W {
CLK_SYS_WATCHDOG_W { w: self }
}
#[doc = "Bit 11"]
#[inline(always)]
pub fn clk_usb_usbctrl(&mut self) -> CLK_USB_USBCTRL_W {
CLK_USB_USBCTRL_W { w: self }
}
#[doc = "Bit 10"]
#[inline(always)]
pub fn clk_sys_usbctrl(&mut self) -> CLK_SYS_USBCTRL_W {
CLK_SYS_USBCTRL_W { w: self }
}
#[doc = "Bit 9"]
#[inline(always)]
pub fn clk_sys_uart1(&mut self) -> CLK_SYS_UART1_W {
CLK_SYS_UART1_W { w: self }
}
#[doc = "Bit 8"]
#[inline(always)]
pub fn clk_peri_uart1(&mut self) -> CLK_PERI_UART1_W {
CLK_PERI_UART1_W { w: self }
}
#[doc = "Bit 7"]
#[inline(always)]
pub fn clk_sys_uart0(&mut self) -> CLK_SYS_UART0_W {
CLK_SYS_UART0_W { w: self }
}
#[doc = "Bit 6"]
#[inline(always)]
pub fn clk_peri_uart0(&mut self) -> CLK_PERI_UART0_W {
CLK_PERI_UART0_W { w: self }
}
#[doc = "Bit 5"]
#[inline(always)]
pub fn clk_sys_timer(&mut self) -> CLK_SYS_TIMER_W {
CLK_SYS_TIMER_W { w: self }
}
#[doc = "Bit 4"]
#[inline(always)]
pub fn clk_sys_tbman(&mut self) -> CLK_SYS_TBMAN_W {
CLK_SYS_TBMAN_W { w: self }
}
#[doc = "Bit 3"]
#[inline(always)]
pub fn clk_sys_sysinfo(&mut self) -> CLK_SYS_SYSINFO_W {
CLK_SYS_SYSINFO_W { w: self }
}
#[doc = "Bit 2"]
#[inline(always)]
pub fn clk_sys_syscfg(&mut self) -> CLK_SYS_SYSCFG_W {
CLK_SYS_SYSCFG_W { w: self }
}
#[doc = "Bit 1"]
#[inline(always)]
pub fn clk_sys_sram5(&mut self) -> CLK_SYS_SRAM5_W {
CLK_SYS_SRAM5_W { w: self }
}
#[doc = "Bit 0"]
#[inline(always)]
pub fn clk_sys_sram4(&mut self) -> CLK_SYS_SRAM4_W {
CLK_SYS_SRAM4_W { w: self }
}
}
|
use std::error::Error;
use cashier_server::{config::Config, services};
#[actix_rt::main]
async fn main() -> Result<(), Box<dyn Error>> {
env_logger::init();
let config = Config::from_env()?;
match config {
Config::Init(init_config) => services::init::init(&init_config).await?,
Config::Start(start_config) => services::start::start(&start_config).await?,
}
Ok(())
}
|
#[cfg(feature = "libm")]
mod libm_math {
#[inline(always)]
pub(crate) fn abs(f: f64) -> f64 {
libm::fabs(f)
}
#[inline(always)]
pub(crate) fn acos_approx(f: f64) -> f64 {
libm::acos(f.clamp(-1.0, 1.0))
}
#[inline(always)]
pub(crate) fn asin_clamped(f: f64) -> f64 {
libm::asin(f.clamp(-1.0, 1.0))
}
#[inline(always)]
pub(crate) fn atan2(f: f64, other: f64) -> f64 {
libm::atan2(f, other)
}
#[inline(always)]
pub(crate) fn sin(f: f64) -> f64 {
libm::sin(f)
}
#[inline(always)]
pub(crate) fn sin_cos(f: f64) -> (f64, f64) {
libm::sincos(f)
}
#[inline(always)]
pub(crate) fn tan(f: f64) -> f64 {
libm::tan(f)
}
#[inline(always)]
pub(crate) fn sqrt(f: f64) -> f64 {
libm::sqrt(f)
}
#[inline(always)]
pub(crate) fn copysign(f: f64, sign: f64) -> f64 {
libm::copysign(f, sign)
}
#[inline(always)]
pub(crate) fn signum(f: f64) -> f64 {
if f.is_nan() {
f64::NAN
} else {
copysign(1.0, f)
}
}
#[inline(always)]
pub(crate) fn round(f: f64) -> f64 {
libm::round(f)
}
#[inline(always)]
pub(crate) fn trunc(f: f64) -> f64 {
libm::trunc(f)
}
#[inline(always)]
pub(crate) fn ceil(f: f64) -> f64 {
libm::ceil(f)
}
#[inline(always)]
pub(crate) fn floor(f: f64) -> f64 {
libm::floor(f)
}
#[inline(always)]
pub(crate) fn exp(f: f64) -> f64 {
libm::exp(f)
}
#[inline(always)]
pub(crate) fn powf(f: f64, n: f64) -> f64 {
libm::pow(f, n)
}
#[inline(always)]
pub(crate) fn mul_add(a: f64, b: f64, c: f64) -> f64 {
libm::fma(a, b, c)
}
#[inline]
pub fn div_euclid(a: f64, b: f64) -> f64 {
// Based on https://doc.rust-lang.org/src/std/f64.rs.html#293
let q = libm::trunc(a / b);
if a % b < 0.0 {
return if b > 0.0 { q - 1.0 } else { q + 1.0 };
}
q
}
#[inline]
pub fn rem_euclid(a: f64, b: f64) -> f64 {
let r = a % b;
if r < 0.0 {
r + abs(b)
} else {
r
}
}
}
#[cfg(not(feature = "libm"))]
mod std_math {
#[inline(always)]
pub(crate) fn abs(f: f64) -> f64 {
f64::abs(f)
}
#[inline(always)]
pub(crate) fn acos_approx(f: f64) -> f64 {
f64::acos(f64::clamp(f, -1.0, 1.0))
}
#[inline(always)]
pub(crate) fn asin_clamped(f: f64) -> f64 {
f64::asin(f64::clamp(f, -1.0, 1.0))
}
#[inline(always)]
pub(crate) fn atan2(f: f64, other: f64) -> f64 {
f64::atan2(f, other)
}
#[inline(always)]
pub(crate) fn sin(f: f64) -> f64 {
f64::sin(f)
}
#[inline(always)]
pub(crate) fn sin_cos(f: f64) -> (f64, f64) {
f64::sin_cos(f)
}
#[inline(always)]
pub(crate) fn tan(f: f64) -> f64 {
f64::tan(f)
}
#[inline(always)]
pub(crate) fn sqrt(f: f64) -> f64 {
f64::sqrt(f)
}
#[inline(always)]
pub(crate) fn copysign(f: f64, sign: f64) -> f64 {
f64::copysign(f, sign)
}
#[inline(always)]
pub(crate) fn signum(f: f64) -> f64 {
f64::signum(f)
}
#[inline(always)]
pub(crate) fn round(f: f64) -> f64 {
f64::round(f)
}
#[inline(always)]
pub(crate) fn trunc(f: f64) -> f64 {
f64::trunc(f)
}
#[inline(always)]
pub(crate) fn ceil(f: f64) -> f64 {
f64::ceil(f)
}
#[inline(always)]
pub(crate) fn floor(f: f64) -> f64 {
f64::floor(f)
}
#[inline(always)]
pub(crate) fn exp(f: f64) -> f64 {
f64::exp(f)
}
#[inline(always)]
pub(crate) fn powf(f: f64, n: f64) -> f64 {
f64::powf(f, n)
}
#[inline(always)]
pub(crate) fn mul_add(a: f64, b: f64, c: f64) -> f64 {
f64::mul_add(a, b, c)
}
#[inline]
pub fn div_euclid(a: f64, b: f64) -> f64 {
f64::div_euclid(a, b)
}
#[inline]
pub fn rem_euclid(a: f64, b: f64) -> f64 {
f64::rem_euclid(a, b)
}
}
#[cfg(feature = "libm")]
pub(crate) use libm_math::*;
#[cfg(not(feature = "libm"))]
pub(crate) use std_math::*;
|
pub const HANGEUL_OFFSET: u32 = 0xAC00; // 44032
pub const SYLLABLE_START: u32 = 0xAC00;
pub const SYLLABLE_END: u32 = 0xD7A3;
pub const CHOSEONG_COUNT: u32 = 588;
pub const JUNGSEONG_COUNT: u32 = 28;
pub const JAMO_START: u32 = 0x1100;
pub const JAMO_END: u32 = 0x11FF;
pub const COMPATIBLE_JAMO_START: u32 = 0x3131;
pub const COMPATIBLE_JAMO_END: u32 = 0x318E;
// lead/first chars
pub const CHOSEONG_START: u32 = 0x1100;
pub const CHOSEONG_END: u32 = 0x1112;
pub const COMPAT_CHOSEONG_START: u32 = 0x3131;
pub const COMPAT_CHOSEONG_END: u32 = 0x314E;
// middle chars / vowels
pub const JUNGSEONG_START: u32 = 0x1161;
pub const JUNGSEONG_END: u32 = 0x1175;
pub const COMPAT_JUNGSEONG_START: u32 = 0x314F;
pub const COMPAT_JUNGSEONG_END: u32 = 0x3163;
// tail/bottom/end chars
pub const JONGSEONG_START: u32 = 0x11A8;
pub const JONGSEONG_END: u32 = 0x11C2;
pub const COMPAT_JONGSEONG_START: u32 = 0x3165;
pub const COMPAT_JONGSEONG_END: u32 = 0x318E;
|
extern crate unterflow_protocol;
use std::env;
use std::net::TcpStream;
use unterflow_protocol::{RequestResponseMessage, TransportMessage};
use unterflow_protocol::io::{FromBytes, FromData, ToBytes, ToData};
use unterflow_protocol::message::{CREATE_STATE, TaskEvent};
use unterflow_protocol::sbe::{EventType, ExecuteCommandRequest};
fn main() {
let broker_address = env::args().nth(1).unwrap_or_else(
|| "localhost:51015".to_string(),
);
let mut stream = TcpStream::connect(&broker_address).expect(&format!("Failed to connect to broker {}", broker_address));
println!("Connected to broker {}", broker_address);
let event = TaskEvent {
state: CREATE_STATE.into(),
lock_owner: "foo".into(),
retries: 3,
..Default::default()
};
let command = event.to_data().expect("Failed to convert event");
let message = ExecuteCommandRequest {
topic_name: "default_topic".into(),
partition_id: 0,
position: 0,
key: 0,
event_type: EventType::TaskEvent,
command,
};
let request = TransportMessage::request(1, message);
request.to_bytes(&mut stream).expect(
"Failed to send request",
);
let response = TransportMessage::from_bytes(&mut stream).expect("Failed to read response");
if let TransportMessage::RequestResponse(response) = response {
if let RequestResponseMessage::ExecuteCommandResponse(ref message) = *response.message() {
let task = TaskEvent::from_data(message).expect("Failed to read task event");
println!("{:#?}", task);
} else {
panic!("Unexpected response message {:?}", response.message());
}
} else {
panic!("Unexpected response {:?}", response);
}
}
|
// https://www.jianshu.com/p/be4f12c9ac83
fn main() {
println!("Hello, world!");
}
struct Config {
path: String,
}
impl Config {
fn new(path: String) -> Config {
Config { path }
}
fn get_path(self) -> String {
self.path
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_config() {
let path = "./Cargo.toml";
let config = Config::new(path.to_string());
assert_eq!(path, config.get_path())
}
#[test]
fn test_config_into() {
let path = "./Cargo.toml";
let config = ConfigInto::new(path);
assert_eq!(path, config.get_path());
let path = "./Cargo.toml";
let config = ConfigInto::new(path.to_string());
assert_eq!(path, config.get_path())
}
}
struct ConfigInto {
path: String,
}
impl ConfigInto {
fn new<T: Into<String>>(path: T) -> Config {
Config { path: path.into() }
}
fn get_path(self) -> String {
self.path
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.