blob_id
stringlengths 40
40
| language
stringclasses 1
value | repo_name
stringlengths 5
140
| path
stringlengths 5
183
| src_encoding
stringclasses 6
values | length_bytes
int64 12
5.32M
| score
float64 2.52
4.94
| int_score
int64 3
5
| detected_licenses
listlengths 0
47
| license_type
stringclasses 2
values | text
stringlengths 12
5.32M
| download_success
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|
ed48b0ee873b5767386070c1ecdbc3d5bf0b7fc0
|
Rust
|
AlvaroEFMota/aprendendo_rust
|
/src/structs.rs
|
UTF-8
| 4,195 | 4.09375 | 4 |
[] |
no_license
|
// Structs -- Used tp create custom data types
// Traditional struct
struct Color {
red: u8,
green: u8,
blue: u8
}
// Tuple Struct
struct ColorT(u8, u8, u8);
//Person struct
struct Person {
first_name: String,
last_name: String
}
impl Person {
// Construct person
fn new(first: &str, last: &str) -> Person {
Person {
first_name: first.to_string(),
last_name: last.to_string()
}
}
// Get full name
fn full_name(&self) -> String {
format!("{} {}", self.first_name, self.last_name)
}
// Set last name
fn set_last_name(&mut self, last: &str) {
self.last_name = last.to_string();
}
//Name to tuple
fn to_tuple(&self) -> (String, String) {
(self.first_name.to_string(), self.last_name.to_string())
}
}
struct User {
username: String,
email: String,
sing_in_count: u64,
active: bool,
}
fn build_user(username: String, email: String) -> User {
User {
username, //username: username
email, //email: email
sing_in_count: 1,
active: true,
}
}
struct PointST(i32, i32, i32); //struct Tuple
struct ColorST(i32, i32, i32);
#[derive(Debug)] // Used to show when we use {:?} in println!
struct Rectangle {
width: i32,
height: i32,
}
fn area(rectangle: &Rectangle) -> i32 {
rectangle.width*rectangle.height
}
impl Rectangle {
fn area(&self) -> i32 { // The &self parameter is like &Rectangle parameter workin almost like the area function above
self.width * self.height
}
fn can_hold(&self, rectangle: &Rectangle) -> bool {
if rectangle.width < self.width && rectangle.height < self.height {
return true
}
false
}
fn square(size: i32) -> Rectangle { // We are passing the Rectangle and the ownership as a return
Rectangle{
width: size,
height: size,
}
}
}
pub fn run(){
// Traditional struct
let mut c = Color {
red: 255,
green: 0,
blue: 0
};
c.red = 200;
println!("Color: {} {} {}", c.red, c.green, c.blue);
//Tuple struct
let mut c1 = ColorT(255,0,0);
c1.1 = 35;
println!("ColorT: {} {} {}", c1.0, c1.1, c1.2);
// Using person struct
let mut p = Person::new("John", "Doe");
println!("Person: {}", p.full_name());
p.set_last_name("Williams");
println!("Person: {}", p.full_name());
println!("Person tuple: {:?}", p.to_tuple());
let mut user = User{
username: String::from("Álvaro E. F. Mota"),
email: String::from("[email protected]"),
sing_in_count: 1,
active: true,
};
println!("user: [{}], [{}], [{}], [{}]", user.username, user.email, user.sing_in_count,user.active);
user.username = String::from("Álvaro Ernani Fonseca Mota");
println!("user: [{}], [{}], [{}], [{}]", user.username, user.email, user.sing_in_count,user.active);
let user1 = build_user(String::from("Laplace"), String::from("[email protected]"));
println!("user1: [{}], [{}], [{}], [{}]", user1.username, user1.email, user1.sing_in_count,user1.active);
let user2 = User {
username: String::from("Laplace Lisert"),
..user1
};
println!("user2: [{}], [{}], [{}], [{}]", user2.username, user2.email, user2.sing_in_count,user2.active);
let black = ColorST(0, 0, 0);// The type Color_st is different from Point_st
let origin = PointST(0, 0, 0);
println!("black: {},{},{} origin: {},{},{}", black.0, black.1, black.2, origin.0, origin.1, origin.2);
let rect = Rectangle{
width: 8,
height: 20,
};
let rect_area = area(&rect);
println!("1) rect: {:?}", rect); // Only avaliable when use the #[derive(Debug)] above Rectangle struct
println!("2) rect: {:#?}", rect);
println!("rect_area: {}", rect_area);
println!("method area: {}", rect.area()); // Calling the method area of Rectangle [5-13]
let rect2 = Rectangle{
width: 10,
height: 25,
};
println!("can_hold?: {}", rect2.can_hold(&rect)); // [5-15]
let rect3 = Rectangle::square(10);
println!("square rectangle: {:?}", rect3);
}
| true |
e96409ad660732ccf9c54404477b82d4167d3e68
|
Rust
|
Chaosbit/amethyst
|
/src/app.rs
|
UTF-8
| 11,024 | 2.671875 | 3 |
[
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] |
permissive
|
//! The core engine framework.
use std::sync::Arc;
use input::InputHandler;
use rayon::ThreadPool;
use renderer::Config as DisplayConfig;
use renderer::PipelineBuilder;
use shred::{Resource, ResourceId};
#[cfg(feature = "profiler")]
use thread_profiler::{register_thread_with_profiler, write_profile};
use winit::{Event, EventsLoop};
use assets::{Asset, Loader, Store};
use ecs::{Component, Dispatcher, DispatcherBuilder, System, World};
use engine::Engine;
use error::{Error, Result};
use state::{State, StateMachine};
use timing::{Stopwatch, Time};
/// User-friendly facade for building games. Manages main loop.
#[derive(Derivative)]
#[derivative(Debug)]
pub struct Application<'a, 'b> {
/// The `engine` struct, holding world and thread pool.
#[derivative(Debug = "ignore")]
pub engine: Engine,
#[derivative(Debug = "ignore")]
dispatcher: Dispatcher<'a, 'b>,
#[derivative(Debug = "ignore")]
events: EventsLoop,
states: StateMachine<'a>,
time: Time,
timer: Stopwatch,
}
impl<'a, 'b> Application<'a, 'b> {
/// Creates a new Application with the given initial game state.
pub fn new<S: State + 'a>(initial_state: S) -> Result<Application<'a, 'b>> {
ApplicationBuilder::new(initial_state)?.build()
}
/// Builds a new Application with the given settings.
pub fn build<S>(initial_state: S) -> Result<ApplicationBuilder<'a, 'b, S>>
where
S: State + 'a,
{
ApplicationBuilder::new(initial_state)
}
/// Starts the application and manages the game loop.
pub fn run(&mut self) {
self.initialize();
while self.states.is_running() {
self.timer.restart();
self.advance_frame();
self.timer.stop();
self.time.delta_time = self.timer.elapsed();
}
self.shutdown();
}
/// Sets up the application.
fn initialize(&mut self) {
#[cfg(feature = "profiler")]
profile_scope!("initialize");
self.engine.world.add_resource(self.time.clone());
self.states.start(&mut self.engine);
}
/// Advances the game world by one tick.
fn advance_frame(&mut self) {
{
let mut time = self.engine.world.write_resource::<Time>();
time.delta_time = self.time.delta_time;
time.fixed_step = self.time.fixed_step;
time.last_fixed_update = self.time.last_fixed_update;
}
{
let engine = &mut self.engine;
let states = &mut self.states;
if engine.world.res.has_value(
ResourceId::new::<InputHandler>(),
)
{
engine
.world
.write_resource::<InputHandler>()
.advance_frame();
}
#[cfg(feature = "profiler")]
profile_scope!("handle_event");
self.events.poll_events(|event| {
if engine.world.res.has_value(
ResourceId::new::<InputHandler>(),
)
{
let mut input = engine.world.write_resource::<InputHandler>();
if let Event::WindowEvent { ref event, .. } = event {
input.send_event(&event);
}
}
states.handle_event(engine, event);
});
}
{
#[cfg(feature = "profiler")]
profile_scope!("fixed_update");
if self.time.last_fixed_update.elapsed() >= self.time.fixed_step {
self.states.fixed_update(&mut self.engine);
self.time.last_fixed_update += self.time.fixed_step;
}
#[cfg(feature = "profiler")]
profile_scope!("update");
self.states.update(&mut self.engine);
}
#[cfg(feature = "profiler")]
profile_scope!("dispatch");
self.dispatcher.dispatch(&mut self.engine.world.res);
#[cfg(feature="profiler")]
profile_scope!("maintain");
self.engine.world.maintain();
}
/// Cleans up after the quit signal is received.
fn shutdown(&mut self) {
// Placeholder.
}
}
#[cfg(feature = "profiler")]
impl<'a, 'b> Drop for Application<'a, 'b> {
fn drop(&mut self) {
// TODO: Specify filename in config.
let path = format!("{}/thread_profile.json", env!("CARGO_MANIFEST_DIR"));
write_profile(path.as_str());
}
}
/// Helper builder for Applications.
pub struct ApplicationBuilder<'a, 'b, T: State + 'a> {
// config: Config,
disp_builder: DispatcherBuilder<'a, 'b>,
initial_state: T,
world: World,
pool: Arc<ThreadPool>,
/// Allows to create `RenderSystem`
// TODO: Come up with something clever
pub events: EventsLoop,
}
impl<'a, 'b, T: State + 'a> ApplicationBuilder<'a, 'b, T> {
/// Creates a new ApplicationBuilder with the given initial game state and
/// display configuration.
pub fn new(initial_state: T) -> Result<Self> {
use num_cpus;
use rayon::Configuration;
let num_cores = num_cpus::get();
let cfg = Configuration::new().num_threads(num_cores);
let pool = ThreadPool::new(cfg).map(|p| Arc::new(p)).map_err(|_| {
Error::Application
})?;
let mut world = World::new();
let base_path = format!("{}/resources", env!("CARGO_MANIFEST_DIR"));
world.add_resource(Loader::new(base_path, pool.clone()));
Ok(ApplicationBuilder {
disp_builder: DispatcherBuilder::new(),
initial_state: initial_state,
world: world,
events: EventsLoop::new(),
pool: pool,
})
}
/// Registers a given component type.
pub fn register<C: Component>(mut self) -> Self {
self.world.register::<C>();
self
}
/// Adds an ECS resource which can be accessed from systems.
pub fn add_resource<R>(mut self, res: R) -> Self
where
R: Resource,
{
self.world.add_resource(res);
self
}
/// Inserts a barrier which assures that all systems added before the
/// barrier are executed before the ones after this barrier.
///
/// Does nothing if there were no systems added since the last call to
/// `add_barrier()`. Thread-local systems are not affected by barriers;
/// they're always executed at the end.
pub fn add_barrier(mut self) -> Self {
self.disp_builder = self.disp_builder.add_barrier();
self
}
/// Adds a given system `sys`, assigns it the string identifier `name`,
/// and marks it dependent on systems `dep`.
/// Note: all dependencies should be added before you add depending system
/// If you want to register systems which can not be specified as dependencies,
/// you can use "" as their name, which will not panic (using another name twice will).
pub fn with<S>(mut self, sys: S, name: &str, dep: &[&str]) -> Self
where
for<'c> S: System<'c> + Send + 'a + 'b,
{
self.disp_builder = self.disp_builder.add(sys, name, dep);
self
}
/// Adds a given thread-local system `sys` to the Application.
///
/// All thread-local systems are executed sequentially after all
/// non-thread-local systems.
pub fn with_thread_local<S>(mut self, sys: S) -> Self
where
for<'c> S: System<'c> + 'a + 'b,
{
self.disp_builder = self.disp_builder.add_thread_local(sys);
self
}
/// Automatically registers components, adds resources and the rendering system.
pub fn with_renderer(
mut self,
pipe: PipelineBuilder,
config: Option<DisplayConfig>,
) -> Result<Self> {
use ecs::SystemExt;
use ecs::rendering::RenderSystem;
let render_sys = RenderSystem::build((&self.events, pipe, config), &mut self.world)?;
self = self.with_thread_local(render_sys);
Ok(
self.register_mesh_asset()
.register_texture_asset()
.register_material_not_yet_asset(),
)
}
/// Add asset loader to resources
pub fn add_store<I, S>(self, name: I, store: S) -> Self
where
I: Into<String>,
S: Store + Send + Sync + 'static,
{
{
let mut loader = self.world.write_resource::<Loader>();
loader.add_store(name, store);
}
self
}
/// Register new context within the loader
pub fn register_asset<A, F>(mut self, make_context: F) -> Self
where
A: Component + Asset + Clone + Send + Sync + 'static,
F: FnOnce(&mut World) -> A::Context,
{
use assets::AssetFuture;
use specs::common::{Merge, Errors};
self.world.register::<A>();
self.world.register::<AssetFuture<A>>();
self.world.add_resource(Errors::new());
self = self.with(Merge::<AssetFuture<A>>::new(), "", &[]);
{
let context = make_context(&mut self.world);
let mut loader = self.world.write_resource::<Loader>();
loader.register(context);
}
self
}
/// Builds the Application and returns the result.
pub fn build(self) -> Result<Application<'a, 'b>> {
#[cfg(feature = "profiler")] register_thread_with_profiler("Main".into());
#[cfg(feature = "profiler")]
profile_scope!("new");
Ok(Application {
engine: Engine::new(self.pool.clone(), self.world),
// config: self.config,
states: StateMachine::new(self.initial_state),
events: self.events,
dispatcher: self.disp_builder.with_pool(self.pool).build(),
time: Time::default(),
timer: Stopwatch::new(),
})
}
/// Register new context within the loader
fn register_mesh_asset(self) -> Self {
use ecs::rendering::{MeshComponent, MeshContext, Factory};
self.register_asset::<MeshComponent, _>(|world| {
let factory = world.read_resource::<Factory>();
MeshContext::new((&*factory).clone())
})
}
/// Register new context within the loader
fn register_material_not_yet_asset(mut self) -> Self {
use assets::AssetFuture;
use ecs::rendering::MaterialComponent;
use specs::common::Merge;
self.world.register::<MaterialComponent>();
self.world.register::<AssetFuture<MaterialComponent>>();
self = self.with(Merge::<AssetFuture<MaterialComponent>>::new(), "", &[]);
self
}
/// Register new context within the loader
fn register_texture_asset(self) -> Self {
use ecs::rendering::{TextureComponent, TextureContext, Factory};
self.register_asset::<TextureComponent, _>(|world| {
let factory = world.read_resource::<Factory>();
TextureContext::new((&*factory).clone())
})
}
}
| true |
fca77da82ad6f8fdba91bc75ee232171e6f79f13
|
Rust
|
mansdahlstrom1/hello_rust
|
/src/guess_the_number.rs
|
UTF-8
| 1,286 | 3.625 | 4 |
[] |
no_license
|
extern crate rand;
use rand::Rng;
use std::io;
use std::cmp::Ordering;
pub enum Clue {
GuessLower = -1,
Correct = 0,
GuessHigher = 1,
}
pub struct GuessingGame {
pub correct: bool,
pub latest_guess: u32,
pub guess_higher: Clue,
}
impl GuessingGame {
pub fn guess(&mut self) {
println!("Please input the magic number!");
let mut guess = String::new();
io::stdin()
.read_line(&mut guess)
.expect("Failed to read line");
println!("you guessed {}", guess);
let guess: u32 = guess
.trim()
.parse()
.expect("Something went wrong");
self.latest_guess = guess;
let secret_number = rand::thread_rng().gen_range(1, 10);
println!("The secret number is {}", secret_number);
match guess.cmp(&secret_number) {
Ordering::Less => {
println!("Guess higher!");
self.guess_higher = Clue::GuessHigher;
self.correct = false;
},
Ordering::Greater => {
println!("Guess lower");
self.guess_higher = Clue::GuessLower;
self.correct = false;
},
Ordering::Equal => {
println!("Correct");
self.guess_higher = Clue::Correct;
self.correct = true;
},
}
}
}
| true |
5cb0b5867343fbc0745bb029d9de44974b2524e0
|
Rust
|
nwoeanhinnogaehr/blocker
|
/src/lib.rs
|
UTF-8
| 3,967 | 3.375 | 3 |
[
"MIT"
] |
permissive
|
use std::sync::{Mutex, Condvar};
use std::ops::{Deref, Drop};
use std::mem;
pub struct Blocker<'a, T: 'a> {
data: &'a T,
ref_count: Box<usize>,
mutex: Mutex<()>,
cond: Condvar,
}
impl<'a, T> Blocker<'a, T> {
pub fn new(data: &'a T) -> Blocker<'a, T> {
Blocker {
data,
ref_count: Box::new(0),
mutex: Mutex::new(()),
cond: Condvar::new(),
}
}
pub fn get(&self) -> Blockref<T> {
unsafe {
Blockref::new(
self.data,
mem::transmute(&*self.ref_count),
&self.mutex,
&self.cond,
)
}
}
}
impl<'a, T> Drop for Blocker<'a, T> {
fn drop(&mut self) {
let mut lock = self.mutex.lock().unwrap();
loop {
lock = self.cond.wait(lock).unwrap();
if *self.ref_count == 0 {
break;
}
}
}
}
pub struct Blockref<T> {
data: *const T,
ref_count: *mut usize,
mutex: *const Mutex<()>,
cond: *const Condvar,
}
impl<T> Blockref<T> {
fn new(
data: *const T,
ref_count: *mut usize,
mutex: *const Mutex<()>,
cond: *const Condvar,
) -> Blockref<T> {
unsafe {
let _lock = (*mutex).lock().unwrap();
*ref_count += 1;
}
Blockref {
data,
ref_count,
mutex,
cond,
}
}
}
impl<T> Drop for Blockref<T> {
fn drop(&mut self) {
unsafe {
let _lock = (*self.mutex).lock().unwrap();
*self.ref_count -= 1;
(*self.cond).notify_one();
}
}
}
impl<T> Deref for Blockref<T> {
type Target = T;
fn deref(&self) -> &T {
return unsafe { mem::transmute(self.data) };
}
}
unsafe impl<T> Sync for Blockref<T> {}
unsafe impl<T> Send for Blockref<T> {}
#[test]
fn test_basic() {
use std::thread;
let x = 5;
let y = Blocker::new(&x);
let z = y.get();
thread::spawn(move || {
thread::sleep_ms(1000);
println!("{}", *z);
});
}
#[derive(Debug)]
struct Test {
x: usize,
}
impl Drop for Test {
fn drop(&mut self) {
self.x = 0;
}
}
#[test]
fn test_multi_explicit_drop() {
use std::thread;
let x = Test { x: 5 };
let y = Blocker::new(&x);
let z = y.get();
let w = y.get();
let v = y.get();
thread::spawn(move || {
thread::sleep_ms(1000);
println!("z{:?}", *z);
});
thread::spawn(move || {
thread::sleep_ms(500);
println!("w{:?}", *w);
});
thread::spawn(move || {
thread::sleep_ms(100);
println!("v{:?}", *v);
});
drop(y);
}
#[test]
fn test_multi() {
use std::thread;
let x = Test { x: 5 };
let y = Blocker::new(&x);
let z = y.get();
let w = y.get();
let v = y.get();
thread::spawn(move || {
thread::sleep_ms(1000);
println!("z{:?}", *z);
});
thread::spawn(move || {
thread::sleep_ms(500);
println!("w{:?}", *w);
});
thread::spawn(move || {
thread::sleep_ms(100);
println!("v{:?}", *v);
});
}
#[test]
fn test_race() {
use std::thread;
use std::sync::Barrier;
use std::sync::Arc;
for i in 0..1000 {
let mut x = Test { x: 5 };
let barrier = Arc::new(Barrier::new(2));
{
let y = Blocker::new(&x);
let z = y.get();
let w = y.get();
let b2 = barrier.clone();
thread::spawn(move || {
thread::sleep_ms(1);
b2.wait();
assert!(z.x == 5);
drop(z);
});
thread::spawn(move || {
thread::sleep_ms(1);
barrier.wait();
assert!(w.x == 5);
drop(w);
});
drop(y);
}
x.x = 6;
}
}
| true |
6bb00bc047bd95759a95c0fdcb9049eaff6cb9f9
|
Rust
|
Skelebot/ruxnasm
|
/src/bin/ruxnasm/argument_parser.rs
|
UTF-8
| 2,766 | 3.328125 | 3 |
[
"MIT"
] |
permissive
|
use std::{
env,
path::{Path, PathBuf},
process::exit,
};
const HELP_MESSAGE: &'static str = r#"Usage: ruxnasm [OPTIONS] INPUT OUTPUT
Options:
-h, --help Display this message
-V, --version Print version info and exit
"#;
const VERSION_MESSAGE: &'static str = concat!("ruxnasm ", env!("CARGO_PKG_VERSION"));
#[derive(Debug)]
pub struct Arguments {
input_file_path: PathBuf,
output_file_path: PathBuf,
}
impl Arguments {
pub fn input_file_path(&self) -> &Path {
&self.input_file_path
}
pub fn output_file_path(&self) -> &Path {
&self.output_file_path
}
}
pub enum Error {
NoInputProvided,
NoOutputProvided,
UnexpectedArgument { argument: String },
UnrecognizedOption { option: String },
}
pub fn parse_arguments() -> Result<Arguments, Error> {
if env::args().len() == 1 {
exit_with_help_message();
}
let mut args = env::args();
args.next();
let mut input_file_path: Option<PathBuf> = None;
let mut output_file_path: Option<PathBuf> = None;
for arg in args {
if arg.starts_with("--") {
match &arg[2..] {
"help" => exit_with_help_message(),
"version" => exit_with_version_message(),
option => {
return Err(Error::UnrecognizedOption {
option: option.to_owned(),
})
}
}
} else if arg.starts_with("-") {
for ch in arg[1..].chars() {
match ch {
'h' => exit_with_help_message(),
'V' => exit_with_version_message(),
option => {
return Err(Error::UnrecognizedOption {
option: option.to_string(),
})
}
}
}
} else {
if input_file_path.is_none() {
input_file_path = Some(arg.into());
} else if output_file_path.is_none() {
output_file_path = Some(arg.into());
} else {
return Err(Error::UnexpectedArgument {
argument: arg.to_owned(),
});
}
}
}
match (input_file_path, output_file_path) {
(Some(input_file_path), Some(output_file_path)) => Ok(Arguments {
input_file_path,
output_file_path,
}),
(None, _) => Err(Error::NoInputProvided),
(_, None) => Err(Error::NoOutputProvided),
}
}
fn exit_with_help_message() {
println!("{}", HELP_MESSAGE);
exit(0);
}
fn exit_with_version_message() {
println!("{}", VERSION_MESSAGE);
exit(0);
}
| true |
ac6d43fc7776cb4ff4625cea7680c7ae7759fffb
|
Rust
|
vindvaki/advent-of-code-2017
|
/src/bin/day_18.rs
|
UTF-8
| 6,391 | 2.78125 | 3 |
[] |
no_license
|
extern crate aoc2017;
use aoc2017::read_fixture;
use std::collections::HashMap;
use std::collections::VecDeque;
fn main() {
let input = read_fixture();
println!("part_1: {}", part_1(input.as_str()));
println!("part_2: {}", part_2(input.as_str()));
}
fn part_1(input: &str) -> i64 {
let mut player = PlayerPart1::new(input);
while player.last_rcv.is_none() || player.last_rcv == Some(0) {
player.step();
}
player.last_rcv.unwrap()
}
fn part_2(input: &str) -> i64 {
let mut player_0 = PlayerPart2::new(input);
let mut player_1 = PlayerPart2::new(input);
player_0.registers.insert("p".to_owned(), 0);
player_1.registers.insert("p".to_owned(), 1);
let mut index_0 = -1;
let mut index_1 = -1;
let mut snd_count_1 = 0;
while player_0.index() != &index_0 || player_1.index() != &index_1 {
while !player_0.outbox.is_empty() {
player_1.inbox.push_back(player_0.outbox.pop_front().unwrap());
}
while !player_1.outbox.is_empty() {
player_0.inbox.push_back(player_1.outbox.pop_front().unwrap());
snd_count_1 += 1;
}
index_0 = player_0.index().clone();
index_1 = player_1.index().clone();
player_0.step();
player_1.step();
}
snd_count_1
}
struct PlayerPart1 {
prog: Vec<String>,
index: i64,
registers: HashMap<String, i64>,
last_snd: Option<i64>,
last_rcv: Option<i64>,
}
impl PlayerPart1 {
fn new(input: &str) -> Self {
Self {
prog: input.lines().map(|s| s.to_owned()).collect(),
index: 0,
registers: HashMap::new(),
last_snd: None,
last_rcv: None,
}
}
}
impl Player for PlayerPart1 {
fn prog(&self) -> &Vec<String> { &self.prog }
fn index(&self) -> &i64 { &self.index }
fn index_mut(&mut self) -> &mut i64 { &mut self.index }
fn registers(&self) -> &HashMap<String, i64> { &self.registers }
fn registers_mut(&mut self) -> &mut HashMap<String, i64> { &mut self.registers }
fn op_snd(&mut self, x_str: &str) {
self.last_snd = Some(x_str.parse().unwrap_or(self.val(x_str)));
}
fn op_rcv(&mut self, x_str: &str) {
let x = self.get(x_str);
if x != 0 {
self.last_rcv = self.last_snd.clone();
}
}
}
struct PlayerPart2 {
prog: Vec<String>,
index: i64,
registers: HashMap<String, i64>,
inbox: VecDeque<i64>,
outbox: VecDeque<i64>,
}
impl PlayerPart2 {
fn new(input: &str) -> Self {
Self {
prog: input.lines().map(|s| s.to_owned()).collect(),
index: 0,
registers: HashMap::new(),
inbox: VecDeque::new(),
outbox: VecDeque::new(),
}
}
}
impl Player for PlayerPart2 {
fn prog(&self) -> &Vec<String> { &self.prog }
fn index(&self) -> &i64 { &self.index }
fn index_mut(&mut self) -> &mut i64 { &mut self.index }
fn registers(&self) -> &HashMap<String, i64> { &self.registers }
fn registers_mut(&mut self) -> &mut HashMap<String, i64> { &mut self.registers }
fn op_snd(&mut self, x_str: &str) {
let x = self.val(x_str);
self.outbox.push_back(x);
}
fn op_rcv(&mut self, x_str: &str) {
let x = x_str.to_owned();
if let Some(y) = self.inbox.pop_front() {
self.registers_mut().insert(x, y);
} else {
self.index -= 1; // wait until next round
}
}
}
trait Player {
fn prog(&self) -> &Vec<String>;
fn index(&self) -> &i64;
fn index_mut(&mut self) -> &mut i64;
fn registers(&self) -> &HashMap<String, i64>;
fn registers_mut(&mut self) -> &mut HashMap<String, i64>;
fn val(&self, x: &str) -> i64 {
x.parse::<i64>().unwrap_or(self.get(x))
}
fn get(&self, x: &str) -> i64 {
self.registers().get(&x.to_owned()).unwrap_or(&0).clone()
}
fn step(&mut self) {
let index = self.index().clone();
if index < 0 || index >= self.prog().len() as i64 {
return
}
let index = self.index().clone();
let line = self.prog()[index as usize].clone();
let mut words = line.split_whitespace().map(|w| w.trim());
let op = words.next().unwrap();
let x_str = words.next().unwrap();
let y_str = words.next().unwrap_or("0");
match op {
"snd" => self.op_snd(x_str),
"rcv" => self.op_rcv(x_str),
// owned ops
"set" => self.op_set(x_str, y_str),
"add" => self.op_add(x_str, y_str),
"mul" => self.op_mul(x_str, y_str),
"mod" => self.op_mod(x_str, y_str),
"jgz" => self.op_jgz(x_str, y_str),
_ => panic!("Invalid operation `{}`", op),
};
*self.index_mut() += 1;
}
fn op_snd(&mut self, x_str: &str);
fn op_rcv(&mut self, x_str: &str);
fn op_set(&mut self, x_str: &str, y_str: &str) {
let x: String = x_str.to_owned();
let y: i64 = self.val(y_str);
self.registers_mut().insert(x, y);
}
fn op_add(&mut self, x_str: &str, y_str: &str) {
let x: String = x_str.to_owned();
let y: i64 = self.val(y_str);
let r = self.get(x_str);
self.registers_mut().insert(x, r + y);
}
fn op_mul(&mut self, x_str: &str, y_str: &str) {
let x: String = x_str.to_owned();
let y: i64 = self.val(y_str);
let r = self.get(x_str);
self.registers_mut().insert(x, r * y);
}
fn op_mod(&mut self, x_str: &str, y_str: &str) {
let x: String = x_str.to_owned();
let y: i64 = self.val(y_str);
let r = self.get(x_str);
self.registers_mut().insert(x, r % y);
}
fn op_jgz(&mut self, x_str: &str, y_str: &str) {
let x: i64 = self.val(x_str);
if x > 0 {
let y: i64 = self.val(y_str);
*self.index_mut() += y - 1;
}
}
}
#[cfg(test)]
mod tests {
#[test]
fn test_part_1() {
use part_1;
let input = "set a 1
add a 2
mul a a
mod a 5
snd a
set a 0
rcv a
jgz a -1
set a 1
jgz a -2\n";
assert_eq!(part_1(input), 4);
}
#[test]
fn test_part_2() {
use part_2;
let input = "snd 1
snd 2
snd p
rcv a
rcv b
rcv c
rcv d";
assert_eq!(part_2(input), 3);
}
}
| true |
5739afbdd02455d49da29d0685ee0ac516ef5450
|
Rust
|
sw17ch/baffles
|
/src/standard.rs
|
UTF-8
| 6,015 | 3.234375 | 3 |
[] |
no_license
|
//! This implementation of a Standard Bloom Filter is fairly basic. If
//! I'm honest, I learned how implement bloom filters at all from the
//! paper [Cache Efficient Bloom Filters for Shared Memory Machines by
//! Tim Kaler](http://tfk.mit.edu/pdf/bloom.pdf). Their basic
//! structure, however, is not that compliated.
use rand::Rng;
use rand;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::marker::PhantomData;
use std;
use bit_array::BitArray;
use index_mask::index_mask;
use hash_until::hash_until;
pub use bloom::BloomFilter;
/// A representation of a StandardBloom filter.
///
/// ```
/// use baffles::standard::*;
///
/// let expected_set_size = 1024 * 1024;
/// let bits_per_item = 16;
/// let hashing_algos = (bits_per_item as f32 * 0.7).ceil() as usize;
///
/// let mut dbb: DefaultStandardBloom<usize> = StandardBloom::new(
/// expected_set_size,
/// bits_per_item,
/// hashing_algos);
///
/// assert!(!dbb.check(&100));
/// dbb.mark(&100);
/// assert!(dbb.check(&100));
/// ```
pub struct StandardBloom<H, T> {
/// The number of hashing functions to use. This also happens to
/// be the number of bits that will be set in this block for each
/// item.
k: usize,
/// The hashing function seeds to use.
seed1: u64,
seed2: u64,
/// The bits in this block.
bits: BitArray,
/// A mask to help select a random bit index.
mask: u64,
/// The estimated set size.
n: usize,
/// The number of bits per member.
c: usize,
_p_hasher: PhantomData<H>,
_p_type: PhantomData<T>,
}
pub type DefaultStandardBloom<T> = StandardBloom<std::collections::hash_map::DefaultHasher, T>;
impl<H, T> fmt::Debug for StandardBloom<H, T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "StandardBloom {{ bits: {:?} }}", self.bits)
}
}
impl<H: Hasher + Default, T: Hash> BloomFilter<T> for StandardBloom<H, T> {
fn name(&self) -> &str {
"standard"
}
fn mark(&mut self, item: &T) {
for ix in self.hash(item) {
self.bits.set(ix);
}
}
fn check(&self, item: &T) -> bool {
self.hash(item).iter().all(|ix| self.bits.get(*ix))
}
fn set_size(&self) -> usize {
self.n
}
fn bits_per_member(&self) -> usize {
self.c
}
fn hash_count(&self) -> usize {
self.k
}
}
impl<H: Hasher + Default, T: Hash> StandardBloom<H, T> {
/// Create a new StandardBloom filter that with an approximate set
/// size of `n`, uses `c` bits per member, and `k` hashing
/// functions.
pub fn new(n: usize, c: usize, k: usize) -> Self {
let mut rng = rand::thread_rng();
StandardBloom::new_with_seeds(n, c, k, rng.gen::<u64>(), rng.gen::<u64>())
}
/// Like `new`, but allows the specification of the seeds to use
/// for the hashers.
pub fn new_with_seeds(
n: usize,
c: usize,
k: usize,
seed1: u64,
seed2: u64,
) -> StandardBloom<H, T> {
assert!(k > 0);
assert!(n * c > 0);
assert!(k <= c);
let bits = n * c;
let max_bit_index = bits - 1;
StandardBloom {
n: n,
c: c,
k: k,
seed1: seed1,
seed2: seed2,
bits: BitArray::new(bits),
mask: index_mask(max_bit_index as u64),
_p_hasher: PhantomData,
_p_type: PhantomData,
}
}
/// Create a list of bit indicies representing the bloom filter
/// hash for `item`.
fn hash(&self, item: &T) -> Vec<usize> {
let mut h1: H = Default::default();
let mut h2: H = Default::default();
h1.write_u64(self.seed1);
h2.write_u64(self.seed2);
item.hash(&mut h1);
item.hash(&mut h2);
let ih1 = h1.finish();
let ih2 = h2.finish();
let mut v = vec![0; self.k];
for i in 0..self.k {
// A. Kirsch and M. Mitzenmacher describe a way to
// generate multiple hashes without having to recompute
// every time in their paper "Less Hashing, Same
// Performance: Building a Better Bloom Filter" published
// September 2008. It's generalized below as:
//
// hi = h1 + (i * h2)
//
// Their paper identifies that this mechanism allows us to
// calculate two hashes once, and derive any number of
// hashes from those initial two without losing entropy in
// each successive hash.
//
// We generate this k_and_m hash and then test whether or
// not it's a suitable candidate for producing a random
// bit index. In order to treat all indicies fairly, the
// hash is recalculated until masking off the top bits of
// the hash produces a number that's less than or equal to
// the number of bits in the block.
// The value for the i'th hash.
let k_and_m = ih1.wrapping_add((i as u64).wrapping_mul(ih2));
// The hasher used for looping.
let mut h3: H = Default::default();
// This will be true when the hash can be used to produce
// a random bit index.
let prop = |h| (self.mask & h) <= (self.bits.width() - 1) as u64;
// This hash, when masked, will give us a usable bit
// index.
let usable_hash = hash_until(&mut h3, k_and_m, prop);
// Store the bit index into the vector.
v[i] = (self.mask & usable_hash) as usize;
}
v
}
}
#[cfg(test)]
mod tests {
use bloom::optimal_hashers;
use super::*;
#[test]
fn the_basics_work() {
let mut bb: DefaultStandardBloom<usize> =
StandardBloom::new(1024 * 1024, 16, optimal_hashers(16));
assert!(!bb.check(&100));
bb.mark(&100);
assert!(bb.check(&100));
}
}
| true |
c14191e054e06bca18c9f293a80d76410a87fe7c
|
Rust
|
nooberfsh/yellow-peach
|
/src/visit.rs
|
UTF-8
| 2,183 | 2.65625 | 3 |
[] |
no_license
|
use reacto::ast::N;
use crate::ast::*;
pub trait Visitor<'ast>: Sized {
fn visit_grammar(&mut self, n: &'ast N<Grammar>) {
walk_grammar(self, n)
}
fn visit_rule(&mut self, n: &'ast N<Rule>) {
walk_rule(self, n)
}
fn visit_named_rule_body(&mut self, n: &'ast N<NamedRuleBody>) {
walk_named_rule_body(self, n)
}
fn visit_rule_body(&mut self, n: &'ast N<RuleBody>) {
walk_rule_body(self, n)
}
fn visit_rule_element(&mut self, n: &'ast N<RuleElement>) {
walk_rule_element(self, n)
}
fn visit_quantifier(&mut self, n: &'ast N<Quantifier>) {
walk_quantifier(self, n)
}
fn visit_ident(&mut self, n: &'ast N<Ident>) {
walk_ident(self, n)
}
fn visit_attr(&mut self, n: &'ast N<Attr>) {
walk_attr(self, n)
}
}
macro_rules! walk_list {
($visitor: expr, $method: ident, $list: expr) => {
for elem in $list {
$visitor.$method(elem)
}
};
}
pub fn walk_grammar<'a, V: Visitor<'a>>(v: &mut V, n: &'a N<Grammar>) {
walk_list!(v, visit_rule, &n.rules);
}
pub fn walk_rule<'a, V: Visitor<'a>>(v: &mut V, n: &'a N<Rule>) {
walk_list!(v, visit_attr, &n.attrs);
v.visit_ident(&n.name);
match &n.kind {
RuleKind::Enum(b) => walk_list!(v, visit_named_rule_body, b),
RuleKind::Normal(b) => v.visit_rule_body(b),
}
}
pub fn walk_named_rule_body<'a, V: Visitor<'a>>(v: &mut V, n: &'a N<NamedRuleBody>) {
v.visit_ident(&n.name);
if let Some(d) = &n.body {
v.visit_rule_body(d);
}
}
pub fn walk_rule_body<'a, V: Visitor<'a>>(v: &mut V, n: &'a N<RuleBody>) {
walk_list!(v, visit_rule_element, &n.body)
}
pub fn walk_rule_element<'a, V: Visitor<'a>>(v: &mut V, n: &'a N<RuleElement>) {
if let Some(d) = &n.name {
v.visit_ident(d);
}
v.visit_ident(&n.nt);
if let Some(q) = &n.quantifier {
v.visit_quantifier(q);
}
}
pub fn walk_quantifier<'a, V: Visitor<'a>>(_v: &mut V, _n: &'a N<Quantifier>) {}
pub fn walk_ident<'a, V: Visitor<'a>>(_v: &mut V, _n: &'a N<Ident>) {}
pub fn walk_attr<'a, V: Visitor<'a>>(_v: &mut V, _n: &'a N<Attr>) {}
| true |
79383663fc2c3b4dc82b49e1045c32cb75201d3e
|
Rust
|
mancanfly-1/symbolic_rust
|
/test_rust/test1/src/a.rs
|
UTF-8
| 315 | 2.609375 | 3 |
[] |
no_license
|
#[no_mangle]
static mut AGE:u32 = 1;
#[no_mangle]
pub static Max:u32 = 12;
#[no_mangle]
pub extern fn add(x:u32, y:u32)->u32
{
// unsafe
// {
// if AGE < Max {
// AGE +=1;
// }
// }
x + y
}
// #[no_mangle]
// pub fn inc1()
// {
// let mut x = 0;
// x = 6;
// }
| true |
3391e8dcb4072ba332d47fbe385f7310089fec2f
|
Rust
|
gnoliyil/fuchsia
|
/src/virtualization/bin/vmm/device/virtio_sound/src/wire.rs
|
UTF-8
| 12,622 | 2.515625 | 3 |
[
"BSD-2-Clause"
] |
permissive
|
// Copyright 2021 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Keep all consts and type defs for completeness.
#![allow(dead_code)]
use {
iota::iota,
zerocopy::{AsBytes, FromBytes},
};
pub use zerocopy::byteorder::little_endian::{U32 as LE32, U64 as LE64};
// The following structures are adapted from:
// https://www.kraxel.org/virtio/virtio-v1.1-cs01-sound-v8.html#x1-49500014
//
// Naming conventions:
//
// - Where constants are given a name in the spec, they have the same name
// here (VIRTIO_SND_*).
//
// - Each struct defined in the spec has the same name here, with snake_case
// converted to CamelCase. For example: virtio_snd_cfg -> VirtioSndCfg.
//
// - We use type aliases to provide each control message with explicitly
// named request and response type. For example: JackInfo{Request,Response}.
//
// All struct fields use integers, even fields that are logically enums, so
// that each struct can derive AsBytes, FromBytes (we can't derive AsBytes, FromBytes from an enum
// field unless the enum covers all possible bit patterns, which isn't true
// of any the enums below).
//
// 5.14.2 Virtqueues
//
pub const CONTROLQ: u16 = 0;
pub const EVENTQ: u16 = 1;
pub const TXQ: u16 = 2;
pub const RXQ: u16 = 3;
//
// 5.14.4 Device Configuration Layout
//
#[derive(Debug, Copy, Clone, AsBytes, FromBytes)]
#[repr(C, packed)]
pub struct VirtioSndConfig {
pub jacks: LE32,
pub streams: LE32,
pub chmaps: LE32,
}
//
// 5.14.6 Device Operation
//
// Jack control request types
iota! {
pub const VIRTIO_SND_R_JACK_INFO: u32 = 1 + iota;
, VIRTIO_SND_R_JACK_REMAP
}
// PCM control request types
iota! {
pub const VIRTIO_SND_R_PCM_INFO: u32 = 0x0100 + iota;
, VIRTIO_SND_R_PCM_SET_PARAMS
, VIRTIO_SND_R_PCM_PREPARE
, VIRTIO_SND_R_PCM_RELEASE
, VIRTIO_SND_R_PCM_START
, VIRTIO_SND_R_PCM_STOP
}
// Channel map control request types
iota! {
pub const VIRTIO_SND_R_CHMAP_INFO: u32 = 0x0200 + iota;
}
// Jack event types
iota! {
pub const VIRTIO_SND_EVT_JACK_CONNECTED: u32 = 0x1000 + iota;
, VIRTIO_SND_EVT_JACK_DISCONNECTED
}
// PCM event types
iota! {
pub const VIRTIO_SND_EVT_PCM_PERIOD_ELAPSED: u32 = 0x1100 + iota;
, VIRTIO_SND_EVT_PCM_XRUN
}
// Common status codes
iota! {
pub const VIRTIO_SND_S_OK: u32 = 0x8000 + iota;
, VIRTIO_SND_S_BAD_MSG
, VIRTIO_SND_S_NOT_SUPP
, VIRTIO_SND_S_IO_ERR
}
// Data flow directions
iota! {
pub const VIRTIO_SND_D_OUTPUT: u8 = iota;
, VIRTIO_SND_D_INPUT
}
// A common header
#[derive(Debug, Copy, Clone, AsBytes, FromBytes)]
#[repr(C, packed)]
pub struct VirtioSndHdr {
pub code: LE32,
}
// An event notification
#[derive(Debug, Copy, Clone, AsBytes, FromBytes)]
#[repr(C, packed)]
pub struct VirtioSndEvent {
pub hdr: VirtioSndHdr, // .code = VIRTIO_SND_EVT_*
pub data: LE32,
}
pub type GenericRequest = VirtioSndHdr; // .code = VIRTIO_SND_R_*
pub type GenericResponse = VirtioSndHdr; // .code = VIRTIO_SND_S_*
//
// 5.14.6.1 Item Information Request
//
#[derive(Debug, Copy, Clone, AsBytes, FromBytes)]
#[repr(C, packed)]
pub struct VirtioSndQueryInfo {
pub hdr: VirtioSndHdr, // .code = VIRTIO_SND_R_*_INFO
pub start_id: LE32,
pub count: LE32,
pub size: LE32,
}
#[derive(Debug, Copy, Clone, AsBytes, FromBytes)]
#[repr(C, packed)]
pub struct VirtioSndInfo {
pub hda_fn_nid: LE32,
}
pub type GenericInfoRequest = VirtioSndQueryInfo;
pub type GenericInfoResponse = VirtioSndInfo;
//
// 5.14.6.4 Jack Control Messages
//
#[derive(Debug, Copy, Clone, AsBytes, FromBytes)]
#[repr(C, packed)]
pub struct VirtioSndJackHdr {
pub hdr: VirtioSndHdr,
pub jack_id: LE32,
}
//
// 5.14.6.4.1 VIRTIO_SND_R_JACK_INFO
//
// Supported jack features
iota! {
pub const VIRTIO_SND_JACK_F_REMAP: u32 = iota;
}
#[derive(Debug, Copy, Clone, AsBytes, FromBytes)]
#[repr(C, packed)]
pub struct VirtioSndJackInfo {
pub hdr: VirtioSndInfo,
pub features: LE32, // 1 << VIRTIO_SND_JACK_F_*
pub hda_reg_defconf: LE32,
pub hda_reg_caps: LE32,
pub connected: u8,
pub padding: [u8; 7],
}
pub type JackInfoRequest = GenericInfoRequest;
pub type JackInfoResponse = VirtioSndJackInfo;
//
// 5.14.6.4.2 VIRTIO_SND_R_JACK_REMAP
//
#[derive(Debug, Copy, Clone, AsBytes, FromBytes)]
#[repr(C, packed)]
pub struct VirtioSndJackRemap {
pub hdr: VirtioSndJackHdr, // .code = VIRTIO_SND_R_JACK_REMAP
pub association: LE32,
pub sequence: LE32,
}
pub type JackRemapRequest = VirtioSndJackRemap;
pub type JackRemapResponse = GenericResponse;
//
// 5.14.6.6 PCM Control Messages
//
#[derive(Debug, Copy, Clone, AsBytes, FromBytes)]
#[repr(C, packed)]
pub struct VirtioSndPcmHdr {
pub hdr: VirtioSndHdr,
pub stream_id: LE32,
}
//
// 5.14.6.6.2 VIRTIO_SND_R_PCM_INFO
//
// Supported PCM stream features
iota! {
pub const VIRTIO_SND_PCM_F_SHMEM_HOST: u32 = iota;
, VIRTIO_SND_PCM_F_SHMEM_GUEST
, VIRTIO_SND_PCM_F_MSG_POLLING
, VIRTIO_SND_PCM_F_EVT_SHMEM_PERIODS
, VIRTIO_SND_PCM_F_EVT_XRUNS
}
// Supported PCM sample formats
iota! {
// Analog formats (width / physical width)
pub const VIRTIO_SND_PCM_FMT_IMA_ADPCM: u8 = iota; // 4 / 4 bits
, VIRTIO_SND_PCM_FMT_MU_LAW // 8 / 8 bits
, VIRTIO_SND_PCM_FMT_A_LAW // 8 / 8 bits
, VIRTIO_SND_PCM_FMT_S8 // 8 / 8 bits
, VIRTIO_SND_PCM_FMT_U8 // 8 / 8 bits
, VIRTIO_SND_PCM_FMT_S16 // 16 / 16 bits
, VIRTIO_SND_PCM_FMT_U16 // 16 / 16 bits
, VIRTIO_SND_PCM_FMT_S18_3 // 18 / 24 bits
, VIRTIO_SND_PCM_FMT_U18_3 // 18 / 24 bits
, VIRTIO_SND_PCM_FMT_S20_3 // 20 / 24 bits
, VIRTIO_SND_PCM_FMT_U20_3 // 20 / 24 bits
, VIRTIO_SND_PCM_FMT_S24_3 // 24 / 24 bits
, VIRTIO_SND_PCM_FMT_U24_3 // 24 / 24 bits
, VIRTIO_SND_PCM_FMT_S20 // 20 / 32 bits
, VIRTIO_SND_PCM_FMT_U20 // 20 / 32 bits
, VIRTIO_SND_PCM_FMT_S24 // 24 / 32 bits
, VIRTIO_SND_PCM_FMT_U24 // 24 / 32 bits
, VIRTIO_SND_PCM_FMT_S32 // 32 / 32 bits
, VIRTIO_SND_PCM_FMT_U32 // 32 / 32 bits
, VIRTIO_SND_PCM_FMT_FLOAT // 32 / 32 bits
, VIRTIO_SND_PCM_FMT_FLOAT64 // 64 / 64 bits
// Digital formats (width / physical width)
, VIRTIO_SND_PCM_FMT_DSD_U8 // 8 / 8 bits
, VIRTIO_SND_PCM_FMT_DSD_U16 // 16 / 16 bits
, VIRTIO_SND_PCM_FMT_DSD_U32 // 32 / 32 bits
, VIRTIO_SND_PCM_FMT_IEC958_SUBFRAME // 32 / 32 bits
}
// Supported PCM frame rates
iota! {
pub const VIRTIO_SND_PCM_RATE_5512: u8 = iota;
, VIRTIO_SND_PCM_RATE_8000
, VIRTIO_SND_PCM_RATE_11025
, VIRTIO_SND_PCM_RATE_16000
, VIRTIO_SND_PCM_RATE_22050
, VIRTIO_SND_PCM_RATE_32000
, VIRTIO_SND_PCM_RATE_44100
, VIRTIO_SND_PCM_RATE_48000
, VIRTIO_SND_PCM_RATE_64000
, VIRTIO_SND_PCM_RATE_88200
, VIRTIO_SND_PCM_RATE_96000
, VIRTIO_SND_PCM_RATE_176400
, VIRTIO_SND_PCM_RATE_192000
, VIRTIO_SND_PCM_RATE_384000
}
#[derive(Debug, Copy, Clone, AsBytes, FromBytes)]
#[repr(C, packed)]
pub struct VirtioSndPcmInfo {
pub hdr: VirtioSndInfo,
pub features: LE32, // 1 << VIRTIO_SND_PCM_F_*
pub formats: LE64, // 1 << VIRTIO_SND_PCM_FMT_*
pub rates: LE64, // 1 << VIRTIO_SND_PCM_RATE_*
pub direction: u8,
pub channels_min: u8,
pub channels_max: u8,
pub padding: [u8; 5],
}
pub type PcmInfoRequest = GenericInfoRequest;
pub type PcmInfoResponse = VirtioSndPcmInfo;
//
// 5.14.6.6.3 VIRTIO_SND_R_PCM_SET_PARAMS
//
#[derive(Debug, Copy, Clone, AsBytes, FromBytes)]
#[repr(C, packed)]
pub struct VirtioSndPcmSetParams {
pub hdr: VirtioSndPcmHdr, // .hdr.code = VIRTIO_SND_R_PCM_SET_PARAMS
pub buffer_bytes: LE32,
pub period_bytes: LE32,
pub features: LE32, // 1 << VIRTIO_SND_PCM_F_*
pub channels: u8,
pub format: u8,
pub rate: u8,
pub padding: u8,
}
pub type PcmSetParamsRequest = VirtioSndPcmSetParams;
pub type PcmSetParamsResponse = GenericResponse;
//
// 5.14.6.6.4 VIRTIO_SND_R_PCM_PREPARE
// 5.14.6.6.5 VIRTIO_SND_R_PCM_RELEASE
// 5.14.6.6.6 VIRTIO_SND_R_PCM_START
// 5.14.6.6.7 VIRTIO_SND_R_PCM_STOP
//
pub type PcmPrepareRequest = VirtioSndPcmHdr;
pub type PcmPrepareResponse = GenericResponse;
pub type PcmReleaseRequest = VirtioSndPcmHdr;
pub type PcmReleaseResponse = GenericResponse;
pub type PcmStartRequest = VirtioSndPcmHdr;
pub type PcmStartResponse = GenericResponse;
pub type PcmStopRequest = VirtioSndPcmHdr;
pub type PcmStopResponse = GenericResponse;
//
// 5.14.6.8 PCM I/O Messages
//
// Header for an I/O message.
#[derive(Debug, Copy, Clone, AsBytes, FromBytes)]
#[repr(C, packed)]
pub struct VirtioSndPcmXfer {
pub stream_id: LE32,
}
// Status of an I/O message.
#[derive(Debug, Copy, Clone, AsBytes, FromBytes)]
#[repr(C, packed)]
pub struct VirtioSndPcmStatus {
pub status: LE32,
pub latency_bytes: LE32,
}
//
// 5.14.6.9.1 VIRTIO_SND_R_CHMAP_INFO
//
// Standard channel position definition
iota! {
pub const VIRTIO_SND_CHMAP_NONE: u8 = iota; // undefined
, VIRTIO_SND_CHMAP_NA // silent
, VIRTIO_SND_CHMAP_MONO // mono stream
, VIRTIO_SND_CHMAP_FL // front left
, VIRTIO_SND_CHMAP_FR // front right
, VIRTIO_SND_CHMAP_RL // rear left
, VIRTIO_SND_CHMAP_RR // rear right
, VIRTIO_SND_CHMAP_FC // front center
, VIRTIO_SND_CHMAP_LFE // low frequency (LFE)
, VIRTIO_SND_CHMAP_SL // side left
, VIRTIO_SND_CHMAP_SR // side right
, VIRTIO_SND_CHMAP_RC // rear center
, VIRTIO_SND_CHMAP_FLC // front left center
, VIRTIO_SND_CHMAP_FRC // front right center
, VIRTIO_SND_CHMAP_RLC // rear left center
, VIRTIO_SND_CHMAP_RRC // rear right center
, VIRTIO_SND_CHMAP_FLW // front left wide
, VIRTIO_SND_CHMAP_FRW // front right wide
, VIRTIO_SND_CHMAP_FLH // front left high
, VIRTIO_SND_CHMAP_FCH // front center high
, VIRTIO_SND_CHMAP_FRH // front right high
, VIRTIO_SND_CHMAP_TC // top center
, VIRTIO_SND_CHMAP_TFL // top front left
, VIRTIO_SND_CHMAP_TFR // top front right
, VIRTIO_SND_CHMAP_TFC // top front center
, VIRTIO_SND_CHMAP_TRL // top rear left
, VIRTIO_SND_CHMAP_TRR // top rear right
, VIRTIO_SND_CHMAP_TRC // top rear center
, VIRTIO_SND_CHMAP_TFLC // top front left center
, VIRTIO_SND_CHMAP_TFRC // top front right center
, VIRTIO_SND_CHMAP_TSL // top side left
, VIRTIO_SND_CHMAP_TSR // top side right
, VIRTIO_SND_CHMAP_LLFE // left LFE
, VIRTIO_SND_CHMAP_RLFE // right LFE
, VIRTIO_SND_CHMAP_BC // bottom center
, VIRTIO_SND_CHMAP_BLC // bottom left center
, VIRTIO_SND_CHMAP_BRC // bottom right center
}
// Maximum possible number of channels
pub const VIRTIO_SND_CHMAP_MAX_SIZE: usize = 18;
#[derive(Debug, Copy, Clone, AsBytes, FromBytes)]
#[repr(C, packed)]
pub struct VirtioSndChmapInfo {
pub hdr: VirtioSndInfo,
pub direction: u8,
pub channels: u8,
pub positions: [u8; VIRTIO_SND_CHMAP_MAX_SIZE],
}
pub type ChmapInfoRequest = GenericInfoRequest;
pub type ChmapInfoResponse = VirtioSndChmapInfo;
| true |
34183b22021653e9cd7538983677752cbbbca524
|
Rust
|
maxdeviant/peacock
|
/src/lib.rs
|
UTF-8
| 1,046 | 2.53125 | 3 |
[
"MIT"
] |
permissive
|
//! Peacock is a game engine for making beautiful games.
//!
//! [](https://crates.io/crates/peacock)
//! [](https://docs.rs/peacock/)
//! [](https://github.com/maxdeviant/peacock/blob/master/LICENSE)
//! [](https://travis-ci.org/maxdeviant/peacock)
//!
//! ## Installation
//! ```toml
//! [dependencies]
//! peacock = "0.0.1"
//! ```
#![warn(missing_docs)]
pub mod ecs;
pub mod error;
pub mod graphics;
pub mod input;
pub mod time;
pub mod window;
mod context;
mod fps_tracker;
mod vector2;
pub use crate::context::*;
pub use crate::error::Result;
pub(crate) use crate::fps_tracker::*;
pub use crate::vector2::*;
pub trait State {
type Context;
fn update(&mut self, ctx: &mut Context<Self::Context>) -> Result<()>;
fn draw(&mut self, ctx: &mut Context<Self::Context>, dt: f64) -> Result<()>;
}
| true |
35f21cd633c1856b781623bb89e608a695633089
|
Rust
|
ackintosh/sandbox
|
/rust/crate-lru_time_cache/benches/bench.rs
|
UTF-8
| 1,201 | 2.703125 | 3 |
[] |
no_license
|
#![feature(test)]
// ベンチマークの実行
//
// ```shell
// $ cargo +nightly bench
// ```
extern crate test;
use test::Bencher;
use lru_time_cache::LruCache;
use std::cell::RefCell;
use std::collections::HashMap;
const RANGE: usize = 32 * 1024;
const FIND_TIMES: usize = 10;
use rand::prelude::*;
// https://github.com/maidsafe/lru_time_cache/issues/143
// にあるベンチマーク
#[bench]
fn lru_time_cache_sum(b: &mut Bencher) {
let mut lru = LruCache::with_capacity(RANGE);
for i in 0..RANGE {
lru.insert(i, i);
}
let lru = RefCell::new(lru);
b.iter(|| {
let res: usize = (0..FIND_TIMES)
.map(|_| {
*lru.borrow_mut()
.get(&thread_rng().gen_range(0..RANGE))
.unwrap_or(&0)
})
.sum();
test::black_box(res);
});
}
#[bench]
fn hashmap_sum(b: &mut Bencher) {
let mut map = HashMap::new();
for i in 0..RANGE {
map.insert(i, i);
}
b.iter(|| {
let res: usize = (0..FIND_TIMES)
.map(|_| *map.get(&thread_rng().gen_range(0..RANGE)).unwrap_or(&0))
.sum();
test::black_box(res);
});
}
| true |
40013ade4ab0b626e491d79553f4964babd84492
|
Rust
|
thesnappingdog/junction-2020-gubbet-koodaa
|
/maze/src/game.rs
|
UTF-8
| 12,438 | 2.78125 | 3 |
[] |
no_license
|
use crate::custom_events::CustomEvent;
use crate::direction::Direction;
use crate::maze::{Cell, MazeGrid};
use crate::window::AppWindow;
use euclid::Vector2D;
use rand::prelude::SliceRandom;
use rand::{thread_rng, Rng};
use raqote::{Color, IntPoint};
use uuid::Uuid;
use winit::event::Event;
use winit_input_helper::WinitInputHelper;
#[derive(Debug, Clone)]
struct Player {
id: Uuid,
name: String,
color: Color,
pos: Vector2D<i32, i32>,
size: i32,
}
impl Player {
pub fn new(size: i32, pos: Vector2D<i32, i32>, name: String) -> Player {
Player {
id: Uuid::new_v4(),
color: Color::new(
255,
rand::thread_rng().gen_range(0, 255) as u8,
rand::thread_rng().gen_range(0, 255) as u8,
rand::thread_rng().gen_range(0, 255) as u8,
),
size,
pos,
name,
}
}
pub fn move_to(&mut self, cell: &Cell) {
self.pos = cell.pos()
}
}
pub struct MazeGame {
maze: MazeGrid,
camera_pos: IntPoint,
input: WinitInputHelper,
cell_size: i32,
players: Vec<Player>,
wall_padding: i32,
is_finished: bool,
winner: Option<String>,
}
impl MazeGame {
pub fn new(grid_size: i32, window: &AppWindow) -> MazeGame {
let maze = MazeGrid::new(grid_size, (0, 0), (grid_size - 1, grid_size - 1));
let (buffer_width, buffer_height) = window.size();
let wall_padding = 2;
// Just some math to get the grid fit height of window
let cell_size = ((window.size().1 as f32 - 1.05 * grid_size as f32 * wall_padding as f32)
/ (1.05 * grid_size as f32)) as i32;
let input = WinitInputHelper::new();
let players = vec![];
MazeGame {
maze,
camera_pos: IntPoint::new(
buffer_width as i32 / 2 - grid_size as i32 / 2 * cell_size,
buffer_height as i32 / 2 - grid_size as i32 / 2 * cell_size,
),
input,
cell_size,
players,
wall_padding,
is_finished: false,
winner: None,
}
}
pub fn restart(&mut self) {
let maze = MazeGrid::new(
self.maze.size(),
(0, 0),
(self.maze.size() - 1, self.maze.size() - 1),
);
let mut players = vec![];
for p in &self.players {
let mut player = p.clone();
player.pos = Vector2D::<i32, i32>::new(0, 0);
players.push(player);
}
self.maze = maze;
self.players = players;
self.is_finished = false;
self.winner = None;
}
pub fn players(&self) -> Vec<(String, Color)> {
let mut players = self
.players
.iter()
.map(|p| (p.name.clone(), p.color))
.collect::<Vec<(String, Color)>>();
players.sort_by(|a, b| a.0.cmp(&b.0));
players
}
fn add_player(&mut self, name: &str) {
if self.players.iter().find(|p| &p.name == name).is_none() {
self.players.push(Player::new(
self.cell_size / 2,
self.maze.start_pos(),
name.to_string(),
));
}
}
fn remove_player(&mut self, name: &str) {
if self.players.iter().find(|p| &p.name == name).is_some() {
let index = self.players.iter().position(|p| &p.name == name).unwrap();
self.players.remove(index);
}
}
pub fn handle_custom_events(&mut self, event: &Event<CustomEvent>) {
match event {
Event::UserEvent(event) => match event {
CustomEvent::PlayerConnected(name) => {
self.add_player(name);
println!("Player connected: {}", name);
}
CustomEvent::PlayerDisconnected(name) => {
self.remove_player(name);
println!("Player disconnected: {}", name);
}
CustomEvent::PlayerMove(name, direction) => {
if self.players.iter().find(|p| &p.name == name).is_none() {
self.add_player(name);
}
self.try_move(name, *direction);
println!("Player move: {} {:?}", name, direction);
}
},
_ => (),
}
}
pub fn handle_input(&mut self, _window: &AppWindow, input: &WinitInputHelper) {
self.input = input.clone();
}
fn try_move(&mut self, player: &str, dir: Direction) {
let grid_dir = dir.grid_dir();
let player_pos = self.get_player(player).pos;
let target_cell = self
.maze
.cell_at(player_pos.x + grid_dir.0, player_pos.y + grid_dir.1)
.cloned();
let curr_cell = self
.maze
.cell_at(player_pos.x, player_pos.y)
.unwrap()
.clone();
if let Some(new_cell) = target_cell {
if curr_cell.has_link_to(&new_cell) {
self.get_player(player).move_to(&new_cell);
if new_cell.pos().x == self.maze.end_pos().x
&& new_cell.pos().y == self.maze.end_pos().y
{
self.is_finished = true;
self.winner = Some(player.to_string());
}
}
}
}
fn get_player(&mut self, name: &str) -> &mut Player {
self.players.iter_mut().find(|p| p.name == name).unwrap()
}
pub fn winner_name(&mut self) -> Option<String> {
if let Some(winner) = self.winner.clone() {
Some(format!("{}", self.get_player(&winner).name))
} else {
None
}
}
pub fn update(&mut self, window: &mut AppWindow, _dt: f64) {
if self.is_finished {
return;
}
// Update game logic based on inputs here, then render
self.render_grid(window);
self.render_players(window);
}
fn render_players(&mut self, window: &mut AppWindow) {
// Shuffle so they are sometimes rendered in different order to show players are in same cell
self.players.shuffle(&mut thread_rng());
for player in self.players.iter() {
let start_x = self.camera_pos.x - self.maze.size() * self.wall_padding / 2
+ player.pos.x * (self.cell_size + self.wall_padding)
+ self.cell_size / 2 as i32
- player.size / 2;
let start_y = self.camera_pos.y - self.maze.size() * self.wall_padding / 2
+ player.pos.y * (self.cell_size + self.wall_padding)
+ self.cell_size / 2 as i32
- player.size / 2;
self.color_rect(
window,
start_x,
start_y,
player.size,
player.size,
player.color,
);
}
}
fn render_grid(&mut self, window: &mut AppWindow) {
for maze_y in 0..self.maze.size() {
for maze_x in 0..self.maze.size() {
if let Some(cell) = self.maze.cell_at(maze_x, maze_y) {
let start_x = self.camera_pos.x - self.maze.size() * self.wall_padding / 2
+ maze_x * (self.cell_size + self.wall_padding);
let start_y = self.camera_pos.y - self.maze.size() * self.wall_padding / 2
+ maze_y * (self.cell_size + self.wall_padding);
// Render cell
self.color_rect(
window,
start_x,
start_y,
self.cell_size,
self.cell_size,
cell.color(),
);
// Render doors
cell.available_directions().iter().for_each(|dir| {
let mut start_x = start_x;
let mut start_y = start_y;
match dir {
Direction::Up => {
if let Some(opposite) = self.maze.cell_at(maze_x, maze_y - 1) {
if cell.has_link_to(opposite) {
start_y = start_y - self.wall_padding;
self.color_rect(
window,
start_x,
start_y,
self.cell_size,
self.wall_padding,
cell.color(),
);
}
}
}
Direction::Right => {
if let Some(opposite) = self.maze.cell_at(maze_x + 1, maze_y) {
if cell.has_link_to(opposite) {
start_x = start_x + self.cell_size;
self.color_rect(
window,
start_x,
start_y,
self.wall_padding,
self.cell_size,
cell.color(),
);
}
}
}
Direction::Left => {
if let Some(opposite) = self.maze.cell_at(maze_x - 1, maze_y) {
if cell.has_link_to(opposite) {
start_x = start_x - self.wall_padding;
self.color_rect(
window,
start_x,
start_y,
self.wall_padding,
self.cell_size,
cell.color(),
);
}
}
}
Direction::Down => {
if let Some(opposite) = self.maze.cell_at(maze_x, maze_y + 1) {
if cell.has_link_to(opposite) {
start_y = start_y + self.cell_size;
self.color_rect(
window,
start_x,
start_y,
self.cell_size,
self.wall_padding,
cell.color(),
);
}
}
}
}
})
}
}
}
}
fn color_rect(
&self,
window: &mut AppWindow,
start_x: i32,
start_y: i32,
rect_width: i32,
rect_height: i32,
color: Color,
) {
let (width, height) = window.size();
let framebuffer = window.framebuffer();
for y in start_y..(start_y + rect_height) {
for x in start_x..(start_x + rect_width) {
if x < 0 || x >= width as i32 || y < 0 || y >= height as i32 {
continue;
}
let pixel_index = (y * width as i32 * 4 + x * 4) as usize;
framebuffer[pixel_index] = color.r();
framebuffer[pixel_index + 1] = color.g();
framebuffer[pixel_index + 2] = color.b();
framebuffer[pixel_index + 3] = color.a();
}
}
}
}
| true |
7a3a577fc8b45b8c1249c6447b09881628a6d71e
|
Rust
|
Dstu93/webtemplate
|
/src/web_backend.rs
|
UTF-8
| 1,512 | 2.546875 | 3 |
[] |
no_license
|
use crate::web::{WebServer, ApplicationError, HttpController, Middleware, RequestProcessor, HttpRequest, HttpResponse, HttpMethod};
use hyper::{Request, Response, Server, Body, Error, Method};
use std::collections::HashMap;
use hyper::header::HeaderName;
impl Into<HttpRequest> for Request<Body> {
fn into(self) -> HttpRequest {
let params = self.uri()
.query()
.map(|v| {
url::form_urlencoded::parse(v.as_bytes())
.into_owned()
.collect()
})
.unwrap_or_else(HashMap::new);
let headers = self.headers()
.iter()
.map(|v|
(v.0.as_str().into(),String::from_utf8_lossy(v.1.as_bytes()).into_owned()))
.collect();
let cookies = self.headers().get("Cookies".into());
HttpRequest{
method: self.method().into(),
path: self.uri().path().into(),
params,
headers,
cookies,
body: vec![]
}
}
}
impl From<&Method> for HttpMethod {
fn from(m: &Method) -> Self {
match m {
&Method::GET => HttpMethod::Get,
&Method::POST => HttpMethod::Post,
&Method::PUT => HttpMethod::Put,
&Method::DELETE => HttpMethod::Delete,
_ => HttpMethod::Unsupported,
}
}
}
impl From<HttpResponse> for Response<Body> {
fn from(_: HttpResponse) -> Self {
unimplemented!()
}
}
| true |
3b337382aedb6e25888338e3512379bb25dc7ab2
|
Rust
|
eugene-babichenko/jorup
|
/src/utils/version.rs
|
UTF-8
| 6,251 | 2.96875 | 3 |
[
"MIT",
"Apache-2.0"
] |
permissive
|
use chrono::{offset::Utc, DateTime};
use semver::{Version as SemverVersion, VersionReq as SemverVersionReq};
use serde::{de, Deserialize, Deserializer};
use std::{
cmp::{Ordering, PartialOrd},
fmt,
str::FromStr,
};
pub use semver::{ReqParseError, SemVerError};
const DATEFMT: &str = "%Y%m%d";
#[derive(Debug, Clone, PartialEq, Eq, Ord)]
pub enum Version {
Nightly(Option<(SemverVersion, DateTime<Utc>)>),
Stable(SemverVersion),
}
#[derive(Debug, Clone)]
pub enum VersionReq {
Latest,
Nightly,
Stable(SemverVersionReq),
ExactStable(SemverVersion),
}
impl Version {
pub fn parse(version: &str) -> Result<Self, SemVerError> {
if version == "nightly" {
return Ok(Version::Nightly(None));
}
SemverVersion::parse(version).map(Version::Stable)
}
pub fn from_git_tag(version: &str) -> Result<Self, SemVerError> {
let version = version.trim_start_matches('v');
Self::parse(version)
}
pub fn to_git_tag(&self) -> String {
match self {
Version::Nightly(_) => "nightly".to_string(),
Version::Stable(version) => format!("v{}", version),
}
}
pub fn configure_nightly(self, last_stable_version: Self, datetime: DateTime<Utc>) -> Self {
let mut version = match last_stable_version {
Version::Stable(version) => version,
Version::Nightly(_) => panic!("only Stable can be provided to this method"),
};
version.increment_patch();
match self {
Version::Nightly(_) => Version::Nightly(Some((version, datetime))),
v => v,
}
}
}
impl VersionReq {
pub fn parse(version_req: &str) -> Result<Self, ReqParseError> {
if version_req == "nightly" {
return Ok(VersionReq::Nightly);
}
SemverVersionReq::parse(version_req).map(VersionReq::Stable)
}
pub fn exact(version: Version) -> Self {
match version {
Version::Nightly(_) => VersionReq::Nightly,
Version::Stable(version) => VersionReq::ExactStable(version),
}
}
pub fn matches(&self, version: &Version) -> bool {
match self {
VersionReq::Latest => false,
VersionReq::Nightly => match version {
Version::Nightly(_) => true,
_ => false,
},
VersionReq::Stable(version_req) => match version {
Version::Nightly(_) => false,
Version::Stable(version) => version_req.matches(version),
},
VersionReq::ExactStable(version_req) => match version {
Version::Nightly(_) => false,
Version::Stable(other) => version_req.eq(other),
},
}
}
pub fn into_version(self) -> Option<Version> {
if let VersionReq::ExactStable(version) = self {
return Some(Version::Stable(version));
}
None
}
}
impl<'de> Deserialize<'de> for Version {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct VersionVisitor;
// Deserialize Version from a string.
impl<'de> de::Visitor<'de> for VersionVisitor {
type Value = Version;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a version as a string")
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: de::Error,
{
Version::parse(v).map_err(de::Error::custom)
}
}
deserializer.deserialize_str(VersionVisitor)
}
}
impl<'de> Deserialize<'de> for VersionReq {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct VersionReqVisitor;
// Deserialize Version from a string.
impl<'de> de::Visitor<'de> for VersionReqVisitor {
type Value = VersionReq;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a version requirement as a string")
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: de::Error,
{
VersionReq::parse(v).map_err(de::Error::custom)
}
}
deserializer.deserialize_str(VersionReqVisitor)
}
}
impl FromStr for Version {
type Err = SemVerError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Version::parse(s)
}
}
impl FromStr for VersionReq {
type Err = ReqParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
VersionReq::parse(s)
}
}
impl fmt::Display for Version {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Version::Nightly(None) => f.write_str("nightly"),
Version::Nightly(Some((version, datetime))) => {
write!(f, "{}-nightly.{}", version, datetime.format(DATEFMT))
}
Version::Stable(version) => f.write_str(&version.to_string()),
}
}
}
impl fmt::Display for VersionReq {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
VersionReq::Latest => f.write_str("latest"),
VersionReq::Nightly => f.write_str("nightly"),
VersionReq::Stable(version_req) => f.write_str(&version_req.to_string()),
VersionReq::ExactStable(version) => f.write_str(&version.to_string()),
}
}
}
impl PartialOrd for Version {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
let res = match self {
Version::Nightly(datetime) => match other {
Version::Nightly(other_datetime) => return datetime.partial_cmp(other_datetime),
Version::Stable(_) => Ordering::Less,
},
Version::Stable(version) => match other {
Version::Nightly(_) => Ordering::Greater,
Version::Stable(other) => version.cmp(other),
},
};
Some(res)
}
}
| true |
9b37dad2c2f1a1926cae8000a254f3d5006cb240
|
Rust
|
kaiakz/jvmrs
|
/src/classfile/mod.rs
|
UTF-8
| 2,855 | 2.796875 | 3 |
[] |
no_license
|
pub mod cp;
pub mod attribute;
pub mod member;
pub mod interface;
use crate::utils::bytes::ByteStream;
use crate::utils::bytes::Bytes;
//the data of classfiles store as big-endian
pub struct ClassFile {
// magic : u32,
minor_version : u16,
majar_version : u16,
constant_pool : cp::ConstantPool, //use vector to store constantinfo and its len() to represent constantpool_count
access_flags : u16,
this_class : u16,
super_class : u16,
interfaces : interface::Interface,
fields : member::Member,
methods : member::Member,
attributes : attribute::Attribute,
}
impl ClassFile {
pub fn load(raw : Bytes) -> ClassFile {
let mut reader = ByteStream::from(raw);
// let mut reader = Cursor::new(code);
// let magic = reader.get_u32_be();
// let minorVersion = reader.get_u16_be();
// let majarVersion = reader.get_u16_be();
// let
// let accessFlags = reader.get_u16_be();
// let thisClass = reader.get_u16_be();
// let superClass = reader.get_u16_be();
//Check Magic:0xCAFEBABE
let magic = reader.get_u32_be().expect("Invaild magic");
if magic != 0xCAFEBABE {
panic!("Bad magic");
}
//Check Version
let minor_version = reader.get_u16_be().expect("Invaild version");
let majar_version = reader.get_u16_be().expect("Invaild version");
// println!("minor_version:{}", &minor_version);
// println!("majar_version:{}", &majar_version);
//Read ConstantPool
let cp = cp::ConstantPool::from(&mut reader);
let access_flags = reader.get_u16_be().expect("Invaild access_flags");
let this_class = reader.get_u16_be().expect("Invaild this_class");
let super_class = reader.get_u16_be().expect("Invaild super_class");
// println!("access_flags:{}", &access_flags);
// println!("this_class:{}", &this_class);
// println!("super_class:{}", &super_class);
//Read interfaces
let interfaces = interface::Interface::from(&mut reader);
//Read Field
let fields = member::Member::from(&mut reader, &cp);
//Read Method
let methods = member::Member::from(&mut reader, &cp);
//Read Attributes
let attributes = attribute::Attribute::from(&mut reader, &cp);
ClassFile {
// magic : reader.get_u32_be().expect("Invaild magic"),
minor_version : minor_version,
majar_version : majar_version,
constant_pool : cp,
access_flags : access_flags,
this_class : this_class,
super_class : super_class,
interfaces : interfaces,
fields : fields,
methods : methods,
attributes : attributes,
}
}
}
| true |
b81c7bd6261e7b54f163aa1d88e685099ec41775
|
Rust
|
ferrous-systems/imxrt1052
|
/src/bee/ctrl/mod.rs
|
UTF-8
| 50,133 | 2.671875 | 3 |
[] |
no_license
|
#[doc = r" Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r" Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::CTRL {
#[doc = r" Modifies the contents of the register"]
#[inline]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,
{
let bits = self.register.get();
let r = R { bits: bits };
let mut w = W { bits: bits };
f(&r, &mut w);
self.register.set(w.bits);
}
#[doc = r" Reads the contents of the register"]
#[inline]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
#[doc = r" Writes to the register"]
#[inline]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
let mut w = W::reset_value();
f(&mut w);
self.register.set(w.bits);
}
#[doc = r" Writes the reset value to the register"]
#[inline]
pub fn reset(&self) {
self.write(|w| w)
}
}
#[doc = "Possible values of the field `BEE_ENABLE`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum BEE_ENABLER {
#[doc = "Disable BEE"]
BEE_ENABLE_0,
#[doc = "Enable BEE"]
BEE_ENABLE_1,
}
impl BEE_ENABLER {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
BEE_ENABLER::BEE_ENABLE_0 => false,
BEE_ENABLER::BEE_ENABLE_1 => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> BEE_ENABLER {
match value {
false => BEE_ENABLER::BEE_ENABLE_0,
true => BEE_ENABLER::BEE_ENABLE_1,
}
}
#[doc = "Checks if the value of the field is `BEE_ENABLE_0`"]
#[inline]
pub fn is_bee_enable_0(&self) -> bool {
*self == BEE_ENABLER::BEE_ENABLE_0
}
#[doc = "Checks if the value of the field is `BEE_ENABLE_1`"]
#[inline]
pub fn is_bee_enable_1(&self) -> bool {
*self == BEE_ENABLER::BEE_ENABLE_1
}
}
#[doc = r" Value of the field"]
pub struct CTRL_CLK_ENR {
bits: bool,
}
impl CTRL_CLK_ENR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct CTRL_SFTRST_NR {
bits: bool,
}
impl CTRL_SFTRST_NR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct KEY_VALIDR {
bits: bool,
}
impl KEY_VALIDR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = "Possible values of the field `KEY_REGION_SEL`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum KEY_REGION_SELR {
#[doc = "Load AES key for region0"]
KEY_REGION_SEL_0,
#[doc = "Load AES key for region1"]
KEY_REGION_SEL_1,
}
impl KEY_REGION_SELR {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
KEY_REGION_SELR::KEY_REGION_SEL_0 => false,
KEY_REGION_SELR::KEY_REGION_SEL_1 => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> KEY_REGION_SELR {
match value {
false => KEY_REGION_SELR::KEY_REGION_SEL_0,
true => KEY_REGION_SELR::KEY_REGION_SEL_1,
}
}
#[doc = "Checks if the value of the field is `KEY_REGION_SEL_0`"]
#[inline]
pub fn is_key_region_sel_0(&self) -> bool {
*self == KEY_REGION_SELR::KEY_REGION_SEL_0
}
#[doc = "Checks if the value of the field is `KEY_REGION_SEL_1`"]
#[inline]
pub fn is_key_region_sel_1(&self) -> bool {
*self == KEY_REGION_SELR::KEY_REGION_SEL_1
}
}
#[doc = r" Value of the field"]
pub struct AC_PROT_ENR {
bits: bool,
}
impl AC_PROT_ENR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = "Possible values of the field `LITTLE_ENDIAN`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum LITTLE_ENDIANR {
#[doc = "The input and output data of the AES core is swapped as below: {B15,B14,B13,B12,B11,B10,B9,B8, B7,B6,B5,B4,B3,B2,B1,B0} swap to {B0,B1,B2,B3,B4,B5,B6,B7, B8,B9,B10,B11,B12,B13,B14,B15}, where B0~B15 refers to Byte0 to Byte15."]
LITTLE_ENDIAN_0,
#[doc = "The input and output data of AES core is not swapped."]
LITTLE_ENDIAN_1,
}
impl LITTLE_ENDIANR {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
LITTLE_ENDIANR::LITTLE_ENDIAN_0 => false,
LITTLE_ENDIANR::LITTLE_ENDIAN_1 => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> LITTLE_ENDIANR {
match value {
false => LITTLE_ENDIANR::LITTLE_ENDIAN_0,
true => LITTLE_ENDIANR::LITTLE_ENDIAN_1,
}
}
#[doc = "Checks if the value of the field is `LITTLE_ENDIAN_0`"]
#[inline]
pub fn is_little_endian_0(&self) -> bool {
*self == LITTLE_ENDIANR::LITTLE_ENDIAN_0
}
#[doc = "Checks if the value of the field is `LITTLE_ENDIAN_1`"]
#[inline]
pub fn is_little_endian_1(&self) -> bool {
*self == LITTLE_ENDIANR::LITTLE_ENDIAN_1
}
}
#[doc = r" Value of the field"]
pub struct SECURITY_LEVEL_R0R {
bits: u8,
}
impl SECURITY_LEVEL_R0R {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
self.bits
}
}
#[doc = "Possible values of the field `CTRL_AES_MODE_R0`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum CTRL_AES_MODE_R0R {
#[doc = "ECB"]
CTRL_AES_MODE_R0_0,
#[doc = "CTR"]
CTRL_AES_MODE_R0_1,
}
impl CTRL_AES_MODE_R0R {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
CTRL_AES_MODE_R0R::CTRL_AES_MODE_R0_0 => false,
CTRL_AES_MODE_R0R::CTRL_AES_MODE_R0_1 => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> CTRL_AES_MODE_R0R {
match value {
false => CTRL_AES_MODE_R0R::CTRL_AES_MODE_R0_0,
true => CTRL_AES_MODE_R0R::CTRL_AES_MODE_R0_1,
}
}
#[doc = "Checks if the value of the field is `CTRL_AES_MODE_R0_0`"]
#[inline]
pub fn is_ctrl_aes_mode_r0_0(&self) -> bool {
*self == CTRL_AES_MODE_R0R::CTRL_AES_MODE_R0_0
}
#[doc = "Checks if the value of the field is `CTRL_AES_MODE_R0_1`"]
#[inline]
pub fn is_ctrl_aes_mode_r0_1(&self) -> bool {
*self == CTRL_AES_MODE_R0R::CTRL_AES_MODE_R0_1
}
}
#[doc = r" Value of the field"]
pub struct SECURITY_LEVEL_R1R {
bits: u8,
}
impl SECURITY_LEVEL_R1R {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
self.bits
}
}
#[doc = "Possible values of the field `CTRL_AES_MODE_R1`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum CTRL_AES_MODE_R1R {
#[doc = "ECB"]
CTRL_AES_MODE_R1_0,
#[doc = "CTR"]
CTRL_AES_MODE_R1_1,
}
impl CTRL_AES_MODE_R1R {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
CTRL_AES_MODE_R1R::CTRL_AES_MODE_R1_0 => false,
CTRL_AES_MODE_R1R::CTRL_AES_MODE_R1_1 => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> CTRL_AES_MODE_R1R {
match value {
false => CTRL_AES_MODE_R1R::CTRL_AES_MODE_R1_0,
true => CTRL_AES_MODE_R1R::CTRL_AES_MODE_R1_1,
}
}
#[doc = "Checks if the value of the field is `CTRL_AES_MODE_R1_0`"]
#[inline]
pub fn is_ctrl_aes_mode_r1_0(&self) -> bool {
*self == CTRL_AES_MODE_R1R::CTRL_AES_MODE_R1_0
}
#[doc = "Checks if the value of the field is `CTRL_AES_MODE_R1_1`"]
#[inline]
pub fn is_ctrl_aes_mode_r1_1(&self) -> bool {
*self == CTRL_AES_MODE_R1R::CTRL_AES_MODE_R1_1
}
}
#[doc = r" Value of the field"]
pub struct BEE_ENABLE_LOCKR {
bits: bool,
}
impl BEE_ENABLE_LOCKR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct CTRL_CLK_EN_LOCKR {
bits: bool,
}
impl CTRL_CLK_EN_LOCKR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct CTRL_SFTRST_N_LOCKR {
bits: bool,
}
impl CTRL_SFTRST_N_LOCKR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct REGION1_ADDR_LOCKR {
bits: bool,
}
impl REGION1_ADDR_LOCKR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct KEY_VALID_LOCKR {
bits: bool,
}
impl KEY_VALID_LOCKR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct KEY_REGION_SEL_LOCKR {
bits: bool,
}
impl KEY_REGION_SEL_LOCKR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct AC_PROT_EN_LOCKR {
bits: bool,
}
impl AC_PROT_EN_LOCKR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct LITTLE_ENDIAN_LOCKR {
bits: bool,
}
impl LITTLE_ENDIAN_LOCKR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct SECURITY_LEVEL_R0_LOCKR {
bits: u8,
}
impl SECURITY_LEVEL_R0_LOCKR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
self.bits
}
}
#[doc = r" Value of the field"]
pub struct CTRL_AES_MODE_R0_LOCKR {
bits: bool,
}
impl CTRL_AES_MODE_R0_LOCKR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct REGION0_KEY_LOCKR {
bits: bool,
}
impl REGION0_KEY_LOCKR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct SECURITY_LEVEL_R1_LOCKR {
bits: u8,
}
impl SECURITY_LEVEL_R1_LOCKR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
self.bits
}
}
#[doc = r" Value of the field"]
pub struct CTRL_AES_MODE_R1_LOCKR {
bits: bool,
}
impl CTRL_AES_MODE_R1_LOCKR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct REGION1_KEY_LOCKR {
bits: bool,
}
impl REGION1_KEY_LOCKR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = "Values that can be written to the field `BEE_ENABLE`"]
pub enum BEE_ENABLEW {
#[doc = "Disable BEE"]
BEE_ENABLE_0,
#[doc = "Enable BEE"]
BEE_ENABLE_1,
}
impl BEE_ENABLEW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
BEE_ENABLEW::BEE_ENABLE_0 => false,
BEE_ENABLEW::BEE_ENABLE_1 => true,
}
}
}
#[doc = r" Proxy"]
pub struct _BEE_ENABLEW<'a> {
w: &'a mut W,
}
impl<'a> _BEE_ENABLEW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: BEE_ENABLEW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Disable BEE"]
#[inline]
pub fn bee_enable_0(self) -> &'a mut W {
self.variant(BEE_ENABLEW::BEE_ENABLE_0)
}
#[doc = "Enable BEE"]
#[inline]
pub fn bee_enable_1(self) -> &'a mut W {
self.variant(BEE_ENABLEW::BEE_ENABLE_1)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 0;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _CTRL_CLK_ENW<'a> {
w: &'a mut W,
}
impl<'a> _CTRL_CLK_ENW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 1;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _CTRL_SFTRST_NW<'a> {
w: &'a mut W,
}
impl<'a> _CTRL_SFTRST_NW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 2;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _KEY_VALIDW<'a> {
w: &'a mut W,
}
impl<'a> _KEY_VALIDW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 4;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `KEY_REGION_SEL`"]
pub enum KEY_REGION_SELW {
#[doc = "Load AES key for region0"]
KEY_REGION_SEL_0,
#[doc = "Load AES key for region1"]
KEY_REGION_SEL_1,
}
impl KEY_REGION_SELW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
KEY_REGION_SELW::KEY_REGION_SEL_0 => false,
KEY_REGION_SELW::KEY_REGION_SEL_1 => true,
}
}
}
#[doc = r" Proxy"]
pub struct _KEY_REGION_SELW<'a> {
w: &'a mut W,
}
impl<'a> _KEY_REGION_SELW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: KEY_REGION_SELW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Load AES key for region0"]
#[inline]
pub fn key_region_sel_0(self) -> &'a mut W {
self.variant(KEY_REGION_SELW::KEY_REGION_SEL_0)
}
#[doc = "Load AES key for region1"]
#[inline]
pub fn key_region_sel_1(self) -> &'a mut W {
self.variant(KEY_REGION_SELW::KEY_REGION_SEL_1)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 5;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _AC_PROT_ENW<'a> {
w: &'a mut W,
}
impl<'a> _AC_PROT_ENW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 6;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `LITTLE_ENDIAN`"]
pub enum LITTLE_ENDIANW {
#[doc = "The input and output data of the AES core is swapped as below: {B15,B14,B13,B12,B11,B10,B9,B8, B7,B6,B5,B4,B3,B2,B1,B0} swap to {B0,B1,B2,B3,B4,B5,B6,B7, B8,B9,B10,B11,B12,B13,B14,B15}, where B0~B15 refers to Byte0 to Byte15."]
LITTLE_ENDIAN_0,
#[doc = "The input and output data of AES core is not swapped."]
LITTLE_ENDIAN_1,
}
impl LITTLE_ENDIANW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
LITTLE_ENDIANW::LITTLE_ENDIAN_0 => false,
LITTLE_ENDIANW::LITTLE_ENDIAN_1 => true,
}
}
}
#[doc = r" Proxy"]
pub struct _LITTLE_ENDIANW<'a> {
w: &'a mut W,
}
impl<'a> _LITTLE_ENDIANW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: LITTLE_ENDIANW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "The input and output data of the AES core is swapped as below: {B15,B14,B13,B12,B11,B10,B9,B8, B7,B6,B5,B4,B3,B2,B1,B0} swap to {B0,B1,B2,B3,B4,B5,B6,B7, B8,B9,B10,B11,B12,B13,B14,B15}, where B0~B15 refers to Byte0 to Byte15."]
#[inline]
pub fn little_endian_0(self) -> &'a mut W {
self.variant(LITTLE_ENDIANW::LITTLE_ENDIAN_0)
}
#[doc = "The input and output data of AES core is not swapped."]
#[inline]
pub fn little_endian_1(self) -> &'a mut W {
self.variant(LITTLE_ENDIANW::LITTLE_ENDIAN_1)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 7;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _SECURITY_LEVEL_R0W<'a> {
w: &'a mut W,
}
impl<'a> _SECURITY_LEVEL_R0W<'a> {
#[doc = r" Writes raw bits to the field"]
#[inline]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 3;
const OFFSET: u8 = 8;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `CTRL_AES_MODE_R0`"]
pub enum CTRL_AES_MODE_R0W {
#[doc = "ECB"]
CTRL_AES_MODE_R0_0,
#[doc = "CTR"]
CTRL_AES_MODE_R0_1,
}
impl CTRL_AES_MODE_R0W {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
CTRL_AES_MODE_R0W::CTRL_AES_MODE_R0_0 => false,
CTRL_AES_MODE_R0W::CTRL_AES_MODE_R0_1 => true,
}
}
}
#[doc = r" Proxy"]
pub struct _CTRL_AES_MODE_R0W<'a> {
w: &'a mut W,
}
impl<'a> _CTRL_AES_MODE_R0W<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: CTRL_AES_MODE_R0W) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "ECB"]
#[inline]
pub fn ctrl_aes_mode_r0_0(self) -> &'a mut W {
self.variant(CTRL_AES_MODE_R0W::CTRL_AES_MODE_R0_0)
}
#[doc = "CTR"]
#[inline]
pub fn ctrl_aes_mode_r0_1(self) -> &'a mut W {
self.variant(CTRL_AES_MODE_R0W::CTRL_AES_MODE_R0_1)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 10;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _SECURITY_LEVEL_R1W<'a> {
w: &'a mut W,
}
impl<'a> _SECURITY_LEVEL_R1W<'a> {
#[doc = r" Writes raw bits to the field"]
#[inline]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 3;
const OFFSET: u8 = 12;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `CTRL_AES_MODE_R1`"]
pub enum CTRL_AES_MODE_R1W {
#[doc = "ECB"]
CTRL_AES_MODE_R1_0,
#[doc = "CTR"]
CTRL_AES_MODE_R1_1,
}
impl CTRL_AES_MODE_R1W {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
CTRL_AES_MODE_R1W::CTRL_AES_MODE_R1_0 => false,
CTRL_AES_MODE_R1W::CTRL_AES_MODE_R1_1 => true,
}
}
}
#[doc = r" Proxy"]
pub struct _CTRL_AES_MODE_R1W<'a> {
w: &'a mut W,
}
impl<'a> _CTRL_AES_MODE_R1W<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: CTRL_AES_MODE_R1W) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "ECB"]
#[inline]
pub fn ctrl_aes_mode_r1_0(self) -> &'a mut W {
self.variant(CTRL_AES_MODE_R1W::CTRL_AES_MODE_R1_0)
}
#[doc = "CTR"]
#[inline]
pub fn ctrl_aes_mode_r1_1(self) -> &'a mut W {
self.variant(CTRL_AES_MODE_R1W::CTRL_AES_MODE_R1_1)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 14;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _BEE_ENABLE_LOCKW<'a> {
w: &'a mut W,
}
impl<'a> _BEE_ENABLE_LOCKW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 16;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _CTRL_CLK_EN_LOCKW<'a> {
w: &'a mut W,
}
impl<'a> _CTRL_CLK_EN_LOCKW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 17;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _CTRL_SFTRST_N_LOCKW<'a> {
w: &'a mut W,
}
impl<'a> _CTRL_SFTRST_N_LOCKW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 18;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _REGION1_ADDR_LOCKW<'a> {
w: &'a mut W,
}
impl<'a> _REGION1_ADDR_LOCKW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 19;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _KEY_VALID_LOCKW<'a> {
w: &'a mut W,
}
impl<'a> _KEY_VALID_LOCKW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 20;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _KEY_REGION_SEL_LOCKW<'a> {
w: &'a mut W,
}
impl<'a> _KEY_REGION_SEL_LOCKW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 21;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _AC_PROT_EN_LOCKW<'a> {
w: &'a mut W,
}
impl<'a> _AC_PROT_EN_LOCKW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 22;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _LITTLE_ENDIAN_LOCKW<'a> {
w: &'a mut W,
}
impl<'a> _LITTLE_ENDIAN_LOCKW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 23;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _SECURITY_LEVEL_R0_LOCKW<'a> {
w: &'a mut W,
}
impl<'a> _SECURITY_LEVEL_R0_LOCKW<'a> {
#[doc = r" Writes raw bits to the field"]
#[inline]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 3;
const OFFSET: u8 = 24;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _CTRL_AES_MODE_R0_LOCKW<'a> {
w: &'a mut W,
}
impl<'a> _CTRL_AES_MODE_R0_LOCKW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 26;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _REGION0_KEY_LOCKW<'a> {
w: &'a mut W,
}
impl<'a> _REGION0_KEY_LOCKW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 27;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _SECURITY_LEVEL_R1_LOCKW<'a> {
w: &'a mut W,
}
impl<'a> _SECURITY_LEVEL_R1_LOCKW<'a> {
#[doc = r" Writes raw bits to the field"]
#[inline]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 3;
const OFFSET: u8 = 28;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _CTRL_AES_MODE_R1_LOCKW<'a> {
w: &'a mut W,
}
impl<'a> _CTRL_AES_MODE_R1_LOCKW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 30;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _REGION1_KEY_LOCKW<'a> {
w: &'a mut W,
}
impl<'a> _REGION1_KEY_LOCKW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 31;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
impl R {
#[doc = r" Value of the register as raw bits"]
#[inline]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bit 0 - BEE enable bit"]
#[inline]
pub fn bee_enable(&self) -> BEE_ENABLER {
BEE_ENABLER::_from({
const MASK: bool = true;
const OFFSET: u8 = 0;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 1 - Clock enable input, low inactive"]
#[inline]
pub fn ctrl_clk_en(&self) -> CTRL_CLK_ENR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 1;
((self.bits >> OFFSET) & MASK as u32) != 0
};
CTRL_CLK_ENR { bits }
}
#[doc = "Bit 2 - Soft reset input, low active"]
#[inline]
pub fn ctrl_sftrst_n(&self) -> CTRL_SFTRST_NR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 2;
((self.bits >> OFFSET) & MASK as u32) != 0
};
CTRL_SFTRST_NR { bits }
}
#[doc = "Bit 4 - AES-128 key is ready"]
#[inline]
pub fn key_valid(&self) -> KEY_VALIDR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 4;
((self.bits >> OFFSET) & MASK as u32) != 0
};
KEY_VALIDR { bits }
}
#[doc = "Bit 5 - AES key region select"]
#[inline]
pub fn key_region_sel(&self) -> KEY_REGION_SELR {
KEY_REGION_SELR::_from({
const MASK: bool = true;
const OFFSET: u8 = 5;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 6 - Enable access permission control"]
#[inline]
pub fn ac_prot_en(&self) -> AC_PROT_ENR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 6;
((self.bits >> OFFSET) & MASK as u32) != 0
};
AC_PROT_ENR { bits }
}
#[doc = "Bit 7 - Endian swap control for the 16 bytes input and output data of AES core."]
#[inline]
pub fn little_endian(&self) -> LITTLE_ENDIANR {
LITTLE_ENDIANR::_from({
const MASK: bool = true;
const OFFSET: u8 = 7;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bits 8:9 - Security level of the allowed access for memory region0"]
#[inline]
pub fn security_level_r0(&self) -> SECURITY_LEVEL_R0R {
let bits = {
const MASK: u8 = 3;
const OFFSET: u8 = 8;
((self.bits >> OFFSET) & MASK as u32) as u8
};
SECURITY_LEVEL_R0R { bits }
}
#[doc = "Bit 10 - AES mode of region0"]
#[inline]
pub fn ctrl_aes_mode_r0(&self) -> CTRL_AES_MODE_R0R {
CTRL_AES_MODE_R0R::_from({
const MASK: bool = true;
const OFFSET: u8 = 10;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bits 12:13 - Security level of the allowed access for memory region1"]
#[inline]
pub fn security_level_r1(&self) -> SECURITY_LEVEL_R1R {
let bits = {
const MASK: u8 = 3;
const OFFSET: u8 = 12;
((self.bits >> OFFSET) & MASK as u32) as u8
};
SECURITY_LEVEL_R1R { bits }
}
#[doc = "Bit 14 - AES mode of region1"]
#[inline]
pub fn ctrl_aes_mode_r1(&self) -> CTRL_AES_MODE_R1R {
CTRL_AES_MODE_R1R::_from({
const MASK: bool = true;
const OFFSET: u8 = 14;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 16 - Lock bit for bee_enable"]
#[inline]
pub fn bee_enable_lock(&self) -> BEE_ENABLE_LOCKR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 16;
((self.bits >> OFFSET) & MASK as u32) != 0
};
BEE_ENABLE_LOCKR { bits }
}
#[doc = "Bit 17 - Lock bit for ctrl_clk_en"]
#[inline]
pub fn ctrl_clk_en_lock(&self) -> CTRL_CLK_EN_LOCKR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 17;
((self.bits >> OFFSET) & MASK as u32) != 0
};
CTRL_CLK_EN_LOCKR { bits }
}
#[doc = "Bit 18 - Lock bit for ctrl_sftrst"]
#[inline]
pub fn ctrl_sftrst_n_lock(&self) -> CTRL_SFTRST_N_LOCKR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 18;
((self.bits >> OFFSET) & MASK as u32) != 0
};
CTRL_SFTRST_N_LOCKR { bits }
}
#[doc = "Bit 19 - Lock bit for region1 address boundary"]
#[inline]
pub fn region1_addr_lock(&self) -> REGION1_ADDR_LOCKR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 19;
((self.bits >> OFFSET) & MASK as u32) != 0
};
REGION1_ADDR_LOCKR { bits }
}
#[doc = "Bit 20 - Lock bit for key_valid"]
#[inline]
pub fn key_valid_lock(&self) -> KEY_VALID_LOCKR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 20;
((self.bits >> OFFSET) & MASK as u32) != 0
};
KEY_VALID_LOCKR { bits }
}
#[doc = "Bit 21 - Lock bit for key_region_sel"]
#[inline]
pub fn key_region_sel_lock(&self) -> KEY_REGION_SEL_LOCKR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 21;
((self.bits >> OFFSET) & MASK as u32) != 0
};
KEY_REGION_SEL_LOCKR { bits }
}
#[doc = "Bit 22 - Lock bit for ac_prot"]
#[inline]
pub fn ac_prot_en_lock(&self) -> AC_PROT_EN_LOCKR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 22;
((self.bits >> OFFSET) & MASK as u32) != 0
};
AC_PROT_EN_LOCKR { bits }
}
#[doc = "Bit 23 - Lock bit for little_endian"]
#[inline]
pub fn little_endian_lock(&self) -> LITTLE_ENDIAN_LOCKR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 23;
((self.bits >> OFFSET) & MASK as u32) != 0
};
LITTLE_ENDIAN_LOCKR { bits }
}
#[doc = "Bits 24:25 - Lock bits for security_level_r0"]
#[inline]
pub fn security_level_r0_lock(&self) -> SECURITY_LEVEL_R0_LOCKR {
let bits = {
const MASK: u8 = 3;
const OFFSET: u8 = 24;
((self.bits >> OFFSET) & MASK as u32) as u8
};
SECURITY_LEVEL_R0_LOCKR { bits }
}
#[doc = "Bit 26 - Lock bit for region0 ctrl_aes_mode"]
#[inline]
pub fn ctrl_aes_mode_r0_lock(&self) -> CTRL_AES_MODE_R0_LOCKR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 26;
((self.bits >> OFFSET) & MASK as u32) != 0
};
CTRL_AES_MODE_R0_LOCKR { bits }
}
#[doc = "Bit 27 - Lock bit for region0 AES key"]
#[inline]
pub fn region0_key_lock(&self) -> REGION0_KEY_LOCKR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 27;
((self.bits >> OFFSET) & MASK as u32) != 0
};
REGION0_KEY_LOCKR { bits }
}
#[doc = "Bits 28:29 - Lock bits for security_level_r1"]
#[inline]
pub fn security_level_r1_lock(&self) -> SECURITY_LEVEL_R1_LOCKR {
let bits = {
const MASK: u8 = 3;
const OFFSET: u8 = 28;
((self.bits >> OFFSET) & MASK as u32) as u8
};
SECURITY_LEVEL_R1_LOCKR { bits }
}
#[doc = "Bit 30 - Lock bit for region1 ctrl_aes_mode"]
#[inline]
pub fn ctrl_aes_mode_r1_lock(&self) -> CTRL_AES_MODE_R1_LOCKR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 30;
((self.bits >> OFFSET) & MASK as u32) != 0
};
CTRL_AES_MODE_R1_LOCKR { bits }
}
#[doc = "Bit 31 - Lock bit for region1 AES key"]
#[inline]
pub fn region1_key_lock(&self) -> REGION1_KEY_LOCKR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 31;
((self.bits >> OFFSET) & MASK as u32) != 0
};
REGION1_KEY_LOCKR { bits }
}
}
impl W {
#[doc = r" Reset value of the register"]
#[inline]
pub fn reset_value() -> W {
W { bits: 30464 }
}
#[doc = r" Writes raw bits to the register"]
#[inline]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bit 0 - BEE enable bit"]
#[inline]
pub fn bee_enable(&mut self) -> _BEE_ENABLEW {
_BEE_ENABLEW { w: self }
}
#[doc = "Bit 1 - Clock enable input, low inactive"]
#[inline]
pub fn ctrl_clk_en(&mut self) -> _CTRL_CLK_ENW {
_CTRL_CLK_ENW { w: self }
}
#[doc = "Bit 2 - Soft reset input, low active"]
#[inline]
pub fn ctrl_sftrst_n(&mut self) -> _CTRL_SFTRST_NW {
_CTRL_SFTRST_NW { w: self }
}
#[doc = "Bit 4 - AES-128 key is ready"]
#[inline]
pub fn key_valid(&mut self) -> _KEY_VALIDW {
_KEY_VALIDW { w: self }
}
#[doc = "Bit 5 - AES key region select"]
#[inline]
pub fn key_region_sel(&mut self) -> _KEY_REGION_SELW {
_KEY_REGION_SELW { w: self }
}
#[doc = "Bit 6 - Enable access permission control"]
#[inline]
pub fn ac_prot_en(&mut self) -> _AC_PROT_ENW {
_AC_PROT_ENW { w: self }
}
#[doc = "Bit 7 - Endian swap control for the 16 bytes input and output data of AES core."]
#[inline]
pub fn little_endian(&mut self) -> _LITTLE_ENDIANW {
_LITTLE_ENDIANW { w: self }
}
#[doc = "Bits 8:9 - Security level of the allowed access for memory region0"]
#[inline]
pub fn security_level_r0(&mut self) -> _SECURITY_LEVEL_R0W {
_SECURITY_LEVEL_R0W { w: self }
}
#[doc = "Bit 10 - AES mode of region0"]
#[inline]
pub fn ctrl_aes_mode_r0(&mut self) -> _CTRL_AES_MODE_R0W {
_CTRL_AES_MODE_R0W { w: self }
}
#[doc = "Bits 12:13 - Security level of the allowed access for memory region1"]
#[inline]
pub fn security_level_r1(&mut self) -> _SECURITY_LEVEL_R1W {
_SECURITY_LEVEL_R1W { w: self }
}
#[doc = "Bit 14 - AES mode of region1"]
#[inline]
pub fn ctrl_aes_mode_r1(&mut self) -> _CTRL_AES_MODE_R1W {
_CTRL_AES_MODE_R1W { w: self }
}
#[doc = "Bit 16 - Lock bit for bee_enable"]
#[inline]
pub fn bee_enable_lock(&mut self) -> _BEE_ENABLE_LOCKW {
_BEE_ENABLE_LOCKW { w: self }
}
#[doc = "Bit 17 - Lock bit for ctrl_clk_en"]
#[inline]
pub fn ctrl_clk_en_lock(&mut self) -> _CTRL_CLK_EN_LOCKW {
_CTRL_CLK_EN_LOCKW { w: self }
}
#[doc = "Bit 18 - Lock bit for ctrl_sftrst"]
#[inline]
pub fn ctrl_sftrst_n_lock(&mut self) -> _CTRL_SFTRST_N_LOCKW {
_CTRL_SFTRST_N_LOCKW { w: self }
}
#[doc = "Bit 19 - Lock bit for region1 address boundary"]
#[inline]
pub fn region1_addr_lock(&mut self) -> _REGION1_ADDR_LOCKW {
_REGION1_ADDR_LOCKW { w: self }
}
#[doc = "Bit 20 - Lock bit for key_valid"]
#[inline]
pub fn key_valid_lock(&mut self) -> _KEY_VALID_LOCKW {
_KEY_VALID_LOCKW { w: self }
}
#[doc = "Bit 21 - Lock bit for key_region_sel"]
#[inline]
pub fn key_region_sel_lock(&mut self) -> _KEY_REGION_SEL_LOCKW {
_KEY_REGION_SEL_LOCKW { w: self }
}
#[doc = "Bit 22 - Lock bit for ac_prot"]
#[inline]
pub fn ac_prot_en_lock(&mut self) -> _AC_PROT_EN_LOCKW {
_AC_PROT_EN_LOCKW { w: self }
}
#[doc = "Bit 23 - Lock bit for little_endian"]
#[inline]
pub fn little_endian_lock(&mut self) -> _LITTLE_ENDIAN_LOCKW {
_LITTLE_ENDIAN_LOCKW { w: self }
}
#[doc = "Bits 24:25 - Lock bits for security_level_r0"]
#[inline]
pub fn security_level_r0_lock(&mut self) -> _SECURITY_LEVEL_R0_LOCKW {
_SECURITY_LEVEL_R0_LOCKW { w: self }
}
#[doc = "Bit 26 - Lock bit for region0 ctrl_aes_mode"]
#[inline]
pub fn ctrl_aes_mode_r0_lock(&mut self) -> _CTRL_AES_MODE_R0_LOCKW {
_CTRL_AES_MODE_R0_LOCKW { w: self }
}
#[doc = "Bit 27 - Lock bit for region0 AES key"]
#[inline]
pub fn region0_key_lock(&mut self) -> _REGION0_KEY_LOCKW {
_REGION0_KEY_LOCKW { w: self }
}
#[doc = "Bits 28:29 - Lock bits for security_level_r1"]
#[inline]
pub fn security_level_r1_lock(&mut self) -> _SECURITY_LEVEL_R1_LOCKW {
_SECURITY_LEVEL_R1_LOCKW { w: self }
}
#[doc = "Bit 30 - Lock bit for region1 ctrl_aes_mode"]
#[inline]
pub fn ctrl_aes_mode_r1_lock(&mut self) -> _CTRL_AES_MODE_R1_LOCKW {
_CTRL_AES_MODE_R1_LOCKW { w: self }
}
#[doc = "Bit 31 - Lock bit for region1 AES key"]
#[inline]
pub fn region1_key_lock(&mut self) -> _REGION1_KEY_LOCKW {
_REGION1_KEY_LOCKW { w: self }
}
}
| true |
75588ca97b2aa9fe2553b6fd3917dc039d5e277f
|
Rust
|
chux0519/leetcode-rust
|
/archived/q1047_remove_all_adjacent_duplicates_in_string.rs
|
UTF-8
| 623 | 3.390625 | 3 |
[] |
no_license
|
struct Solution;
impl Solution {
/// 直接使用栈
pub fn remove_duplicates(s: String) -> String {
let mut stack = Vec::new();
for c in s.as_bytes() {
if !stack.is_empty() && stack[stack.len() - 1] == *c {
stack.pop();
} else {
stack.push(*c);
}
}
stack.into_iter().map(|c| c as char).collect()
}
}
#[cfg(test)]
mod tests {
use super::Solution;
#[test]
fn q1047() {
assert_eq!(
"ca".to_owned(),
Solution::remove_duplicates("abbaca".to_owned())
);
}
}
| true |
4e6a6e24f14ea1c6a85d63a53499cb5ae598eb30
|
Rust
|
Th3Whit3Wolf/nxpkgr
|
/src/package/settings.rs
|
UTF-8
| 1,597 | 2.671875 | 3 |
[
"MIT"
] |
permissive
|
use serde::de;
use serde::{Deserialize, Serialize};
use toml::value::Table;
use std::fmt;
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
pub struct TomlSettings {
#[serde(default = "bool::default")]
pub create_flake: bool,
#[serde(default = "bool::default")]
pub create_overlay: bool,
#[serde(default = "bool::default")]
pub create_package: bool,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_settings() {
let test_str = r#"
[settings]
create_flake = false
create_overlay = true
create_package = true
"#;
let test_str2 = r#"
[settings]
create_flake = true
"#;
let manifest = crate::package::TomlManifest::from_str(test_str).unwrap();
assert!(manifest.github.is_none());
assert!(manifest.openvsx.is_none());
assert!(manifest.vsmarketplace.is_none());
let manifest_settings = *manifest.settings.unwrap();
assert!(!manifest_settings.create_flake);
assert!(manifest_settings.create_overlay);
assert!(manifest_settings.create_package);
let manifest2 = crate::package::TomlManifest::from_str(test_str2).unwrap();
assert!(manifest2.github.is_none());
assert!(manifest2.openvsx.is_none());
assert!(manifest2.vsmarketplace.is_none());
let manifest_settings2 = *manifest2.settings.unwrap();
assert!(manifest_settings2.create_flake);
assert!(!manifest_settings2.create_overlay);
assert!(!manifest_settings2.create_package);
}
}
| true |
27e3a0be3dedf067c30b171cb98e6ed230fb6920
|
Rust
|
gmalmquist/advent
|
/2020/advent2020/src/day03.rs
|
UTF-8
| 1,332 | 3.453125 | 3 |
[] |
no_license
|
use std::fs;
use std::io::{self, BufRead};
pub fn main() {
if let Ok(file) = fs::File::open("input3.txt") {
let lines = io::BufReader::new(file).lines();
let forest = Forest::new(lines);
let slopes = vec![
(1, 1),
(3, 1),
(5, 1),
(7, 1),
(1, 2),
];
let mut product: u64 = 1;
for (right, down) in slopes {
let trees = forest.count_trees(right, down);
product *= trees as u64;
println!("slope {:?}, trees: {}, *: {}", (right, down), trees, product);
}
}
}
struct Forest {
trees: Vec<Vec<char>>,
}
impl Forest {
fn new(lines: std::io::Lines<io::BufReader<fs::File>>) -> Self {
Self {
trees: lines
.filter(|l| l.is_ok())
.map(|l| l.unwrap())
.map(|l| l.chars().collect())
.collect(),
}
}
fn getc(&self, i: usize, j: usize) -> char {
self.trees[i][j % self.trees[i].len()]
}
fn is_tree(&self, i: usize, j: usize) -> bool {
self.getc(i, j) == '#'
}
fn count_trees(&self, right: usize, down: usize) -> u32 {
let mut count = 0;
let mut j = 0;
for i in (0..self.trees.len()).step_by(down) {
count += self.is_tree(i, j) as u32;
j += right;
}
count
}
}
| true |
6f5c303858d95e0cecdfb0c12fb220e3bbfc3682
|
Rust
|
nickolay/git-interactive-rebase-tool
|
/src/display/src/tui.rs
|
UTF-8
| 4,236 | 3.015625 | 3 |
[
"BSD-3-Clause",
"GPL-3.0-only",
"Apache-2.0",
"BSD-2-Clause",
"GPL-3.0-or-later",
"LicenseRef-scancode-unknown-license-reference",
"GPL-1.0-or-later"
] |
permissive
|
use crossterm::style::Colors;
use super::{color_mode::ColorMode, Size};
use crate::DisplayError;
/// An interface that describes interactions with a terminal interface.
pub trait Tui {
/// Get the supported color mode.
fn get_color_mode(&self) -> ColorMode;
/// Reset the terminal interface to a default state.
///
/// # Errors
///
/// Errors if the Tui cannot be reset for any reason. In general this should not error, and if
/// this does generate an error, the Tui should be considered to be in a non-recoverable state.
fn reset(&mut self) -> Result<(), DisplayError>;
/// Flush the contents printed to the terminal interface.
///
/// # Errors
///
/// Errors if the Tui cannot be flushed for any reason. In general this should not error, and if
/// this does generate an error, the Tui should be considered to be in a non-recoverable state.
fn flush(&mut self) -> Result<(), DisplayError>;
/// Print text to the terminal interface.
///
/// # Errors
///
/// Errors if the Tui cannot be printed to for any reason. In general this should not error, and
/// if this does generate an error, the Tui should be considered to be in a non-recoverable
/// state.
fn print(&mut self, s: &str) -> Result<(), DisplayError>;
/// Set the color attribute of text printed to the terminal interface.
///
/// # Errors
///
/// Errors if the Tui cannot set the color for any reason. In general this should not error, and
/// if this does generate an error, the Tui should be considered to be in a non-recoverable
/// state.
fn set_color(&mut self, colors: Colors) -> Result<(), DisplayError>;
/// Set the dimmed style attribute of text printed to the terminal interface.
///
/// # Errors
///
/// Errors if the Tui cannot set the dimmed state for any reason. In general this should not
/// error, and if this does generate an error, the Tui should be considered to be in a
/// non-recoverable state.
fn set_dim(&mut self, dim: bool) -> Result<(), DisplayError>;
/// Set the underlined style attribute of text printed to the terminal interface.
///
/// # Errors
///
/// Errors if the Tui cannot set the underline state for any reason. In general this should not
/// error, and if this does generate an error, the Tui should be considered to be in a
/// non-recoverable state.
fn set_underline(&mut self, underline: bool) -> Result<(), DisplayError>;
/// Set the reversed style attribute of text printed to the terminal interface.
///
/// # Errors
///
/// Errors if the Tui cannot set the reversed state for any reason. In general this should not
/// error, and if this does generate an error, the Tui should be considered to be in a
/// non-recoverable state.
fn set_reverse(&mut self, reverse: bool) -> Result<(), DisplayError>;
/// Get the number of columns and rows of the terminal interface.
fn get_size(&self) -> Size;
/// Move the cursor position `x` characters from the start of the line.
///
/// # Errors
///
/// Errors if the Tui cannot move to a column for any reason. In general this should not error,
/// and if this does generate an error, the Tui should be considered to be in a non-recoverable
/// state.
fn move_to_column(&mut self, x: u16) -> Result<(), DisplayError>;
/// Move the cursor to the next line.
///
/// # Errors
///
/// Errors if the Tui cannot move to the next line for any reason. In general this should not
/// error, and if this does generate an error, the Tui should be considered to be in a
/// non-recoverable state.
fn move_next_line(&mut self) -> Result<(), DisplayError>;
/// Start the terminal interface interactions.
///
/// # Errors
///
/// Errors if the Tui cannot move to a started state any reason. In general this should not
/// error,and if this does generate an error, the Tui should be considered to be in a
/// non-recoverable state.
fn start(&mut self) -> Result<(), DisplayError>;
/// End the terminal interface interactions.
///
/// # Errors
///
/// Errors if the Tui cannot move to an ended state any reason. In general this should not
/// error,and if this does generate an error, the Tui should be considered to be in a
/// non-recoverable state.
fn end(&mut self) -> Result<(), DisplayError>;
}
| true |
d95e480c5a1b80772fe24f2aea5f9642a959c799
|
Rust
|
IThawk/rust-project
|
/rust-master/src/test/run-pass/diverging-fallback-option.rs
|
UTF-8
| 382 | 2.890625 | 3 |
[
"MIT",
"LicenseRef-scancode-other-permissive",
"Apache-2.0",
"BSD-3-Clause",
"BSD-2-Clause",
"NCSA"
] |
permissive
|
#![allow(warnings)]
// Here the type of `c` is `Option<?T>`, where `?T` is unconstrained.
// Because there is data-flow from the `{ return; }` block, which
// diverges and hence has type `!`, into `c`, we will default `?T` to
// `!`, and hence this code compiles rather than failing and requiring
// a type annotation.
fn main() {
let c = Some({ return; });
c.unwrap();
}
| true |
398eb9c40911a907f6fe26e95779a695b580c60d
|
Rust
|
fredlim/canvas
|
/packages/canvas/src-native/canvas-native/canvas-core/src/common/svg/prelude.rs
|
UTF-8
| 2,115 | 2.59375 | 3 |
[
"Apache-2.0"
] |
permissive
|
use skia_safe::{Rect, Size};
use crate::common::svg::enums::preserve_aspect_ratio::{
AlignMeetOrSlice, AspectRatioAlign, AspectRatioMeetOrSlice,
};
use crate::common::svg::view_box::ViewBox;
pub trait ColorConversation {
fn to_int(&self) -> u32;
}
impl ColorConversation for skia_safe::Color {
fn to_int(&self) -> u32 {
let r = 255 & 0xFF;
let g = 255 & 0xFF;
let b = 0 & 0xFF;
let a = 1 & 0xFF;
(r << 24) + (g << 16) + (b << 8) + (a)
}
}
pub trait RectUtils {
fn to_size(&self) -> skia_safe::Size;
}
pub trait SizeUtils {
fn scale_to(&self, to: Self) -> Self;
fn expand_to(&self, to: Self) -> Self;
fn fit_view_box(&self, vb: ViewBox, aspect: AlignMeetOrSlice) -> Self;
fn size_scale(s1: Self, s2: Self, expand: bool) -> Self;
fn to_rect(&self, x: f32, y: f32) -> skia_safe::Rect;
}
impl RectUtils for skia_safe::Rect {
fn to_size(&self) -> Size {
Size::new(self.width(), self.height())
}
}
impl SizeUtils for skia_safe::Size {
fn scale_to(&self, to: Self) -> Self {
Self::size_scale(*self, to, false)
}
fn expand_to(&self, to: Self) -> Self {
Self::size_scale(*self, to, true)
}
fn fit_view_box(&self, vb: ViewBox, aspect: AlignMeetOrSlice) -> Self {
let s = vb.size();
if aspect.align() == AspectRatioAlign::None {
s
} else if aspect.meet_or_slice() == AspectRatioMeetOrSlice::Slice {
self.expand_to(s)
} else {
self.scale_to(s)
}
}
fn size_scale(s1: Self, s2: Self, expand: bool) -> Self {
let rw = s2.height * s1.width / s1.height;
let with_h = if expand {
rw <= s2.width
} else {
rw >= s2.width
};
if !with_h {
skia_safe::Size::new(rw, s2.height)
} else {
let h = s2.width * s1.height / s1.width;
skia_safe::Size::new(s2.width, h)
}
}
fn to_rect(&self, x: f32, y: f32) -> Rect {
skia_safe::Rect::from_xywh(x, y, self.width, self.height)
}
}
| true |
02073833ee442a748e81c3e6bddc7502a26d7e25
|
Rust
|
arudei-dev/hep-framework
|
/src/math/number/complex/tests/test_op_arithm.rs
|
UTF-8
| 4,248 | 3.1875 | 3 |
[] |
no_license
|
use super::*;
fn generate_data() -> Vec<Complex> {
vec![
Complex::from( 0., 0.),
Complex::from( 1., 0.),
Complex::from(-1., 0.),
Complex::from( 0., 1.),
Complex::from( 0., -1.),
Complex::from( 1., 1.),
Complex::from(-1., -1.)
]
}
#[test]
fn test_op_arithm_add() {
macro_rules! assert_op {
($z1:ident, $z2:ident) => {
let z_th = $z1 + $z2;
let z_exp = Complex::from(
$z1.real() + $z2.real(),
$z1.imag() + $z2.imag()
);
assert_eq!(z_th.real(), z_exp.real());
assert_eq!(z_th.imag(), z_exp.imag());
};
}
let gen_data = generate_data();
for z1 in &gen_data {
for z2 in &gen_data {
assert_op!(z1, z2);
}
}
for z1 in gen_data.clone() {
for z2 in &gen_data {
assert_op!(z1, z2);
}
}
for z1 in &gen_data {
for z2 in gen_data.clone() {
assert_op!(z1, z2);
}
}
for z1 in gen_data.clone() {
for z2 in gen_data.clone() {
assert_op!(z1, z2);
}
}
}
#[test]
fn test_op_arithm_sub() {
macro_rules! assert_op {
($z1:ident, $z2:ident) => {
let z_th = $z1 - $z2;
let z_exp = Complex::from(
$z1.real() - $z2.real(),
$z1.imag() - $z2.imag()
);
assert_eq!(z_th.real(), z_exp.real());
assert_eq!(z_th.imag(), z_exp.imag());
};
}
let gen_data = generate_data();
for z1 in &gen_data {
for z2 in &gen_data {
assert_op!(z1, z2);
}
}
for z1 in gen_data.clone() {
for z2 in &gen_data {
assert_op!(z1, z2);
}
}
for z1 in &gen_data {
for z2 in gen_data.clone() {
assert_op!(z1, z2);
}
}
for z1 in gen_data.clone() {
for z2 in gen_data.clone() {
assert_op!(z1, z2);
}
}
}
#[test]
fn test_op_arithm_mul() {
macro_rules! assert_op {
($z1:ident, $z2:ident) => {
let z_th = $z1 * $z2;
let z_exp = Complex::from(
$z1.real() * $z2.real() - $z1.imag() * $z2.imag(),
$z1.real() * $z2.imag() + $z1.imag() * $z2.real(),
);
assert_eq!(z_th.real(), z_exp.real());
assert_eq!(z_th.imag(), z_exp.imag());
};
}
let gen_data = generate_data();
for z1 in &gen_data {
for z2 in &gen_data {
assert_op!(z1, z2);
}
}
for z1 in gen_data.clone() {
for z2 in &gen_data {
assert_op!(z1, z2);
}
}
for z1 in &gen_data {
for z2 in gen_data.clone() {
assert_op!(z1, z2);
}
}
for z1 in gen_data.clone() {
for z2 in gen_data.clone() {
assert_op!(z1, z2);
}
}
}
#[test]
fn test_op_arithm_div() {
macro_rules! assert_op {
($z1:ident, $z2:ident) => {
if $z2.real() == 0. &&
$z2.imag() == 0. {
continue;
}
let z_th = $z1 / $z2;
let denom = ($z2.real() * $z2.real()) + ($z2.imag() * $z2.imag());
let z_exp = Complex::from(
($z1.real() * $z2.real() + $z1.imag() * $z2.imag()) / denom,
($z1.imag() * $z2.real() - $z1.real() * $z2.imag()) / denom,
);
assert_eq!(z_th.real(), z_exp.real());
assert_eq!(z_th.imag(), z_exp.imag());
};
}
let gen_data = generate_data();
for z1 in &gen_data {
for z2 in &gen_data {
assert_op!(z1, z2);
}
}
for z1 in gen_data.clone() {
for z2 in &gen_data {
assert_op!(z1, z2);
}
}
for z1 in &gen_data {
for z2 in gen_data.clone() {
assert_op!(z1, z2);
}
}
for z1 in gen_data.clone() {
for z2 in gen_data.clone() {
assert_op!(z1, z2);
}
}
}
| true |
ce2097b36959111239b516bc8a782711ce120373
|
Rust
|
HAL22/ignore
|
/lib/src/event_driver.rs
|
UTF-8
| 2,712 | 2.84375 | 3 |
[] |
no_license
|
use rusqlite::{Connection, Result,Statement};
use std::fs::File;
use std::env;
pub struct MyEventDriver<'a>{
pub dbcontext: crate::db_context::MyDbContext<'a>,
pub filecontext: crate::file_context::MyFileContext,
}
impl<'a> MyEventDriver <'a>{
pub fn new(connection: &'a Connection,tablename:String,file:File) -> Self{
return MyEventDriver{
dbcontext: crate::db_context::MyDbContext::new(connection, tablename),
filecontext: crate::file_context::MyFileContext::new(file)
}
}
pub fn generate_gitignore_db(& mut self,keys:&Vec<String>) -> Result<()>{
let mut files_holder :Vec<String> = Vec::new();
self.dbcontext.connection.execute_batch("BEGIN TRANSACTION;")?;
for key in keys{
let mut vec :Vec<String> = self.dbcontext.read_gitignorefile(&key)?;
files_holder.push(vec.remove(0));
}
self.dbcontext.connection.execute_batch("COMMIT TRANSACTION;")?;
let result = self.filecontext.make_or_amend_gitignore_using_files(&files_holder);
return Ok(());
}
pub fn create_new_gitignore(& mut self,key:&String,value:&String) -> Result<()>{
self.dbcontext.connection.execute_batch("BEGIN TRANSACTION;")?;
let row = self.dbcontext.create_gitignorefile(key,value)?;
self.dbcontext.connection.execute_batch("COMMIT TRANSACTION;")?;
return Ok(());
}
pub fn update_gitignore(& mut self,key:&String,value:&String) -> Result<()>{
self.dbcontext.connection.execute_batch("BEGIN TRANSACTION;")?;
self.dbcontext.update_gitignorefile(key,value)?;
self.dbcontext.connection.execute_batch("COMMIT TRANSACTION;")?;
return Ok(());
}
pub fn delete_gitignore(& mut self,key:&String) -> Result<()>{
self.dbcontext.connection.execute_batch("BEGIN TRANSACTION;")?;
self.dbcontext.delete_gitignorefile(key)?;
self.dbcontext.connection.execute_batch("COMMIT TRANSACTION;")?;
return Ok(());
}
//To be removed
pub fn event_handler(& mut self,mut args: env::Args,size:i32) -> Result<(),String>{
if size<2{
return Err(String::from("Not enough inputs"));
}else{
args.next();
}
let mut keys:Vec<String> = Vec::new();
for arg in args{
keys.push(arg);
}
println!("{:?}",keys);
let c = self.generate_gitignore_db(&keys);
println!("{:?}",c);
// let r = self.create_new_gitignore(&String::from("gomaven"),&String::from("/Users/thethelafaltein/Desktop/Projects/rustlangproj/ignore/lable"));
return Ok(());
}
}
| true |
a5757031f11fa98e1141f3a7bc1093a34222d9e3
|
Rust
|
andrew-johnson-4/rdxl_static_macros
|
/tests/www.rs
|
UTF-8
| 584 | 2.75 | 3 |
[
"Apache-2.0",
"MIT"
] |
permissive
|
use rdxl_static_macros::*;
pub mod static_files {
use rdxl_static_macros::*;
#[dot_template]
fn template1(xhtml: String) -> String {
format!("{}", xhtml)
}
#[dot]
fn file() -> String {
dot_html!(
template=::template1,
"abcd"
)
}
#[dot(suffix=".txt")]
fn file2() -> String {
"aaa".to_string()
}
}
#[dot_template]
fn template1(title: String, xhtml: String) -> String {
format!("{}{}", title, xhtml)
}
#[dot]
fn index() -> String {
dot_html!(
template=::template1,
<p>Dot Hello</p>
)
}
| true |
941294814f4f31c124924ef1248196a47bd7ae13
|
Rust
|
poetinger/Web-Engineering
|
/backend/src/routes/carriers/get_carriers.rs
|
UTF-8
| 4,192 | 2.921875 | 3 |
[] |
no_license
|
//! A module dealing with the `get_carriers` routes.
use super::views::Carrier;
use crate::CorgisDbConn;
use diesel::{dsl::*, prelude::*, result::Error};
use rayon::prelude::*;
use rocket::get;
use rocket_contrib::json::Json;
use rocket_contrib_local::csv::Csv;
use rustic_hal::HalResource;
fn get_carriers_data(conn: &diesel::PgConnection, id: Option<i64>) -> Result<Vec<Carrier>, Error> {
use crate::database::schema::carriers::dsl::carriers;
use crate::database::{models, schema};
match id {
None => match carriers.load::<models::Carrier>(conn).optional()? {
Some(carrier_data) => Ok(carrier_data.into_par_iter().map(Carrier::from).collect()),
None => Ok(Vec::new()),
},
Some(id) => {
// Find the airports that match the provided id.
let airport_id: i64 = match schema::airports::table
.find(id)
.select(schema::airports::id)
.first(conn)
.optional()?
{
None => return Ok(Vec::new()),
Some(airport_id) => airport_id,
};
let carrier_ids: Vec<i64> = match schema::statistics::table
.filter(schema::statistics::airport_id.eq(airport_id))
.inner_join(carriers)
.select(schema::carriers::id)
.load(conn)
.optional()?
{
None => return Ok(Vec::new()),
Some(carrier_ids) => carrier_ids,
};
match carriers
.filter(schema::carriers::id.eq(any(carrier_ids)))
.load::<models::Carrier>(conn)
.optional()?
{
Some(carrier_data) => Ok(carrier_data.into_par_iter().map(Carrier::from).collect()),
None => Ok(Vec::new()),
}
}
}
}
/// Get the JSON representation of the carriers in the database.
#[get("/?<airport>", format = "application/json", rank = 1)]
pub fn get_carriers_json(
conn: CorgisDbConn,
airport: Option<i64>,
) -> Result<Json<Vec<Carrier>>, Error> {
get_carriers_data(&conn, airport).map(Json)
}
/// Get the CSV representation of the carriers in the database.
#[get("/?<airport>", format = "text/csv", rank = 2)]
pub fn get_carriers_csv(
conn: CorgisDbConn,
airport: Option<i64>,
) -> Result<Csv<Vec<Carrier>>, Error> {
fn convertor(carriers: &Vec<Carrier>) -> String {
let mut wtr = csv::WriterBuilder::default().from_writer(Vec::new());
for carrier in carriers {
wtr.serialize(carrier).unwrap();
}
String::from_utf8(wtr.into_inner().unwrap()).unwrap()
};
get_carriers_data(&conn, airport).map(|data| Csv(data, convertor))
}
/// Get the HAL representation of the carriers in the database.
#[get("/?<airport>", format = "application/hal+json", rank = 3)]
pub fn get_carriers_hal(
conn: CorgisDbConn,
airport: Option<i64>,
) -> Result<Json<Vec<HalResource>>, Error> {
let result = get_carriers_data(&conn, airport)?
.into_par_iter()
.map(|data| match airport {
Some(airport) => HalResource::new(&data)
.with_link("self", format!("/carriers/{}", data.id))
.with_link("carriers", format!("/airports?carrier={}", data.id))
.with_link(
"statistics",
format!("/statistics?airport={}&carrier={}", data.id, airport),
),
None => HalResource::new(&data)
.with_link("self", format!("/carriers/{}", data.id))
.with_link("carriers", format!("/airports?carrier={}", data.id))
.with_link("statistics", format!("/statistics?carrier={}", data.id)),
})
.collect();
Ok(Json(result))
}
/// Get the default representation of the carriers in the data store. This is
/// executed if the other routes are not matched.
#[get("/?<airport>", rank = 4)]
pub fn get_carriers_default(
conn: CorgisDbConn,
airport: Option<i64>,
) -> Result<Json<Vec<Carrier>>, diesel::result::Error> {
get_carriers_json(conn, airport)
}
| true |
2d53f46bc66c1ddb19c1055b82a89361854b57b9
|
Rust
|
mikialex/rendiation
|
/interphaser/src/core/graphics/mod.rs
|
UTF-8
| 1,771 | 2.78125 | 3 |
[] |
no_license
|
use rendiation_texture::Size;
use webgpu::GPU2DTextureView;
use crate::*;
pub trait UIPresenter {
fn resize(&mut self, size: Size);
fn render(&mut self, content: &UIPresentation, fonts: &FontManager, texts: &mut TextCache);
}
pub struct PresentationBuilder<'a> {
pub fonts: &'a FontManager,
pub texts: &'a mut TextCache,
pub present: UIPresentation,
parent_offset_chain: Vec<UIPosition>,
current_origin_offset: UIPosition,
}
impl<'a> PresentationBuilder<'a> {
pub fn new(fonts: &'a FontManager, texts: &'a mut TextCache) -> Self {
Self {
fonts,
texts,
present: UIPresentation::new(),
parent_offset_chain: Vec::new(),
current_origin_offset: Default::default(),
}
}
pub fn push_offset(&mut self, offset: UIPosition) {
self.parent_offset_chain.push(offset);
self.current_origin_offset.x += offset.x;
self.current_origin_offset.y += offset.y;
}
pub fn pop_offset(&mut self) {
if let Some(offset) = self.parent_offset_chain.pop() {
self.current_origin_offset.x -= offset.x;
self.current_origin_offset.y -= offset.y;
}
}
pub fn current_origin_offset(&self) -> UIPosition {
self.current_origin_offset
}
}
#[derive(Clone)]
pub enum Style {
SolidColor(Color),
Texture(GPU2DTextureView),
}
#[derive(Clone)]
pub enum Primitive {
Quad((RectangleShape, Style)),
Text(TextLayoutRef),
}
pub struct UIPresentation {
pub view_size: UISize,
pub primitives: Vec<Primitive>,
}
impl UIPresentation {
pub fn new() -> Self {
Self {
primitives: Vec::new(),
view_size: UISize::new(1000., 1000.),
}
}
pub fn reset(&mut self) {
self.primitives.clear()
}
}
impl Default for UIPresentation {
fn default() -> Self {
Self::new()
}
}
| true |
b3cace6f9f7c387a9e53205a2b87a0d994d9ca42
|
Rust
|
anuj-apdev/rust-learn
|
/src/mio/main.rs
|
UTF-8
| 2,387 | 3.359375 | 3 |
[] |
no_license
|
use std::error::Error;
use mio::net::{TcpListener, TcpStream};
use mio::{Events, Interest, Poll, Token};
// Some tokens to allow us to identify which event is for which socket.
const SERVER: Token = Token(0);
const CLIENT: Token = Token(1);
fn main() -> Result<(), Box<dyn Error>> {
// Create a poll instance.
let mut poll = Poll::new()?;
// Create storage for events.
let mut events = Events::with_capacity(128);
// Setup the server socket.
let addr = "127.0.0.1:13265".parse()?;
let mut server = TcpListener::bind(addr)?;
// Start listening for incoming connections.
poll.registry()
.register(&mut server, SERVER, Interest::READABLE)?;
// Setup the client socket.
let mut client = TcpStream::connect(addr)?;
// Register the socket.
poll.registry()
.register(&mut client, CLIENT, Interest::READABLE | Interest::WRITABLE)?;
// Start an event loop.
loop {
// Poll Mio for events, blocking until we get an event.
poll.poll(&mut events, None)?;
// Process each event.
for event in events.iter() {
// We can use the token we previously provided to `register` to
// determine for which socket the event is.
match event.token() {
SERVER => {
// If this is an event for the server, it means a connection
// is ready to be accepted.
//
// Accept the connection and drop it immediately. This will
// close the socket and notify the client of the EOF.
let connection = server.accept();
drop(connection);
}
CLIENT => {
if event.is_writable() {
// We can (likely) write to the socket without blocking.
}
if event.is_readable() {
// We can (likely) read from the socket without blocking.
}
// Since the server just shuts down the connection, let's
// just exit from our event loop.
return Ok(());
}
// We don't expect any events with tokens other than those we provided.
_ => unreachable!(),
}
}
}
}
| true |
a8805a3ce7711bbcd481b8cf5aef2eb71d101b65
|
Rust
|
abhijeetbhagat/boa
|
/boa/src/syntax/parser/statement/declaration/hoistable.rs
|
UTF-8
| 3,480 | 3.0625 | 3 |
[
"Unlicense",
"MIT"
] |
permissive
|
//! Hoistable declaration parsing.
//!
//! More information:
//! - [ECMAScript specification][spec]
//!
//! [spec]: https://tc39.es/ecma262/#prod-HoistableDeclaration
use crate::{
syntax::{
ast::{node::FunctionDecl, Keyword, Node, Punctuator},
parser::{
function::FormalParameters, function::FunctionBody, statement::BindingIdentifier,
AllowAwait, AllowDefault, AllowYield, Cursor, ParseError, ParseResult, TokenParser,
},
},
BoaProfiler,
};
/// Hoistable declaration parsing.
///
/// More information:
/// - [ECMAScript specification][spec]
///
/// [spec]: https://tc39.es/ecma262/#prod-FunctionDeclaration
#[derive(Debug, Clone, Copy)]
pub(super) struct HoistableDeclaration {
allow_yield: AllowYield,
allow_await: AllowAwait,
is_default: AllowDefault,
}
impl HoistableDeclaration {
/// Creates a new `HoistableDeclaration` parser.
pub(super) fn new<Y, A, D>(allow_yield: Y, allow_await: A, is_default: D) -> Self
where
Y: Into<AllowYield>,
A: Into<AllowAwait>,
D: Into<AllowDefault>,
{
Self {
allow_yield: allow_yield.into(),
allow_await: allow_await.into(),
is_default: is_default.into(),
}
}
}
impl TokenParser for HoistableDeclaration {
type Output = Node;
fn parse(self, cursor: &mut Cursor<'_>) -> ParseResult {
let _timer = BoaProfiler::global().start_event("HoistableDeclaration", "Parsing");
// TODO: check for generators and async functions + generators
FunctionDeclaration::new(self.allow_yield, self.allow_await, self.is_default)
.parse(cursor)
.map(Node::from)
}
}
/// Function declaration parsing.
///
/// More information:
/// - [MDN documentation][mdn]
/// - [ECMAScript specification][spec]
///
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function
/// [spec]: https://tc39.es/ecma262/#prod-FunctionDeclaration
#[derive(Debug, Clone, Copy)]
struct FunctionDeclaration {
allow_yield: AllowYield,
allow_await: AllowAwait,
is_default: AllowDefault,
}
impl FunctionDeclaration {
/// Creates a new `FunctionDeclaration` parser.
fn new<Y, A, D>(allow_yield: Y, allow_await: A, is_default: D) -> Self
where
Y: Into<AllowYield>,
A: Into<AllowAwait>,
D: Into<AllowDefault>,
{
Self {
allow_yield: allow_yield.into(),
allow_await: allow_await.into(),
is_default: is_default.into(),
}
}
}
impl TokenParser for FunctionDeclaration {
type Output = FunctionDecl;
fn parse(self, cursor: &mut Cursor<'_>) -> Result<Self::Output, ParseError> {
cursor.expect(Keyword::Function, "function declaration")?;
// TODO: If self.is_default, then this can be empty.
let name = BindingIdentifier::new(self.allow_yield, self.allow_await).parse(cursor)?;
cursor.expect(Punctuator::OpenParen, "function declaration")?;
let params = FormalParameters::new(false, false).parse(cursor)?;
cursor.expect(Punctuator::CloseParen, "function declaration")?;
cursor.expect(Punctuator::OpenBlock, "function declaration")?;
let body = FunctionBody::new(self.allow_yield, self.allow_await).parse(cursor)?;
cursor.expect(Punctuator::CloseBlock, "function declaration")?;
Ok(FunctionDecl::new(name, params, body))
}
}
| true |
739c59a8d7665f9f8be0c8a0a36d2629b7b33a9f
|
Rust
|
nVitius/ktmpl
|
/src/parameter.rs
|
UTF-8
| 4,456 | 3.328125 | 3 |
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
use std::collections::HashMap;
use std::error::Error;
use std::str::FromStr;
use base64::encode;
use clap::Values;
use yaml::Yaml;
pub struct Parameter {
pub description: Option<String>,
pub display_name: Option<String>,
pub name: String,
pub parameter_type: Option<ParameterType>,
pub required: bool,
pub value: Option<String>,
}
#[derive(PartialEq)]
pub enum ParameterType {
Base64,
Bool,
Int,
String,
}
pub struct UserValue {
pub base64_encoded: bool,
pub value: String,
}
pub type ParamMap = HashMap<String, Parameter>;
pub type UserValues = HashMap<String, UserValue>;
fn should_base64_encode(parameter_type: &Option<ParameterType>, user_value: &UserValue)
-> bool {
if parameter_type.is_none() || parameter_type.as_ref().unwrap() != &ParameterType::Base64 {
return false;
}
!user_value.base64_encoded
}
impl Parameter {
pub fn new(yaml: &Yaml, user_values: &UserValues) -> Result<Self, String> {
let description = match yaml["description"] {
Yaml::String(ref description) => Some(description.clone()),
_ => None,
};
let display_name = match yaml["displayName"] {
Yaml::String(ref description) => Some(description.clone()),
_ => None,
};
let name = match yaml["name"] {
Yaml::String(ref name) => name.clone(),
_ => return Err("Parameters must have a \"name\" field.".to_owned()),
};
let parameter_type = match yaml["parameterType"].as_str() {
Some(ref parameter_type) => Some(try!(parameter_type.parse())),
None => None,
};
let required = yaml["required"].as_bool().unwrap_or(false);
let value = match user_values.get(&name) {
Some(user_value) => {
if should_base64_encode(¶meter_type, &user_value) {
match encode(&user_value.value) {
Ok(v) => Some(v),
Err(error) => return Err(format!("{}", error.description())),
}
} else {
Some(user_value.value.clone())
}
}
None => match yaml["value"] {
Yaml::Boolean(ref value) => Some(format!("{}", value)),
Yaml::Integer(ref value) => Some(format!("{}", value)),
Yaml::String(ref value) => Some(value.clone()),
_ => if required {
return Err(
format!(
"Parameter {} required and must be {}",
display_name.unwrap_or(name),
parameter_type.map(|pt| match pt {
ParameterType::Base64 => "base64",
ParameterType::Bool => "a bool",
ParameterType::Int => "an int",
ParameterType::String => "a string"
}).unwrap_or("base64, bool, int, or string")
)
)
} else {
None
},
}
};
Ok(Parameter {
description: description,
display_name: display_name,
name: name,
parameter_type: parameter_type,
required: required,
value: value,
})
}
}
impl FromStr for ParameterType {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"base64" => Ok(ParameterType::Base64),
"bool" => Ok(ParameterType::Bool),
"int" => Ok(ParameterType::Int),
"string" => Ok(ParameterType::String),
_ => Err("parameterType must be base64, bool, int, or string.".to_owned()),
}
}
}
pub fn user_values(mut parameters: Values, base64_encoded: bool) -> UserValues {
let mut user_values = UserValues::new();
loop {
if let Some(name) = parameters.next() {
let value = parameters.next().expect("Parameter was missing its value.");
let user_value = UserValue {
base64_encoded: base64_encoded,
value: value.to_string(),
};
user_values.insert(name.to_string(), user_value);
} else {
break;
}
}
user_values
}
| true |
d4e2bd9aec5985bee45803e76e787f0bb31bb7c9
|
Rust
|
ExLeonem/mobile_computing
|
/server/src/models.rs
|
UTF-8
| 5,292 | 3.0625 | 3 |
[] |
no_license
|
pub mod sqlite;
pub use self::sqlite::*;
#[derive(Debug)]
pub enum DatabaseError {
AlreadyExists,
NotFound,
CouldNotCrateNewEntry,
SqliteError,
UnknownError,
}
impl std::error::Error for DatabaseError {
fn description(&self) -> &str {
"use fmt::display()"
}
fn cause(&self) -> Option<&std::error::Error> {
None
}
}
impl std::fmt::Display for DatabaseError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
DatabaseError::AlreadyExists => write!(f, "Value already exists in Database"),
DatabaseError::NotFound => write!(f, "Could not find entry"),
DatabaseError::CouldNotCrateNewEntry => write!(f, "Could not create new table entry"),
DatabaseError::SqliteError => write!(f, "SQLite Error"),
DatabaseError::UnknownError => write!(f, "Encounterd an unknown error"),
}
}
}
#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize)]
pub struct Schedule {
pub id: Option<i32>,
pub device: String,
pub integration: String,
pub led_setting: LedSetting,
pub activation_time: chrono::NaiveDateTime,
pub active: bool,
pub running: bool,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct NewSchedule {
pub id: Option<i32>,
pub device: String,
pub integration: String,
pub led_setting: LedSetting,
pub activation_time: chrono::NaiveDateTime,
pub active: bool,
}
#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize)]
pub enum LedMode {
Default,
Unknown,
}
impl From<LedMode> for i32 {
fn from(item: LedMode) -> Self {
match item {
LedMode::Default => 0,
_ => -1,
}
}
}
impl From<i32> for LedMode {
fn from(item: i32) -> Self {
match item {
0 => LedMode::Default,
_ => LedMode::Unknown,
}
}
}
#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize)]
pub struct LedSetting {
pub mode: LedMode,
pub color: [u8; 3],
}
impl From<DbSchedule> for Schedule {
fn from(item: DbSchedule) -> Self {
let led_setting = LedSetting {
mode: item.color_mode.into(),
color: [
item.color_red as u8,
item.color_green as u8,
item.color_blue as u8,
],
};
Schedule {
id: match item.schedule_id {
-1 => None,
x => Some(x),
},
device: item.device,
integration: item.integration,
led_setting,
activation_time: item.activation_time,
active: item.active,
running: item.running,
}
}
}
impl From<DbSchedule> for NewDbSchedule {
fn from(item: DbSchedule) -> Self {
NewDbSchedule {
device: item.device,
integration: item.integration,
color_mode: item.color_mode,
color_red: item.color_red,
color_green: item.color_green,
color_blue: item.color_blue,
activation_time: item.activation_time,
active: item.active,
running: item.running,
}
}
}
impl From<NewSchedule> for NewDbSchedule {
fn from(item: NewSchedule) -> Self {
NewDbSchedule {
device: item.device,
integration: item.integration,
color_mode: item.led_setting.mode.into(),
color_red: item.led_setting.color[0] as i32,
color_green: item.led_setting.color[1] as i32,
color_blue: item.led_setting.color[2] as i32,
activation_time: item.activation_time,
active: item.active,
running: false,
}
}
}
impl From<Schedule> for NewDbSchedule {
fn from(item: Schedule) -> Self {
DbSchedule::from(item).into()
}
}
impl From<Schedule> for DbSchedule {
fn from(item: Schedule) -> Self {
DbSchedule {
schedule_id: item.id.unwrap_or(-1),
device: item.device,
integration: item.integration,
color_mode: item.led_setting.mode.into(),
color_red: item.led_setting.color[0] as i32,
color_green: item.led_setting.color[1] as i32,
color_blue: item.led_setting.color[2] as i32,
activation_time: item.activation_time,
active: item.active,
running: item.running,
}
}
}
use super::schema::schedules;
#[derive(Debug, Clone, Queryable, AsChangeset, Deserialize, Serialize)]
#[table_name = "schedules"]
pub struct DbSchedule {
pub schedule_id: i32,
pub device: String,
pub integration: String,
pub color_mode: i32,
pub color_red: i32,
pub color_green: i32,
pub color_blue: i32,
pub activation_time: chrono::NaiveDateTime,
pub active: bool,
pub running: bool,
}
#[derive(Debug, Insertable, Deserialize, Serialize)]
#[table_name = "schedules"]
pub struct NewDbSchedule {
pub device: String,
pub integration: String,
pub color_mode: i32,
pub color_red: i32,
pub color_green: i32,
pub color_blue: i32,
pub activation_time: chrono::NaiveDateTime,
pub active: bool,
pub running: bool,
}
| true |
046778dbeced92332cc89fd7be9839dc327d9bd5
|
Rust
|
xpeerchain/xpeerchain
|
/language/bytecode_verifier/invalid_mutations/src/bounds.rs
|
UTF-8
| 18,042 | 2.640625 | 3 |
[
"Apache-2.0"
] |
permissive
|
// Copyright (c) The XPeer Core Contributors
// SPDX-License-Identifier: Apache-2.0
use proptest::{
prelude::*,
sample::{self, Index as PropIndex},
};
use proptest_helpers::pick_slice_idxs;
use std::collections::BTreeMap;
use vm::{
errors::{VMStaticViolation, VerificationError},
file_format::{
AddressPoolIndex, CompiledModule, CompiledModuleMut, FieldDefinitionIndex,
FunctionHandleIndex, FunctionSignatureIndex, LocalsSignatureIndex, ModuleHandleIndex,
StringPoolIndex, StructHandleIndex, TableIndex, TypeSignatureIndex,
},
internals::ModuleIndex,
views::{ModuleView, SignatureTokenView},
IndexKind,
};
mod code_unit;
pub use code_unit::{ApplyCodeUnitBoundsContext, CodeUnitBoundsMutation};
/// Represents the number of pointers that exist out from a node of a particular kind.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum PointerKind {
/// Exactly one pointer out with this index kind as its destination.
One(IndexKind),
/// Zero or one pointer out with this index kind as its destination. Like the `?` operator in
/// regular expressions.
Optional(IndexKind),
/// Zero or more pointers out with this index kind as its destination. Like the `*` operator
/// in regular expressions.
Star(IndexKind),
}
impl PointerKind {
/// A list of what pointers (indexes) exist out from a particular kind of node within the
/// module.
///
/// The only special case is `FunctionDefinition`, which contains a `CodeUnit` that can contain
/// one of several kinds of pointers out. That is not represented in this table.
#[inline]
pub fn pointers_from(src_kind: IndexKind) -> &'static [PointerKind] {
use IndexKind::*;
use PointerKind::*;
match src_kind {
ModuleHandle => &[One(AddressPool), One(StringPool)],
StructHandle => &[One(ModuleHandle), One(StringPool)],
FunctionHandle => &[One(ModuleHandle), One(StringPool), One(FunctionSignature)],
StructDefinition => &[One(StructHandle), One(FieldDefinition)],
FieldDefinition => &[One(StructHandle), One(StringPool), One(TypeSignature)],
FunctionDefinition => &[One(FunctionHandle), One(LocalsSignature)],
TypeSignature => &[Optional(StructHandle)],
FunctionSignature => &[Star(StructHandle)],
LocalsSignature => &[Star(StructHandle)],
StringPool => &[],
ByteArrayPool => &[],
AddressPool => &[],
// LocalPool and CodeDefinition are function-local, and this only works for
// module-scoped indexes.
// XXX maybe don't treat LocalPool and CodeDefinition the same way as the others?
LocalPool => &[],
CodeDefinition => &[],
}
}
#[inline]
pub fn to_index_kind(self) -> IndexKind {
match self {
PointerKind::One(idx) | PointerKind::Optional(idx) | PointerKind::Star(idx) => idx,
}
}
}
pub static VALID_POINTER_SRCS: &[IndexKind] = &[
IndexKind::ModuleHandle,
IndexKind::StructHandle,
IndexKind::FunctionHandle,
IndexKind::StructDefinition,
IndexKind::FieldDefinition,
IndexKind::FunctionDefinition,
IndexKind::TypeSignature,
IndexKind::FunctionSignature,
IndexKind::LocalsSignature,
];
#[cfg(test)]
mod test {
use super::*;
#[test]
fn pointer_kind_sanity() {
for variant in IndexKind::variants() {
if VALID_POINTER_SRCS.iter().any(|x| x == variant) {
assert!(
!PointerKind::pointers_from(*variant).is_empty(),
"expected variant {:?} to be a valid pointer source",
variant,
);
} else {
assert!(
PointerKind::pointers_from(*variant).is_empty(),
"expected variant {:?} to not be a valid pointer source",
variant,
);
}
}
}
}
/// Represents a single mutation to a `CompiledModule` to produce an out-of-bounds situation.
///
/// Use `OutOfBoundsMutation::strategy()` to generate them, preferably using `Vec` to generate
/// many at a time. Then use `ApplyOutOfBoundsContext` to apply those mutations.
#[derive(Debug)]
pub struct OutOfBoundsMutation {
src_kind: IndexKind,
src_idx: PropIndex,
dst_kind: IndexKind,
offset: usize,
}
impl OutOfBoundsMutation {
pub fn strategy() -> impl Strategy<Value = Self> {
(
Self::src_kind_strategy(),
any::<PropIndex>(),
any::<PropIndex>(),
0..16 as usize,
)
.prop_map(|(src_kind, src_idx, dst_kind_idx, offset)| {
let dst_kind = Self::dst_kind(src_kind, dst_kind_idx);
Self {
src_kind,
src_idx,
dst_kind,
offset,
}
})
}
// Not all source kinds can be made to be out of bounds (e.g. inherent types can't.)
fn src_kind_strategy() -> impl Strategy<Value = IndexKind> {
sample::select(VALID_POINTER_SRCS)
}
fn dst_kind(src_kind: IndexKind, dst_kind_idx: PropIndex) -> IndexKind {
dst_kind_idx
.get(PointerKind::pointers_from(src_kind))
.to_index_kind()
}
}
/// This is used for source indexing, to work with pick_slice_idxs.
impl AsRef<PropIndex> for OutOfBoundsMutation {
#[inline]
fn as_ref(&self) -> &PropIndex {
&self.src_idx
}
}
pub struct ApplyOutOfBoundsContext {
module: CompiledModuleMut,
// This is an Option because it gets moved out in apply before apply_one is called. Rust
// doesn't let you call another con-consuming method after a partial move out.
mutations: Option<Vec<OutOfBoundsMutation>>,
// Some precomputations done for signatures.
type_sig_structs: Vec<TypeSignatureIndex>,
function_sig_structs: Vec<FunctionSignatureTokenIndex>,
locals_sig_structs: Vec<(LocalsSignatureIndex, usize)>,
}
impl ApplyOutOfBoundsContext {
pub fn new(module: CompiledModule, mutations: Vec<OutOfBoundsMutation>) -> Self {
let type_sig_structs: Vec<_> = Self::type_sig_structs(&module).collect();
let function_sig_structs: Vec<_> = Self::function_sig_structs(&module).collect();
let locals_sig_structs: Vec<_> = Self::locals_sig_structs(&module).collect();
Self {
module: module.into_inner(),
mutations: Some(mutations),
type_sig_structs,
function_sig_structs,
locals_sig_structs,
}
}
pub fn apply(mut self) -> (CompiledModuleMut, Vec<VerificationError>) {
// This is a map from (source kind, dest kind) to the actual mutations -- this is done to
// figure out how many mutations to do for a particular pair, which is required for
// pick_slice_idxs below.
let mut mutation_map = BTreeMap::new();
for mutation in self
.mutations
.take()
.expect("mutations should always be present")
{
mutation_map
.entry((mutation.src_kind, mutation.dst_kind))
.or_insert_with(|| vec![])
.push(mutation);
}
let mut results = vec![];
for ((src_kind, dst_kind), mutations) in mutation_map {
// It would be cool to use an iterator here, if someone could figure out exactly how
// to get the lifetimes right :)
results.extend(self.apply_one(src_kind, dst_kind, mutations));
}
(self.module, results)
}
fn apply_one(
&mut self,
src_kind: IndexKind,
dst_kind: IndexKind,
mutations: Vec<OutOfBoundsMutation>,
) -> Vec<VerificationError> {
let src_count = match src_kind {
// Only the signature indexes that have structs in them (i.e. are in *_sig_structs)
// are going to be modifiable, so pick among them.
IndexKind::TypeSignature => self.type_sig_structs.len(),
IndexKind::FunctionSignature => self.function_sig_structs.len(),
IndexKind::LocalsSignature => self.locals_sig_structs.len(),
// For the other sorts it's always possible to change an index.
src_kind => self.module.kind_count(src_kind),
};
// Any signature can be a destination, not just the ones that have structs in them.
let dst_count = self.module.kind_count(dst_kind);
let to_mutate = pick_slice_idxs(src_count, &mutations);
mutations
.iter()
.zip(to_mutate)
.map(move |(mutation, src_idx)| {
self.set_index(
src_kind,
src_idx,
dst_kind,
dst_count,
(dst_count + mutation.offset) as TableIndex,
)
})
.collect()
}
/// Sets the particular index in the table
///
/// For example, with `src_kind` set to `ModuleHandle` and `dst_kind` set to `AddressPool`,
/// this will set self.module_handles[src_idx].address to new_idx.
///
/// This is mainly used for test generation.
fn set_index(
&mut self,
src_kind: IndexKind,
src_idx: usize,
dst_kind: IndexKind,
dst_count: usize,
new_idx: TableIndex,
) -> VerificationError {
use IndexKind::*;
// These are default values, but some of the match arms below mutate them.
let mut src_idx = src_idx;
let mut err = VMStaticViolation::IndexOutOfBounds(dst_kind, dst_count, new_idx as usize);
// A dynamic type system would be able to express this next block of code far more
// concisely. A static type system would require some sort of complicated dependent type
// structure that Rust doesn't have. As things stand today, every possible case needs to
// be listed out.
match (src_kind, dst_kind) {
(ModuleHandle, AddressPool) => {
self.module.module_handles[src_idx].address = AddressPoolIndex::new(new_idx);
}
(ModuleHandle, StringPool) => {
self.module.module_handles[src_idx].name = StringPoolIndex::new(new_idx)
}
(StructHandle, ModuleHandle) => {
self.module.struct_handles[src_idx].module = ModuleHandleIndex::new(new_idx)
}
(StructHandle, StringPool) => {
self.module.struct_handles[src_idx].name = StringPoolIndex::new(new_idx)
}
(FunctionHandle, ModuleHandle) => {
self.module.function_handles[src_idx].module = ModuleHandleIndex::new(new_idx)
}
(FunctionHandle, StringPool) => {
self.module.function_handles[src_idx].name = StringPoolIndex::new(new_idx)
}
(FunctionHandle, FunctionSignature) => {
self.module.function_handles[src_idx].signature =
FunctionSignatureIndex::new(new_idx)
}
(StructDefinition, StructHandle) => {
self.module.struct_defs[src_idx].struct_handle = StructHandleIndex::new(new_idx)
}
(StructDefinition, FieldDefinition) => {
// Consider a situation with 3 fields, and with first field = 1 and count = 2.
// A graphical representation of that might be:
//
// |___|___|___|
// idx 0 1 2
// ^ ^
// | |
// first field = 1 (first field + count) = 3
//
// Given that the lowest value for new_idx is 3 (offset 0), the goal is to make
// (first field + count) at least 4, or (new_idx + 1). This means that the first
// field would be new_idx + 1 - count.
let end_idx = new_idx + 1;
let first_new_idx = end_idx - self.module.struct_defs[src_idx].field_count;
self.module.struct_defs[src_idx].fields = FieldDefinitionIndex::new(first_new_idx);
err = VMStaticViolation::RangeOutOfBounds(
dst_kind,
dst_count,
first_new_idx as usize,
end_idx as usize,
);
}
(FieldDefinition, StructHandle) => {
self.module.field_defs[src_idx].struct_ = StructHandleIndex::new(new_idx)
}
(FieldDefinition, StringPool) => {
self.module.field_defs[src_idx].name = StringPoolIndex::new(new_idx)
}
(FieldDefinition, TypeSignature) => {
self.module.field_defs[src_idx].signature = TypeSignatureIndex::new(new_idx)
}
(FunctionDefinition, FunctionHandle) => {
self.module.function_defs[src_idx].function = FunctionHandleIndex::new(new_idx)
}
(FunctionDefinition, LocalsSignature) => {
self.module.function_defs[src_idx].code.locals = LocalsSignatureIndex::new(new_idx)
}
(TypeSignature, StructHandle) => {
// For this and the other signatures, the source index will be picked from
// only the ones that have struct handles in them.
src_idx = self.type_sig_structs[src_idx].into_index();
self.module.type_signatures[src_idx]
.0
.debug_set_sh_idx(StructHandleIndex::new(new_idx));
}
(FunctionSignature, StructHandle) => match &self.function_sig_structs[src_idx] {
FunctionSignatureTokenIndex::ReturnType(actual_src_idx, ret_idx) => {
src_idx = actual_src_idx.into_index();
self.module.function_signatures[src_idx].return_types[*ret_idx]
.debug_set_sh_idx(StructHandleIndex::new(new_idx));
}
FunctionSignatureTokenIndex::ArgType(actual_src_idx, arg_idx) => {
src_idx = actual_src_idx.into_index();
self.module.function_signatures[src_idx].arg_types[*arg_idx]
.debug_set_sh_idx(StructHandleIndex::new(new_idx));
}
},
(LocalsSignature, StructHandle) => {
let (actual_src_idx, arg_idx) = self.locals_sig_structs[src_idx];
src_idx = actual_src_idx.into_index();
self.module.locals_signatures[src_idx].0[arg_idx]
.debug_set_sh_idx(StructHandleIndex::new(new_idx));
}
_ => panic!("Invalid pointer kind: {:?} -> {:?}", src_kind, dst_kind),
}
VerificationError {
kind: src_kind,
idx: src_idx,
err,
}
}
/// Returns the indexes of type signatures that contain struct handles inside them.
fn type_sig_structs<'b>(
module: &'b CompiledModule,
) -> impl Iterator<Item = TypeSignatureIndex> + 'b {
let module_view = ModuleView::new(module);
module_view
.type_signatures()
.enumerate()
.filter_map(|(idx, signature)| {
signature
.token()
.struct_handle()
.map(|_| TypeSignatureIndex::new(idx as u16))
})
}
/// Returns the indexes of function signatures that contain struct handles inside them.
fn function_sig_structs<'b>(
module: &'b CompiledModule,
) -> impl Iterator<Item = FunctionSignatureTokenIndex> + 'b {
let module_view = ModuleView::new(module);
let return_tokens = module_view
.function_signatures()
.enumerate()
.map(|(idx, signature)| {
let idx = FunctionSignatureIndex::new(idx as u16);
Self::find_struct_tokens(signature.return_tokens(), move |arg_idx| {
FunctionSignatureTokenIndex::ReturnType(idx, arg_idx)
})
})
.flatten();
let arg_tokens = module_view
.function_signatures()
.enumerate()
.map(|(idx, signature)| {
let idx = FunctionSignatureIndex::new(idx as u16);
Self::find_struct_tokens(signature.arg_tokens(), move |arg_idx| {
FunctionSignatureTokenIndex::ArgType(idx, arg_idx)
})
})
.flatten();
return_tokens.chain(arg_tokens)
}
/// Returns the indexes of locals signatures that contain struct handles inside them.
fn locals_sig_structs<'b>(
module: &'b CompiledModule,
) -> impl Iterator<Item = (LocalsSignatureIndex, usize)> + 'b {
let module_view = ModuleView::new(module);
module_view
.locals_signatures()
.enumerate()
.map(|(idx, signature)| {
let idx = LocalsSignatureIndex::new(idx as u16);
Self::find_struct_tokens(signature.tokens(), move |arg_idx| (idx, arg_idx))
})
.flatten()
}
#[inline]
fn find_struct_tokens<'b, F, T>(
tokens: impl IntoIterator<Item = SignatureTokenView<'b, CompiledModule>> + 'b,
map_fn: F,
) -> impl Iterator<Item = T> + 'b
where
F: Fn(usize) -> T + 'b,
{
tokens
.into_iter()
.enumerate()
.filter_map(move |(arg_idx, token)| token.struct_handle().map(|_| map_fn(arg_idx)))
}
}
#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
enum FunctionSignatureTokenIndex {
ReturnType(FunctionSignatureIndex, usize),
ArgType(FunctionSignatureIndex, usize),
}
| true |
23f8b873c853b69e2fb287e56cf7c1d81a4cf7b6
|
Rust
|
danielbintar/qwe-2
|
/src/components/player.rs
|
UTF-8
| 336 | 2.78125 | 3 |
[] |
no_license
|
use amethyst::ecs::{Component, DenseVecStorage};
#[derive(Default)]
pub struct Player {
id: usize
}
impl Player {
pub fn new(id: usize) -> Self {
Self {
id
}
}
pub fn get_id(&self) -> usize {
self.id
}
}
impl Component for Player {
type Storage = DenseVecStorage<Self>;
}
| true |
ee7963dc4ec4c9a7a30d99915c07920a0cbf88c9
|
Rust
|
IThawk/rust-project
|
/rust-master/src/test/ui/borrowck/borrowck-issue-14498.rs
|
UTF-8
| 2,695 | 3.109375 | 3 |
[
"MIT",
"LicenseRef-scancode-other-permissive",
"Apache-2.0",
"BSD-3-Clause",
"BSD-2-Clause",
"NCSA"
] |
permissive
|
// This tests that we can't modify Box<&mut T> contents while they
// are borrowed (#14498).
//
// Also includes tests of the errors reported when the Box in question
// is immutable (#14270).
#![feature(box_syntax)]
struct A { a: isize }
struct B<'a> { a: Box<&'a mut isize> }
fn indirect_write_to_imm_box() {
let mut x: isize = 1;
let y: Box<_> = box &mut x;
let p = &y;
***p = 2; //~ ERROR cannot assign to `***p`
drop(p);
}
fn borrow_in_var_from_var() {
let mut x: isize = 1;
let mut y: Box<_> = box &mut x;
let p = &y;
let q = &***p;
**y = 2; //~ ERROR cannot assign to `**y` because it is borrowed
drop(p);
drop(q);
}
fn borrow_in_var_from_var_via_imm_box() {
let mut x: isize = 1;
let y: Box<_> = box &mut x;
let p = &y;
let q = &***p;
**y = 2; //~ ERROR cannot assign to `**y` because it is borrowed
drop(p);
drop(q);
}
fn borrow_in_var_from_field() {
let mut x = A { a: 1 };
let mut y: Box<_> = box &mut x.a;
let p = &y;
let q = &***p;
**y = 2; //~ ERROR cannot assign to `**y` because it is borrowed
drop(p);
drop(q);
}
fn borrow_in_var_from_field_via_imm_box() {
let mut x = A { a: 1 };
let y: Box<_> = box &mut x.a;
let p = &y;
let q = &***p;
**y = 2; //~ ERROR cannot assign to `**y` because it is borrowed
drop(p);
drop(q);
}
fn borrow_in_field_from_var() {
let mut x: isize = 1;
let mut y = B { a: box &mut x };
let p = &y.a;
let q = &***p;
**y.a = 2; //~ ERROR cannot assign to `**y.a` because it is borrowed
drop(p);
drop(q);
}
fn borrow_in_field_from_var_via_imm_box() {
let mut x: isize = 1;
let y = B { a: box &mut x };
let p = &y.a;
let q = &***p;
**y.a = 2; //~ ERROR cannot assign to `**y.a` because it is borrowed
drop(p);
drop(q);
}
fn borrow_in_field_from_field() {
let mut x = A { a: 1 };
let mut y = B { a: box &mut x.a };
let p = &y.a;
let q = &***p;
**y.a = 2; //~ ERROR cannot assign to `**y.a` because it is borrowed
drop(p);
drop(q);
}
fn borrow_in_field_from_field_via_imm_box() {
let mut x = A { a: 1 };
let y = B { a: box &mut x.a };
let p = &y.a;
let q = &***p;
**y.a = 2; //~ ERROR cannot assign to `**y.a` because it is borrowed
drop(p);
drop(q);
}
fn main() {
indirect_write_to_imm_box();
borrow_in_var_from_var();
borrow_in_var_from_var_via_imm_box();
borrow_in_var_from_field();
borrow_in_var_from_field_via_imm_box();
borrow_in_field_from_var();
borrow_in_field_from_var_via_imm_box();
borrow_in_field_from_field();
borrow_in_field_from_field_via_imm_box();
}
| true |
615193536d41629cf343b8e13ee1fb91c5d060ae
|
Rust
|
dovahcrow/binance-async-rs
|
/src/error.rs
|
UTF-8
| 1,621 | 2.640625 | 3 |
[
"MIT",
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] |
permissive
|
use http::{header::InvalidHeaderValue, StatusCode};
use serde::Deserialize;
use thiserror::Error;
#[derive(Deserialize, Debug, Clone)]
pub struct BinanceResponseError {
pub code: i64,
pub msg: String,
}
#[derive(Debug, Error)]
pub enum BinanceError {
#[error("No Api key set for private api")]
MissingApiKey,
#[error("No Api secret set for private api")]
MissingApiSecret,
#[error("Websocket is closed")]
WebsocketClosed,
#[error("Topics is empty")]
EmptyTopics,
#[error("Unknown stream {0}")]
UnknownStream(String),
#[error("Stream {0} not implemented yet")]
StreamNotImplemented(String),
#[error("User data stream event {0} not implemented yet")]
UserDataStreamEventNotImplemented(String),
#[error("Error when try to connect websocket: {0} - {1}")]
StartWebsocketError(StatusCode, String),
#[error("The field for the given event type {0} in user data stream is empty")]
EmptyUserDataStream(String),
#[error("Binance returns error: {code} - {msg}")]
BinanceResponse { code: i64, msg: String },
#[error(transparent)]
Websocket(#[from] tungstenite::Error),
#[error(transparent)]
SerdeQs(#[from] serde_qs::Error),
#[error(transparent)]
HttpHeader(#[from] InvalidHeaderValue),
#[error(transparent)]
Reqwest(#[from] reqwest::Error),
#[error(transparent)]
SerdeJson(#[from] serde_json::Error),
}
impl From<BinanceResponseError> for BinanceError {
fn from(v: BinanceResponseError) -> Self {
Self::BinanceResponse {
code: v.code,
msg: v.msg,
}
}
}
| true |
d85224dbfd093c70f91dc4660c6ae7830692193e
|
Rust
|
SynecticLabs/wrangler
|
/src/install/mod.rs
|
UTF-8
| 5,563 | 2.515625 | 3 |
[
"MIT",
"Apache-2.0"
] |
permissive
|
pub mod dependencies;
pub mod target;
use crate::terminal::emoji;
use binary_install::{Cache, Download};
use log::info;
use semver::Version;
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use lazy_static::lazy_static;
lazy_static! {
static ref CACHE: Cache = get_wrangler_cache().expect("Could not get Wrangler cache location");
}
enum ToolDownload {
NeedsInstall(Version),
InstalledAt(Download),
}
pub fn install_cargo_generate() -> Result<PathBuf, failure::Error> {
let tool_name = "cargo-generate";
let tool_author = "ashleygwilliams";
let is_binary = true;
let version = Version::parse(dependencies::GENERATE_VERSION)?;
install(tool_name, tool_author, is_binary, version)?.binary(tool_name)
}
pub fn install_wasm_pack() -> Result<PathBuf, failure::Error> {
let tool_name = "wasm-pack";
let tool_author = "rustwasm";
let is_binary = true;
let version = Version::parse(dependencies::WASM_PACK_VERSION)?;
install(tool_name, tool_author, is_binary, version)?.binary(tool_name)
}
pub fn install(
tool_name: &str,
owner: &str,
is_binary: bool,
version: Version,
) -> Result<Download, failure::Error> {
let download = match tool_needs_update(tool_name, version)? {
ToolDownload::NeedsInstall(version) => {
println!("{} Installing {} v{}...", emoji::DOWN, tool_name, version);
let binaries: Vec<&str> = if is_binary { vec![tool_name] } else { vec![] };
let download =
download_prebuilt(tool_name, owner, &version.to_string(), binaries.as_ref());
match download {
Ok(download) => Ok(download),
Err(e) => Err(failure::format_err!(
"could not download `{}`\n{}",
tool_name,
e
)),
}
}
ToolDownload::InstalledAt(download) => Ok(download),
}?;
log::debug!("tool {} located at {:?}", tool_name, download);
Ok(download)
}
fn tool_needs_update(
tool_name: &str,
target_version: Version,
) -> Result<ToolDownload, failure::Error> {
let current_installation = get_installation(tool_name, &target_version);
// if something goes wrong checking the current installation
// we shouldn't fail, we should just re-install for them
if let Ok(current_installation) = current_installation {
if let Some((installed_version, installed_location)) = current_installation {
if installed_version.major == target_version.major
&& installed_version >= target_version
{
return Ok(ToolDownload::InstalledAt(Download::at(&installed_location)));
}
}
}
Ok(ToolDownload::NeedsInstall(target_version))
}
fn get_installation(
tool_name: &str,
target_version: &Version,
) -> Result<Option<(Version, PathBuf)>, failure::Error> {
for entry in fs::read_dir(&CACHE.destination)? {
let entry = entry?;
let filename = entry.file_name().into_string();
if let Ok(filename) = filename {
if filename.starts_with(tool_name) {
let installed_version = filename
.split(&format!("{}-", tool_name))
.collect::<Vec<&str>>()[1];
let installed_version = Version::parse(installed_version);
// if the installed version can't be parsed, ignore it
if let Ok(installed_version) = installed_version {
if &installed_version == target_version {
return Ok(Some((installed_version, entry.path())));
}
}
}
}
}
Ok(None)
}
fn download_prebuilt(
tool_name: &str,
owner: &str,
version: &str,
binaries: &[&str],
) -> Result<Download, failure::Error> {
let url = match prebuilt_url(tool_name, owner, version) {
Some(url) => url,
None => failure::bail!(format!(
"no prebuilt {} binaries are available for this platform",
tool_name
)),
};
info!("prebuilt artifact {}", url);
// no binaries are expected; downloading it as an artifact
let res = if !binaries.is_empty() {
CACHE.download_version(true, tool_name, binaries, &url, version)?
} else {
CACHE.download_artifact_version(tool_name, &url, version)?
};
match res {
Some(download) => Ok(download),
None => failure::bail!("{} is not installed!", tool_name),
}
}
fn prebuilt_url(tool_name: &str, owner: &str, version: &str) -> Option<String> {
if tool_name == "wranglerjs" {
Some(format!(
"https://workers.cloudflare.com/get-wranglerjs-binary/{0}/v{1}.tar.gz",
tool_name, version
))
} else {
let target = if target::LINUX && target::x86_64 {
"x86_64-unknown-linux-musl"
} else if target::MACOS && target::x86_64 {
"x86_64-apple-darwin"
} else if target::WINDOWS && target::x86_64 {
"x86_64-pc-windows-msvc"
} else {
return None;
};
let url = format!(
"https://workers.cloudflare.com/get-binary/{0}/{1}/v{2}/{3}.tar.gz",
owner, tool_name, version, target
);
Some(url)
}
}
fn get_wrangler_cache() -> Result<Cache, failure::Error> {
if let Ok(path) = env::var("WRANGLER_CACHE") {
Ok(Cache::at(Path::new(&path)))
} else {
Cache::new("wrangler")
}
}
| true |
86d92a3f294d27667404a0921e387b31acb108bb
|
Rust
|
giuliop/advent-of-code-2020
|
/src/day19.rs
|
UTF-8
| 5,162 | 3.09375 | 3 |
[] |
no_license
|
use std::collections::{HashMap, HashSet};
use std::fs;
use std::iter::FromIterator;
enum Rule {
Literal(Vec<String>),
Single(Vec<usize>),
Double((Vec<usize>, Vec<usize>)),
}
struct ValidMessage(HashMap<usize, HashSet<String>>);
type Messages = Vec<String>;
impl ValidMessage {
fn from_str(s: &str) -> Self {
let mut rules = parse_rules(s);
let mut res = ValidMessage(HashMap::new());
while !rules.is_empty() {
for k in rules.keys().map(|x| *x).collect::<Vec<usize>>() {
let v = rules.get(&k).unwrap();
match v {
Rule::Literal(v) => {
res.0.insert(k, HashSet::from_iter(v.clone()));
rules.remove(&k);
}
Rule::Single(v) => {
if v.iter().all(|x| res.0.contains_key(x)) {
res.add(k, &v);
rules.remove(&k);
}
}
Rule::Double((v1, v2)) => {
if v1.iter().all(|x| res.0.contains_key(x))
&& v2.iter().all(|x| res.0.contains_key(x))
{
res.add_double(k, &v1, &v2);
rules.remove(&k);
}
}
}
}
}
res
}
fn add(&mut self, key: usize, value: &Vec<usize>) {
let v = value.iter().fold(vec!["".to_string()], |acc, k| {
combinations(&acc, self.0.get(k).unwrap())
});
self.0.insert(key, HashSet::from_iter(v));
}
fn add_double(&mut self, key: usize, v1: &Vec<usize>, v2: &Vec<usize>) {
let mut v1 = v1.iter().fold(vec!["".to_string()], |acc, k| {
combinations(&acc, self.0.get(k).unwrap())
});
let v2 = v2.iter().fold(vec!["".to_string()], |acc, k| {
combinations(&acc, self.0.get(k).unwrap())
});
v1.extend(v2);
self.0.insert(key, HashSet::from_iter(v1));
}
}
fn combinations(v1: &Vec<String>, v2: &HashSet<String>) -> Vec<String> {
let mut res = Vec::new();
for x in v1 {
for y in v2 {
res.push(x.clone() + y);
}
}
res
}
fn nums_from(s: &str) -> Vec<usize> {
s.split(' ')
.filter_map(|s| s.parse::<usize>().ok())
.collect()
}
fn parse_rules(s: &str) -> HashMap<usize, Rule> {
let mut h = HashMap::new();
for rule in s.lines() {
let mut kv = rule.split(": ");
let k: usize = kv.next().unwrap().parse().unwrap();
let v: &str = kv.next().unwrap();
let v0: char = v.chars().next().unwrap();
let v = match v0 {
'"' => Rule::Literal(vec![v[1..v.len() - 1].to_string()]),
_ => match v.find(|x| x == '|') {
Some(idx) => Rule::Double((
nums_from(&v[..idx - 1]),
nums_from(&v[idx + 2..]),
)),
None => Rule::Single(nums_from(v)),
},
};
h.insert(k, v);
}
h
}
fn parse_input(s: &str) -> (ValidMessage, Messages) {
let mut data = s.split("\n\n");
(
ValidMessage::from_str(data.next().unwrap()),
data.next()
.unwrap()
.lines()
.map(|s| s.to_string())
.collect(),
)
}
pub fn a() -> String {
let data = fs::read_to_string("../input/day19").expect("error reading file");
let (rules, msg) = parse_input(&data);
let valid: &HashSet<String> = rules.0.get(&0).unwrap();
msg.iter()
.filter(|m| valid.contains(*m))
.count()
.to_string()
}
// new 8 -> "8: 42 | 42 8"
// new 11 -> "11: 42 31 | 42 11 31"
pub fn b() -> String {
let data = fs::read_to_string("../input/day19").expect("error reading file");
let (rules, msg) = parse_input(&data);
let valid: &HashSet<String> = rules.0.get(&0).unwrap();
let r42 = rules.0.get(&42).unwrap();
let r31 = rules.0.get(&31).unwrap();
let len = r42.iter().next().unwrap().len();
assert!(
r42.iter().all(|x| x.len() == len) && r31.iter().all(|x| x.len() == len)
);
msg.iter()
.filter(|m| valid.contains(*m) || is_valid_by_new_rules(*m, &r42, &r31, len))
.count()
.to_string()
}
fn is_valid_by_new_rules(
m: &str,
r42: &HashSet<String>,
r31: &HashSet<String>,
sublen: usize,
) -> bool {
let head = head_matches(m, r42, sublen);
let tail = tail_matches(m, r31, sublen);
m.len() % sublen == 0
&& head >= 2
&& tail >= 1
&& head > tail
&& head + tail >= m.len() / sublen
}
fn head_matches(m: &str, ss: &HashSet<String>, sublen: usize) -> usize {
(0..(m.len() / sublen))
.take_while(|i| ss.contains(&m[i * sublen..(i + 1) * sublen]))
.count()
}
fn tail_matches(m: &str, ss: &HashSet<String>, sublen: usize) -> usize {
(0..(m.len() / sublen))
.rev()
.take_while(|i| ss.contains(&m[i * sublen..(i + 1) * sublen]))
.count()
}
| true |
2ed23ad2fadaff04191dc3bdfd76a4472a43e269
|
Rust
|
rust-db/refinery
|
/refinery_core/src/config.rs
|
UTF-8
| 14,205 | 3 | 3 |
[
"MIT"
] |
permissive
|
use crate::error::Kind;
use crate::Error;
use serde::{Deserialize, Serialize};
use std::convert::TryFrom;
use std::fs;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use url::Url;
// refinery config file used by migrate_from_config if migration from a Config struct is preferred instead of using the macros
// Config can either be instanced with [`Config::new`] or retrieved from a config file with [`Config::from_file_location`]
#[derive(Serialize, Deserialize, Debug)]
pub struct Config {
main: Main,
}
#[derive(Clone, Copy, Serialize, Deserialize, PartialEq, Debug)]
pub enum ConfigDbType {
Mysql,
Postgres,
Sqlite,
Mssql,
}
impl Config {
/// create a new config instance
pub fn new(db_type: ConfigDbType) -> Config {
Config {
main: Main {
db_type,
db_path: None,
db_host: None,
db_port: None,
db_user: None,
db_pass: None,
db_name: None,
#[cfg(feature = "tiberius-config")]
trust_cert: false,
},
}
}
/// create a new Config instance from an environment variable that contains a URL
pub fn from_env_var(name: &str) -> Result<Config, Error> {
let value = std::env::var(name).map_err(|_| {
Error::new(
Kind::ConfigError(format!("Couldn't find {} environment variable", name)),
None,
)
})?;
Config::from_str(&value)
}
/// create a new Config instance from a config file located on the file system
pub fn from_file_location<T: AsRef<Path>>(location: T) -> Result<Config, Error> {
let file = std::fs::read_to_string(&location).map_err(|err| {
Error::new(
Kind::ConfigError(format!("could not open config file, {}", err)),
None,
)
})?;
let mut config: Config = toml::from_str(&file).map_err(|err| {
Error::new(
Kind::ConfigError(format!("could not parse config file, {}", err)),
None,
)
})?;
//replace relative path with canonical path in case of Sqlite db
if config.main.db_type == ConfigDbType::Sqlite {
let mut config_db_path = config.main.db_path.ok_or_else(|| {
Error::new(
Kind::ConfigError("field path must be present for Sqlite database type".into()),
None,
)
})?;
if config_db_path.is_relative() {
let mut config_db_dir = location
.as_ref()
.parent()
//safe to call unwrap in the below cases as the current dir exists and if config was opened there are permissions on the current dir
.unwrap_or(&std::env::current_dir().unwrap())
.to_path_buf();
config_db_dir = fs::canonicalize(config_db_dir).unwrap();
config_db_path = config_db_dir.join(&config_db_path)
}
let config_db_path = config_db_path.canonicalize().map_err(|err| {
Error::new(
Kind::ConfigError(format!("invalid sqlite db path, {}", err)),
None,
)
})?;
config.main.db_path = Some(config_db_path);
}
Ok(config)
}
cfg_if::cfg_if! {
if #[cfg(feature = "rusqlite")] {
pub(crate) fn db_path(&self) -> Option<&Path> {
self.main.db_path.as_deref()
}
pub fn set_db_path(self, db_path: &str) -> Config {
Config {
main: Main {
db_path: Some(db_path.into()),
..self.main
},
}
}
}
}
cfg_if::cfg_if! {
if #[cfg(feature = "tiberius-config")] {
pub fn set_trust_cert(&mut self) {
self.main.trust_cert = true;
}
}
}
pub fn db_type(&self) -> ConfigDbType {
self.main.db_type
}
pub fn db_host(&self) -> Option<&str> {
self.main.db_host.as_deref()
}
pub fn db_port(&self) -> Option<&str> {
self.main.db_port.as_deref()
}
pub fn set_db_user(self, db_user: &str) -> Config {
Config {
main: Main {
db_user: Some(db_user.into()),
..self.main
},
}
}
pub fn set_db_pass(self, db_pass: &str) -> Config {
Config {
main: Main {
db_pass: Some(db_pass.into()),
..self.main
},
}
}
pub fn set_db_host(self, db_host: &str) -> Config {
Config {
main: Main {
db_host: Some(db_host.into()),
..self.main
},
}
}
pub fn set_db_port(self, db_port: &str) -> Config {
Config {
main: Main {
db_port: Some(db_port.into()),
..self.main
},
}
}
pub fn set_db_name(self, db_name: &str) -> Config {
Config {
main: Main {
db_name: Some(db_name.into()),
..self.main
},
}
}
}
impl TryFrom<Url> for Config {
type Error = Error;
fn try_from(url: Url) -> Result<Config, Self::Error> {
let db_type = match url.scheme() {
"mysql" => ConfigDbType::Mysql,
"postgres" => ConfigDbType::Postgres,
"postgresql" => ConfigDbType::Postgres,
"sqlite" => ConfigDbType::Sqlite,
"mssql" => ConfigDbType::Mssql,
_ => {
return Err(Error::new(
Kind::ConfigError("Unsupported database".into()),
None,
))
}
};
cfg_if::cfg_if! {
if #[cfg(feature = "tiberius-config")] {
use std::{borrow::Cow, collections::HashMap};
let query_params = url
.query_pairs()
.collect::<HashMap< Cow<'_, str>, Cow<'_, str>>>();
let trust_cert = query_params.
get("trust_cert")
.unwrap_or(&Cow::Borrowed("false"))
.parse::<bool>()
.map_err(|_| {
Error::new(
Kind::ConfigError("Invalid trust_cert value, please use true/false".into()),
None,
)
})?;
}
}
Ok(Self {
main: Main {
db_type,
db_path: Some(
url.as_str()[url.scheme().len()..]
.trim_start_matches(':')
.trim_start_matches("//")
.to_string()
.into(),
),
db_host: url.host_str().map(|r| r.to_string()),
db_port: url.port().map(|r| r.to_string()),
db_user: Some(url.username().to_string()),
db_pass: url.password().map(|r| r.to_string()),
db_name: Some(url.path().trim_start_matches('/').to_string()),
#[cfg(feature = "tiberius-config")]
trust_cert,
},
})
}
}
impl FromStr for Config {
type Err = Error;
/// create a new Config instance from a string that contains a URL
fn from_str(url_str: &str) -> Result<Config, Self::Err> {
let url = Url::parse(url_str).map_err(|_| {
Error::new(
Kind::ConfigError(format!("Couldn't parse the string '{}' as a URL", url_str)),
None,
)
})?;
Config::try_from(url)
}
}
#[derive(Serialize, Deserialize, Debug)]
struct Main {
db_type: ConfigDbType,
db_path: Option<PathBuf>,
db_host: Option<String>,
db_port: Option<String>,
db_user: Option<String>,
db_pass: Option<String>,
db_name: Option<String>,
#[cfg(feature = "tiberius-config")]
#[serde(default)]
trust_cert: bool,
}
#[cfg(any(
feature = "mysql",
feature = "postgres",
feature = "tokio-postgres",
feature = "mysql_async"
))]
pub(crate) fn build_db_url(name: &str, config: &Config) -> String {
let mut url: String = name.to_string() + "://";
if let Some(user) = &config.main.db_user {
url = url + user;
}
if let Some(pass) = &config.main.db_pass {
url = url + ":" + pass;
}
if let Some(host) = &config.main.db_host {
if config.main.db_user.is_some() {
url = url + "@" + host;
} else {
url = url + host;
}
}
if let Some(port) = &config.main.db_port {
url = url + ":" + port;
}
if let Some(name) = &config.main.db_name {
url = url + "/" + name;
}
url
}
cfg_if::cfg_if! {
if #[cfg(feature = "tiberius-config")] {
use tiberius::{AuthMethod, Config as TConfig};
impl TryFrom<&Config> for TConfig {
type Error=Error;
fn try_from(config: &Config) -> Result<Self, Self::Error> {
let mut tconfig = TConfig::new();
if let Some(host) = &config.main.db_host {
tconfig.host(host);
}
if let Some(port) = &config.main.db_port {
let port = port.parse().map_err(|_| Error::new(
Kind::ConfigError(format!("Couldn't parse value {} as mssql port", port)),
None,
))?;
tconfig.port(port);
}
if let Some(db) = &config.main.db_name {
tconfig.database(db);
}
let user = config.main.db_user.as_deref().unwrap_or("");
let pass = config.main.db_pass.as_deref().unwrap_or("");
if config.main.trust_cert {
tconfig.trust_cert();
}
tconfig.authentication(AuthMethod::sql_server(&user, &pass));
Ok(tconfig)
}
}
}
}
#[cfg(test)]
mod tests {
use super::{build_db_url, Config, Kind};
use std::io::Write;
use std::str::FromStr;
#[test]
fn returns_config_error_from_invalid_config_location() {
let config = Config::from_file_location("invalid_path").unwrap_err();
match config.kind() {
Kind::ConfigError(msg) => assert!(msg.contains("could not open config file")),
_ => panic!("test failed"),
}
}
#[test]
fn returns_config_error_from_invalid_toml_file() {
let config = "[<$%
db_type = \"Sqlite\" \n";
let mut config_file = tempfile::NamedTempFile::new_in(".").unwrap();
config_file.write_all(config.as_bytes()).unwrap();
let config = Config::from_file_location(config_file.path()).unwrap_err();
match config.kind() {
Kind::ConfigError(msg) => assert!(msg.contains("could not parse config file")),
_ => panic!("test failed"),
}
}
#[test]
fn returns_config_error_from_sqlite_with_missing_path() {
let config = "[main] \n
db_type = \"Sqlite\" \n";
let mut config_file = tempfile::NamedTempFile::new_in(".").unwrap();
config_file.write_all(config.as_bytes()).unwrap();
let config = Config::from_file_location(config_file.path()).unwrap_err();
match config.kind() {
Kind::ConfigError(msg) => {
assert_eq!("field path must be present for Sqlite database type", msg)
}
_ => panic!("test failed"),
}
}
#[test]
fn builds_sqlite_path_from_relative_path() {
let db_file = tempfile::NamedTempFile::new_in(".").unwrap();
let config = format!(
"[main] \n
db_type = \"Sqlite\" \n
db_path = \"{}\"",
db_file.path().file_name().unwrap().to_str().unwrap()
);
let mut config_file = tempfile::NamedTempFile::new_in(".").unwrap();
config_file.write_all(config.as_bytes()).unwrap();
let config = Config::from_file_location(config_file.path()).unwrap();
let parent = config_file.path().parent().unwrap();
assert!(parent.is_dir());
assert_eq!(
db_file.path().canonicalize().unwrap(),
config.main.db_path.unwrap()
);
}
#[test]
fn builds_db_url() {
let config = "[main] \n
db_type = \"Postgres\" \n
db_host = \"localhost\" \n
db_port = \"5432\" \n
db_user = \"root\" \n
db_pass = \"1234\" \n
db_name = \"refinery\"";
let config: Config = toml::from_str(config).unwrap();
assert_eq!(
"postgres://root:1234@localhost:5432/refinery",
build_db_url("postgres", &config)
);
}
#[test]
fn builds_db_env_var() {
std::env::set_var(
"DATABASE_URL",
"postgres://root:1234@localhost:5432/refinery",
);
let config = Config::from_env_var("DATABASE_URL").unwrap();
assert_eq!(
"postgres://root:1234@localhost:5432/refinery",
build_db_url("postgres", &config)
);
}
#[test]
fn builds_from_str() {
let config = Config::from_str("postgres://root:1234@localhost:5432/refinery").unwrap();
assert_eq!(
"postgres://root:1234@localhost:5432/refinery",
build_db_url("postgres", &config)
);
}
#[test]
fn builds_db_env_var_failure() {
std::env::set_var("DATABASE_URL", "this_is_not_a_url");
let config = Config::from_env_var("DATABASE_URL");
assert!(config.is_err());
}
}
| true |
d27e0b01e65e84f0ae45f935825001a182578218
|
Rust
|
ToruNiina/rustracer
|
/src/color.rs
|
UTF-8
| 14,409 | 3.671875 | 4 |
[
"MIT"
] |
permissive
|
//! RGB/RGBA colors.
//!
//! It contains color by `f32`. It supports Add, Mul, Div for RGB only.
//! Alpha blending is not supported.
//! RGB acts as 3D Vector, but Mul is implemented as Hadamard product.
//!
//! It is because the pixel in an image generated by rustracer becomes
//! transparent only when the rays does not collides with anything.
pub trait Color {
type Value;
fn r(&self) -> Self::Value;
fn g(&self) -> Self::Value;
fn b(&self) -> Self::Value;
fn a(&self) -> Self::Value;
fn set_r(&mut self, v: Self::Value);
fn set_g(&mut self, v: Self::Value);
fn set_b(&mut self, v: Self::Value);
fn set_a(&mut self, v: Self::Value);
}
#[derive(Debug, Copy, Clone, PartialEq)]
#[repr(align(16))]
pub struct RGBA {
colors: [f32; 4],
}
#[derive(Debug, Copy, Clone, PartialEq)]
#[repr(align(16))]
pub struct RGB {
colors: [f32; 4], // the last element is for padding
}
impl RGBA {
/// constructs a new RGBA color.
pub fn new(r: f32, g: f32, b: f32, a: f32) -> Self {
RGBA {colors: [r, g, b, a]}
}
/// extracts RGB part. Note that it does not perform alpha blending.
pub fn rgb(&self) -> RGB {
RGB::new(self.r(), self.g(), self.b())
}
}
impl RGB {
/// construct new RGB color.
pub fn new(r: f32, g: f32, b: f32) -> Self {
RGB {colors: [r, g, b, 0.0]}
}
#[cfg(target_feature = "sse")]
pub fn sqrt(&self) -> Self {
use std::arch::x86_64::_mm_load_ps;
use std::arch::x86_64::_mm_store_ps;
use std::arch::x86_64::_mm_sqrt_ps;
let mut retval = RGB::new(0.0, 0.0, 0.0);
unsafe {
_mm_store_ps(retval.as_mut_ptr(),
_mm_sqrt_ps(_mm_load_ps(self.as_ptr())));
}
return retval;
}
#[cfg(not(target_feature = "sse"))]
pub fn sqrt(&self) -> Self {
RGB::new(self.r() + other.r(),
self.g() + other.g(),
self.b() + other.b())
}
// private method to use SIMD is possible
fn as_ptr(&self) -> *const f32 {
self.colors.as_ptr()
}
// private method to use SIMD is possible
fn as_mut_ptr(&mut self) -> *mut f32 {
self.colors.as_mut_ptr()
}
}
impl std::convert::From<RGBA> for RGB {
/// convert RGBA image into RGB by blending with the RGB white
fn from(rgba: RGBA) -> RGB {
let s = rgba.a();
let t = 1.0 - s;
RGB::new(rgba.r(), rgba.g(), rgba.b()) * s + RGB::new(1.0, 1.0, 1.0) * t
}
}
impl std::convert::From<RGB> for RGBA {
/// convert RGB image into RGBA assuming alpha = 1.0
fn from(rgb: RGB) -> RGBA {
RGBA::new(rgb.colors[0], rgb.colors[1], rgb.colors[2], 1.0)
}
}
impl Color for RGB {
type Value = f32;
fn r(&self) -> Self::Value {self.colors[0]}
fn g(&self) -> Self::Value {self.colors[1]}
fn b(&self) -> Self::Value {self.colors[2]}
fn a(&self) -> Self::Value {1.0}
fn set_r(&mut self, v: Self::Value) {self.colors[0] = v}
fn set_g(&mut self, v: Self::Value) {self.colors[1] = v}
fn set_b(&mut self, v: Self::Value) {self.colors[2] = v}
fn set_a(&mut self, _: Self::Value) {}
}
impl Color for RGBA {
type Value = f32;
fn r(&self) -> Self::Value {self.colors[0]}
fn g(&self) -> Self::Value {self.colors[1]}
fn b(&self) -> Self::Value {self.colors[2]}
fn a(&self) -> Self::Value {self.colors[3]}
fn set_r(&mut self, v: Self::Value) {self.colors[0] = v}
fn set_g(&mut self, v: Self::Value) {self.colors[1] = v}
fn set_b(&mut self, v: Self::Value) {self.colors[2] = v}
fn set_a(&mut self, v: Self::Value) {self.colors[3] = v}
}
// --------------------------------------------------------------------------
// operators for RGB. they behave as a 3D vector.
// For RGB * RGB case, it performs Hadamard product.
// Subtracts are not supported.
// --------------------------------------------------------------------------
impl std::ops::Add for RGB {
type Output = RGB;
#[cfg(target_feature = "sse")]
fn add(self, other: RGB) -> RGB {
use std::arch::x86_64::_mm_load_ps;
use std::arch::x86_64::_mm_store_ps;
use std::arch::x86_64::_mm_add_ps;
unsafe {
let mut retval = RGB::new(0.0, 0.0, 0.0);
_mm_store_ps(retval.as_mut_ptr(), _mm_add_ps(
_mm_load_ps(self.as_ptr()), _mm_load_ps(other.as_ptr())));
return retval;
}
}
#[cfg(not(target_feature = "sse"))]
fn add(self, other: RGB) -> RGB {
RGB::new(self.r() + other.r(),
self.g() + other.g(),
self.b() + other.b())
}
}
impl std::ops::AddAssign for RGB {
#[cfg(target_feature = "sse")]
fn add_assign(&mut self, other: RGB) {
use std::arch::x86_64::_mm_load_ps;
use std::arch::x86_64::_mm_store_ps;
use std::arch::x86_64::_mm_add_ps;
unsafe {
_mm_store_ps(self.as_mut_ptr(), _mm_add_ps(
_mm_load_ps(self.as_ptr()), _mm_load_ps(other.as_ptr())));
}
}
#[cfg(not(target_feature = "sse"))]
fn add_assign(&mut self, other: RGB) {
self.colors[0] += other.r();
self.colors[1] += other.g();
self.colors[2] += other.b();
}
}
impl std::ops::Mul<f32> for RGB {
type Output = RGB;
#[cfg(target_feature = "sse")]
fn mul(self, other: f32) -> RGB {
use std::arch::x86_64::_mm_load_ps;
use std::arch::x86_64::_mm_store_ps;
use std::arch::x86_64::_mm_set1_ps;
use std::arch::x86_64::_mm_mul_ps;
unsafe {
let mut retval = RGB::new(0.0, 0.0, 0.0);
_mm_store_ps(retval.as_mut_ptr(), _mm_mul_ps(
_mm_load_ps(self.as_ptr()), _mm_set1_ps(other)));
return retval
}
}
#[cfg(not(target_feature = "sse"))]
fn mul(self, other: f32) -> RGB {
RGB::new(self.r() * other,
self.g() * other,
self.b() * other)
}
}
impl std::ops::Mul<RGB> for f32 {
type Output = RGB;
#[cfg(target_feature = "sse")]
fn mul(self, other: RGB) -> RGB {
use std::arch::x86_64::_mm_load_ps;
use std::arch::x86_64::_mm_store_ps;
use std::arch::x86_64::_mm_set1_ps;
use std::arch::x86_64::_mm_mul_ps;
unsafe {
let mut retval = RGB::new(0.0, 0.0, 0.0);
_mm_store_ps(retval.as_mut_ptr(), _mm_mul_ps(
_mm_set1_ps(self), _mm_load_ps(other.as_ptr())));
return retval
}
}
#[cfg(not(target_feature = "sse"))]
fn mul(self, other: RGB) -> RGB {
RGB::new(self * other.r(),
self * other.g(),
self * other.b())
}
}
impl std::ops::Mul<RGB> for RGB {
type Output = RGB;
#[cfg(target_feature = "sse")]
fn mul(self, other: RGB) -> RGB {
use std::arch::x86_64::_mm_load_ps;
use std::arch::x86_64::_mm_store_ps;
use std::arch::x86_64::_mm_mul_ps;
unsafe {
let mut retval = RGB::new(0.0, 0.0, 0.0);
_mm_store_ps(retval.as_mut_ptr(), _mm_mul_ps(
_mm_load_ps(self.as_ptr()), _mm_load_ps(other.as_ptr())));
return retval
}
}
#[cfg(not(target_feature = "sse"))]
fn mul(self, other: RGB) -> RGB {
RGB::new(self.r() * other.r(),
self.g() * other.g(),
self.b() * other.b())
}
}
impl std::ops::MulAssign<f32> for RGB {
#[cfg(target_feature = "sse")]
fn mul_assign(&mut self, other: f32) {
use std::arch::x86_64::_mm_load_ps;
use std::arch::x86_64::_mm_store_ps;
use std::arch::x86_64::_mm_set1_ps;
use std::arch::x86_64::_mm_mul_ps;
unsafe {
_mm_store_ps(self.as_mut_ptr(), _mm_mul_ps(
_mm_load_ps(self.as_ptr()), _mm_set1_ps(other)));
}
}
#[cfg(not(target_feature = "sse"))]
fn mul_assign(&mut self, other: f32) {
self.colors[0] *= other;
self.colors[1] *= other;
self.colors[2] *= other;
}
}
impl std::ops::MulAssign<RGB> for RGB {
#[cfg(target_feature = "sse")]
fn mul_assign(&mut self, other: RGB) {
use std::arch::x86_64::_mm_load_ps;
use std::arch::x86_64::_mm_store_ps;
use std::arch::x86_64::_mm_mul_ps;
unsafe {
_mm_store_ps(self.as_mut_ptr(), _mm_mul_ps(
_mm_load_ps(self.as_ptr()), _mm_load_ps(other.as_ptr())));
}
}
#[cfg(not(target_feature = "sse"))]
fn mul_assign(&mut self, other: RGB) {
self.colors[0] *= other.r();
self.colors[1] *= other.g();
self.colors[2] *= other.b();
}
}
impl std::ops::Div<f32> for RGB {
type Output = RGB;
#[cfg(target_feature = "sse")]
fn div(self, other: f32) -> RGB {
use std::arch::x86_64::_mm_load_ps;
use std::arch::x86_64::_mm_set1_ps;
use std::arch::x86_64::_mm_store_ps;
use std::arch::x86_64::_mm_div_ps;
unsafe {
let mut retval = RGB::new(0.0, 0.0, 0.0);
_mm_store_ps(retval.as_mut_ptr(), _mm_div_ps(
_mm_load_ps(self.as_ptr()), _mm_set1_ps(other)));
return retval
}
}
#[cfg(not(target_feature = "sse"))]
fn div(self, other: f32) -> RGB {
RGB::new(self.r() / other,
self.g() / other,
self.b() / other)
}
}
impl std::ops::Div<RGB> for RGB {
type Output = RGB;
#[cfg(target_feature = "sse")]
fn div(self, other: RGB) -> RGB {
use std::arch::x86_64::_mm_load_ps;
use std::arch::x86_64::_mm_store_ps;
use std::arch::x86_64::_mm_div_ps;
unsafe {
let mut retval = RGB::new(0.0, 0.0, 0.0);
_mm_store_ps(retval.as_mut_ptr(), _mm_div_ps(
_mm_load_ps(self.as_ptr()), _mm_load_ps(other.as_ptr())));
return retval
}
}
#[cfg(not(target_feature = "sse"))]
fn div(self, other: RGB) -> RGB {
RGB::new(self.r() / other.r(),
self.g() / other.g(),
self.b() / other.b())
}
}
impl std::ops::DivAssign<f32> for RGB {
#[cfg(target_feature = "sse")]
fn div_assign(&mut self, other: f32) {
use std::arch::x86_64::_mm_load_ps;
use std::arch::x86_64::_mm_set1_ps;
use std::arch::x86_64::_mm_store_ps;
use std::arch::x86_64::_mm_div_ps;
unsafe {
_mm_store_ps(self.as_mut_ptr(), _mm_div_ps(
_mm_load_ps(self.as_ptr()), _mm_set1_ps(other)));
}
}
#[cfg(not(target_feature = "sse"))]
fn div_assign(&mut self, other: f32) {
self.colors[0] /= other;
self.colors[1] /= other;
self.colors[2] /= other;
}
}
impl std::ops::DivAssign<RGB> for RGB {
#[cfg(target_feature = "sse")]
fn div_assign(&mut self, other: RGB) {
use std::arch::x86_64::_mm_load_ps;
use std::arch::x86_64::_mm_store_ps;
use std::arch::x86_64::_mm_div_ps;
unsafe {
_mm_store_ps(self.as_mut_ptr(), _mm_div_ps(
_mm_load_ps(self.as_ptr()), _mm_load_ps(other.as_ptr())));
}
}
#[cfg(not(target_feature = "sse"))]
fn div_assign(&mut self, other: RGB) {
self.colors[0] /= other.r();
self.colors[1] /= other.g();
self.colors[2] /= other.b();
}
}
#[cfg(test)]
mod tests {
use crate::color::*;
#[test]
fn add() {
let u = RGB::new(1.0, 2.0, 3.0);
let v = RGB::new(2.0, 3.0, 4.0);
let w = u + v;
assert_eq!(w.r(), 1.0 + 2.0);
assert_eq!(w.g(), 2.0 + 3.0);
assert_eq!(w.b(), 3.0 + 4.0);
}
#[test]
fn add_assign() {
let mut u = RGB::new(1.0, 2.0, 3.0);
let v = RGB::new(10., 10., 10.);
u += v;
assert_eq!(u.r(), 1.0 + 10.0);
assert_eq!(u.g(), 2.0 + 10.0);
assert_eq!(u.b(), 3.0 + 10.0);
}
#[test]
fn mul() {
{
let u = RGB::new(1.0, 2.0, 3.0);
let v = 2.0;
let w = u * v;
assert_eq!(w.r(), 1.0 * 2.0);
assert_eq!(w.g(), 2.0 * 2.0);
assert_eq!(w.b(), 3.0 * 2.0);
}
{
let u = RGB::new(1.0, 2.0, 3.0);
let v = RGB::new(2.0, 3.0, 4.0);
let w = u * v;
assert_eq!(w.r(), 1.0 * 2.0);
assert_eq!(w.g(), 2.0 * 3.0);
assert_eq!(w.b(), 3.0 * 4.0);
}
}
#[test]
fn mul_assign() {
{
let mut u = RGB::new(1.0, 2.0, 3.0);
let v = 2.0;
u *= v;
assert_eq!(u.r(), 1.0 * 2.0);
assert_eq!(u.g(), 2.0 * 2.0);
assert_eq!(u.b(), 3.0 * 2.0);
}
{
let mut u = RGB::new(1.0, 2.0, 3.0);
let v = RGB::new(10., 10., 10.);
u *= v;
assert_eq!(u.r(), 1.0 * 10.0);
assert_eq!(u.g(), 2.0 * 10.0);
assert_eq!(u.b(), 3.0 * 10.0);
}
}
#[test]
fn div() {
{
let u = RGB::new(1.0, 2.0, 3.0);
let v = 2.0;
let w = u / v;
assert_eq!(w.r(), 1.0 / 2.0);
assert_eq!(w.g(), 2.0 / 2.0);
assert_eq!(w.b(), 3.0 / 2.0);
}
{
let u = RGB::new(1.0, 2.0, 3.0);
let v = RGB::new(2.0, 3.0, 4.0);
let w = u / v;
assert_eq!(w.r(), 1.0 / 2.0);
assert_eq!(w.g(), 2.0 / 3.0);
assert_eq!(w.b(), 3.0 / 4.0);
}
}
#[test]
fn div_assign() {
{
let mut u = RGB::new(1.0, 2.0, 3.0);
let v = 2.0;
u /= v;
assert_eq!(u.r(), 1.0 / 2.0);
assert_eq!(u.g(), 2.0 / 2.0);
assert_eq!(u.b(), 3.0 / 2.0);
}
{
let mut u = RGB::new(1.0, 2.0, 3.0);
let v = RGB::new(10., 10., 10.);
u /= v;
assert_eq!(u.r(), 1.0 / 10.0);
assert_eq!(u.g(), 2.0 / 10.0);
assert_eq!(u.b(), 3.0 / 10.0);
}
}
#[test]
fn sqrt() {
let u = RGB::new(1.0, 2.0, 3.0);
let v = u.sqrt();
assert_eq!(v.r(), 1.0f32.sqrt());
assert_eq!(v.g(), 2.0f32.sqrt());
assert_eq!(v.b(), 3.0f32.sqrt());
}
}
| true |
96bd21e6be96264c499deda6747febd28a01a58a
|
Rust
|
Fantom-foundation/sled
|
/src/tx.rs
|
UTF-8
| 9,930 | 3.25 | 3 |
[
"MIT",
"Apache-2.0"
] |
permissive
|
//! Fully serializable (ACID) multi-`Tree` transactions
//!
//! # Examples
//!
//! ```
//! use sled::{Db, Transactional};
//!
//! let db = Db::open("tx_db").unwrap();
//!
//! // Use write-only transactions as a writebatch:
//! db.transaction(|db| {
//! db.insert(b"k1", b"cats")?;
//! db.insert(b"k2", b"dogs")?;
//! Ok(())
//! })
//! .unwrap();
//!
//! // Atomically swap two items:
//! db.transaction(|db| {
//! let v1_option = db.remove(b"k1")?;
//! let v1 = v1_option.unwrap();
//! let v2_option = db.remove(b"k2")?;
//! let v2 = v2_option.unwrap();
//!
//! db.insert(b"k1", v2);
//! db.insert(b"k2", v1);
//!
//! Ok(())
//! })
//! .unwrap();
//!
//! assert_eq!(&db.get(b"k1").unwrap().unwrap(), b"dogs");
//! assert_eq!(&db.get(b"k2").unwrap().unwrap(), b"cats");
//!
//! // Transactions also work on tuples of `Tree`s,
//! // preserving serializable ACID semantics!
//! // In this example, we treat two trees like a
//! // work queue, atomically apply updates to
//! // data and move them from the unprocessed `Tree`
//! // to the processed `Tree`.
//! let unprocessed = db.open_tree(b"unprocessed items").unwrap();
//! let processed = db.open_tree(b"processed items").unwrap();
//!
//! // An update somehow gets into the tree, which we
//! // later trigger the atomic processing of.
//! unprocessed.insert(b"k3", b"ligers").unwrap();
//!
//! // Atomically process the new item and move it
//! // between `Tree`s.
//! (&unprocessed, &processed)
//! .transaction(|(unprocessed, processed)| {
//! let unprocessed_item = unprocessed.remove(b"k3")?.unwrap();
//! let mut processed_item = b"yappin' ".to_vec();
//! processed_item.extend_from_slice(&unprocessed_item);
//! processed.insert(b"k3", processed_item)?;
//! Ok(())
//! })
//! .unwrap();
//!
//! assert_eq!(unprocessed.get(b"k3").unwrap(), None);
//! assert_eq!(&processed.get(b"k3").unwrap().unwrap(), b"yappin' ligers");
//! ```
#![allow(unused)]
#![allow(missing_docs)]
use parking_lot::RwLockWriteGuard;
use std::{cell::RefCell, collections::HashMap, fmt, rc::Rc, sync::Arc};
use crate::{Batch, Error, IVec, Result, Tree};
/// A transaction that will
/// be applied atomically to the
/// Tree.
#[derive(Clone)]
pub struct TransactionalTree {
pub(super) tree: Tree,
pub(super) writes: Rc<RefCell<HashMap<IVec, Option<IVec>>>>,
pub(super) read_cache: Rc<RefCell<HashMap<IVec, Option<IVec>>>>,
}
#[derive(Debug, Clone, PartialEq)]
pub enum TransactionError {
Conflict,
Abort,
Storage(Error),
}
impl fmt::Display for TransactionError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use TransactionError::*;
match self {
Conflict => write!(f, "Conflict during transaction"),
Abort => write!(f, "Transaction was aborted"),
Storage(e) => e.fmt(f),
}
}
}
impl std::error::Error for TransactionError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
TransactionError::Storage(ref e) => Some(e),
_ => None,
}
}
}
pub type TransactionResult<T> = std::result::Result<T, TransactionError>;
fn abort() -> TransactionError {
TransactionError::Abort
}
impl From<Error> for TransactionError {
fn from(error: Error) -> Self {
TransactionError::Storage(error)
}
}
impl TransactionalTree {
/// Set a key to a new value
pub fn insert<K, V>(
&self,
key: K,
value: V,
) -> TransactionResult<Option<IVec>>
where
IVec: From<K> + From<V>,
K: AsRef<[u8]>,
{
let old = self.get(key.as_ref())?;
let mut writes = self.writes.borrow_mut();
let _last_write =
writes.insert(IVec::from(key), Some(IVec::from(value)));
Ok(old)
}
/// Remove a key
pub fn remove<K>(&self, key: K) -> TransactionResult<Option<IVec>>
where
IVec: From<K>,
K: AsRef<[u8]>,
{
let old = self.get(key.as_ref());
let mut writes = self.writes.borrow_mut();
let _last_write = writes.insert(IVec::from(key), None);
old
}
/// Get the value associated with a key
pub fn get<K: AsRef<[u8]>>(
&self,
key: K,
) -> TransactionResult<Option<IVec>> {
let writes = self.writes.borrow();
if let Some(first_try) = writes.get(key.as_ref()) {
return Ok(first_try.clone());
}
let mut reads = self.read_cache.borrow_mut();
if let Some(second_try) = reads.get(key.as_ref()) {
return Ok(second_try.clone());
}
// not found in a cache, need to hit the backing db
let get = self.tree.get_inner(key.as_ref())?;
let last = reads.insert(key.as_ref().into(), get.clone());
assert!(last.is_none());
Ok(get)
}
/// Atomically apply multiple inserts and removals.
pub fn apply_batch(&self, batch: Batch) -> TransactionResult<()> {
for (k, v_opt) in batch.writes {
if let Some(v) = v_opt {
let _old = self.insert(k, v)?;
} else {
let _old = self.remove(k)?;
}
}
Ok(())
}
fn stage(&self) -> TransactionResult<Vec<RwLockWriteGuard<'_, ()>>> {
let guard = self.tree.concurrency_control.write();
Ok(vec![guard])
}
fn unstage(&self) {
unimplemented!()
}
fn validate(&self) -> bool {
true
}
fn commit(&self) -> Result<()> {
let mut writes = self.writes.borrow_mut();
for (k, v_opt) in &*writes {
if let Some(v) = v_opt {
let _old = self.tree.insert_inner(k, v)?;
} else {
let _old = self.tree.remove_inner(k)?;
}
}
Ok(())
}
}
pub struct TransactionalTrees {
inner: Vec<TransactionalTree>,
}
impl TransactionalTrees {
fn stage(&self) -> TransactionResult<Vec<RwLockWriteGuard<'_, ()>>> {
// we want to stage our trees in
// lexicographic order to guarantee
// no deadlocks should they block
// on mutexes in their own staging
// implementations.
let mut tree_idxs: Vec<(&[u8], usize)> = self
.inner
.iter()
.enumerate()
.map(|(idx, t)| (&*t.tree.tree_id, idx))
.collect();
tree_idxs.sort_unstable();
let mut last_idx = usize::max_value();
let mut all_guards = vec![];
for (_, idx) in tree_idxs {
if idx == last_idx {
// prevents us from double-locking
continue;
}
last_idx = idx;
let mut guards = self.inner[idx].stage()?;
all_guards.append(&mut guards);
}
Ok(all_guards)
}
fn unstage(&self) {
for tree in &self.inner {
tree.unstage();
}
}
fn validate(&self) -> bool {
for tree in &self.inner {
if !tree.validate() {
return false;
}
}
true
}
fn commit(&self) -> Result<()> {
let peg = self.inner[0].tree.context.pin_log()?;
for tree in &self.inner {
tree.commit()?;
}
// when the peg drops, it ensures all updates
// written to the log since its creation are
// recovered atomically
peg.seal_batch()
}
}
pub trait Transactional {
type View;
fn make_overlay(&self) -> TransactionalTrees;
fn view_overlay(overlay: &TransactionalTrees) -> Self::View;
fn transaction<F, R>(&self, f: F) -> TransactionResult<R>
where
F: Fn(&Self::View) -> TransactionResult<R>,
{
loop {
let tt = self.make_overlay();
let view = Self::view_overlay(&tt);
let locks = if let Ok(l) = tt.stage() {
l
} else {
tt.unstage();
continue;
};
let ret = f(&view);
if !tt.validate() {
tt.unstage();
continue;
}
match ret {
Ok(r) => {
tt.commit()?;
return Ok(r);
}
Err(TransactionError::Abort) => {
return Err(TransactionError::Abort);
}
Err(TransactionError::Conflict) => continue,
Err(TransactionError::Storage(e)) => {
return Err(TransactionError::Storage(e));
}
}
}
}
}
impl Transactional for &Tree {
type View = TransactionalTree;
fn make_overlay(&self) -> TransactionalTrees {
TransactionalTrees {
inner: vec![TransactionalTree {
tree: (*self).clone(),
writes: Default::default(),
read_cache: Default::default(),
}],
}
}
fn view_overlay(overlay: &TransactionalTrees) -> Self::View {
overlay.inner[0].clone()
}
}
impl Transactional for (&Tree, &Tree) {
type View = (TransactionalTree, TransactionalTree);
fn make_overlay(&self) -> TransactionalTrees {
TransactionalTrees {
inner: vec![
TransactionalTree {
tree: self.0.clone(),
writes: Default::default(),
read_cache: Default::default(),
},
TransactionalTree {
tree: self.1.clone(),
writes: Default::default(),
read_cache: Default::default(),
},
],
}
}
fn view_overlay(overlay: &TransactionalTrees) -> Self::View {
(overlay.inner[0].clone(), overlay.inner[1].clone())
}
}
| true |
ac2052abd82bd739f4c13ba8e3829d203524170b
|
Rust
|
iCodeIN/safe_arch
|
/src/x86_x64/popcnt.rs
|
UTF-8
| 861 | 2.96875 | 3 |
[
"Zlib"
] |
permissive
|
#![cfg(target_feature = "popcnt")]
use super::*;
/// Count the number of bits set within an `i32`
/// ```
/// # use safe_arch::*;
/// assert_eq!(population_count_i32(0), 0);
/// assert_eq!(population_count_i32(0b1), 1);
/// assert_eq!(population_count_i32(0b1001), 2);
/// ```
#[must_use]
#[inline(always)]
#[cfg_attr(docs_rs, doc(cfg(target_feature = "popcnt")))]
pub fn population_count_i32(a: i32) -> i32 {
unsafe { _popcnt32(a) }
}
/// Count the number of bits set within an `i64`
/// ```
/// # use safe_arch::*;
/// assert_eq!(population_count_i64(0), 0);
/// assert_eq!(population_count_i64(0b1), 1);
/// assert_eq!(population_count_i64(0b1001), 2);
/// ```
#[must_use]
#[inline(always)]
#[cfg(target_arch = "x86_64")]
#[cfg_attr(docs_rs, doc(cfg(target_feature = "popcnt")))]
pub fn population_count_i64(a: i64) -> i32 {
unsafe { _popcnt64(a) }
}
| true |
eeaf7393c10fe239efa2607c34689147281c96ac
|
Rust
|
alistairmgreen/AdventOfCode2017
|
/day22/src/lib.rs
|
UTF-8
| 4,800 | 3.375 | 3 |
[] |
no_license
|
use std::collections::HashMap;
use std::ops::{Index, IndexMut};
use std::str::{FromStr};
#[derive(Debug, Eq, PartialEq, Hash, Clone)]
pub enum InfectionState {
Clean,
Weakened,
Infected,
Flagged,
}
impl From<char> for InfectionState {
fn from(c: char) -> InfectionState {
match c {
'#' => InfectionState::Infected,
_ => InfectionState::Clean
}
}
}
#[derive(Debug, Default)]
pub struct InfiniteGrid {
grid: HashMap<(i32, i32), InfectionState>,
}
impl InfiniteGrid {
pub fn new() -> InfiniteGrid {
InfiniteGrid {
grid: HashMap::new(),
}
}
}
impl FromStr for InfiniteGrid {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut grid = InfiniteGrid::new();
let lines = s.lines().collect::<Vec<&str>>();
let middle_line = lines.len() as i32 / 2;
for (row, line) in lines.iter().enumerate() {
let y = middle_line - (row as i32);
let middle_column = line.len() as i32 / 2;
for (column, character) in line.chars().enumerate() {
let x = (column as i32) - middle_column;
grid[(x, y)] = character.into();
}
}
Ok(grid)
}
}
impl Index<(i32, i32)> for InfiniteGrid {
type Output = InfectionState;
fn index(&self, index: (i32, i32)) -> &Self::Output {
self.grid.get(&index).unwrap_or(&InfectionState::Clean)
}
}
impl IndexMut<(i32, i32)> for InfiniteGrid {
fn index_mut(&mut self, index: (i32, i32)) -> &mut Self::Output {
self.grid.entry(index).or_insert(InfectionState::Clean)
}
}
#[derive(Debug, Eq, PartialEq, Clone, Copy)]
enum Direction {
North,
East,
South,
West,
}
impl Direction {
fn right(&self) -> Direction {
match *self {
Direction::North => Direction::East,
Direction::East => Direction::South,
Direction::South => Direction::West,
Direction::West => Direction::North,
}
}
fn left(&self) -> Direction {
match *self {
Direction::North => Direction::West,
Direction::East => Direction::North,
Direction::South => Direction::East,
Direction::West => Direction::South,
}
}
fn reverse(&self) -> Direction {
match *self {
Direction::North => Direction::South,
Direction::East => Direction::West,
Direction::South => Direction::North,
Direction::West => Direction::East,
}
}
}
fn step(position: &(i32, i32), direction: Direction) -> (i32, i32) {
let &(x, y) = position;
match direction {
Direction::North => (x, y + 1),
Direction::East => (x + 1, y),
Direction::South => (x, y - 1),
Direction::West => (x - 1, y),
}
}
pub fn infect(grid: &mut InfiniteGrid, iterations: usize) -> usize {
let mut infections: usize = 0;
let mut position = (0, 0);
let mut direction = Direction::North;
for _ in 0..iterations {
let current_sector = &mut grid[position];
direction = match *current_sector {
InfectionState::Clean => direction.left(),
InfectionState::Weakened => direction,
InfectionState::Infected => direction.right(),
InfectionState::Flagged => direction.reverse()
};
*current_sector = match *current_sector {
InfectionState::Clean => InfectionState::Weakened,
InfectionState::Weakened => InfectionState::Infected,
InfectionState::Infected => InfectionState::Flagged,
InfectionState::Flagged => InfectionState::Clean
};
if *current_sector == InfectionState::Infected {
infections += 1;
}
position = step(&position, direction);
}
infections
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn infinite_grid_defaults_to_clean() {
let grid = InfiniteGrid::new();
assert_eq!(grid[(1, -2)], InfectionState::Clean);
}
#[test]
fn set_entry_in_infinite_grid() {
let mut grid = InfiniteGrid::new();
grid[(1, 2)] = InfectionState::Infected;
assert_eq!(grid[(1, 2)], InfectionState::Infected);
}
#[test]
fn part_2_example_a() {
let mut grid: InfiniteGrid = "..#\n#..\n...".parse().unwrap();
println!("Grid: {:?}", grid);
let infections = infect(&mut grid, 100);
assert_eq!(infections, 26);
}
#[test]
fn part_2_example_b() {
let mut grid: InfiniteGrid = "..#\n#..\n...".parse().unwrap();
let infections = infect(&mut grid, 10_000_000);
assert_eq!(infections, 2_511_944);
}
}
| true |
2f12f0f57ca3eb3bc1ea950434ca01ba44e44993
|
Rust
|
mufeedvh/jam0001
|
/LexicalCrimes/src/core/lexer.rs
|
UTF-8
| 10,355 | 2.859375 | 3 |
[
"MIT"
] |
permissive
|
use std::process;
use logos::Logos;
use super::{
tokens::*,
messages::*,
states::{ProgramState, Operation},
memory::{MemoryLayout, Value, Manager},
parser::Parser,
};
pub struct Lexer;
pub trait Analyser {
fn analyse(&self, slice: &str) -> Option<Token>;
fn tokenize(&self, slice: &str) -> Vec<Token>;
fn slice(&self, slice: &str) -> Vec<String>;
fn lexerize(&self, source: &str);
}
/// Lexical Analysis
impl Analyser for Lexer {
// stepped analysis
fn analyse(&self, slice: &str) -> Option<Token> {
let state = ProgramState::read_state();
// TODO: it's seperated for now, make it a single block with default iteration count as 1
// running inside a loop state
if state.function == Token::Loop {
// iterate parser `iter_count` times
// statement grammar
match token_grammar(slice) {
Token::Statement => {
let slice_parse = Parser {
token: Token::Statement,
slice: slice.to_string(),
};
Parser::parse(&slice_parse);
},
Token::String => return Some(Token::String),
Token::Math => return Some(Token::Math),
Token::IfCondition => {
let state = ProgramState::read_state();
// lexer skip if conditions are met on state to avoid parsing unneeded blocks
match state.function {
Token::ConditionMet => return None,
_ => {
ProgramState::set_state(
Token::IfCondition,
Operation::StateChange,
0
);
let slice_parse = Parser {
token: Token::IfCondition,
slice: slice.to_string(),
};
Parser::parse(&slice_parse);
}
}
return None
},
_ => return None
}
// maintains seperate code bodies
let codebody_key = "<CODEBODY>".to_string();
let mem_fetch = MemoryLayout::fetch(&codebody_key);
if mem_fetch.is_some() {
let mut body = String::new();
let value = match mem_fetch.unwrap() {
Value::String(value) => value,
Value::FInt(value) => value.to_string(),
Value::Int(value) => value.to_string(),
Value::Nothing => unimplemented!(),
};
body.push_str(&value);
MemoryLayout::alloc(
codebody_key,
Value::String(body)
);
} else {
MemoryLayout::alloc(
codebody_key,
Value::String(slice.to_string())
);
}
None
} else {
// statement grammar
match token_grammar(slice) {
Token::Statement => {
let slice_parse = Parser {
token: Token::Statement,
slice: slice.to_string(),
};
Parser::parse(&slice_parse);
return None
},
Token::String => return Some(Token::String),
Token::Math => return Some(Token::Math),
Token::IfCondition => {
let state = ProgramState::read_state();
// lexer skip if conditions are met on state to avoid parsing unneeded blocks
match state.function {
Token::ConditionMet => return None,
_ => {
ProgramState::set_state(
Token::IfCondition,
Operation::StateChange,
0
);
let slice_parse = Parser {
token: Token::IfCondition,
slice: slice.to_string(),
};
Parser::parse(&slice_parse);
}
}
return None
},
Token::LoopBack => {
let slice_parse = Parser {
token: Token::LoopBack,
slice: slice.to_string(),
};
Parser::parse(&slice_parse);
None
},
_ => return None
}
}
}
fn tokenize(&self, slice: &str) -> Vec<Token> {
let mut lex = Token::lexer(slice);
// maximum statement scope stays 4
// confident lookaheads here -> on assignments lexer decides slice type based on format
// parser takes care of the rest (i hope lol)
let mut tokens: Vec<Token> = Vec::with_capacity(4);
loop {
let (token, _span, slice) = (lex.next(), lex.span(), lex.slice());
if token.is_some() {
let curr_token = token.unwrap();
match token {
Some(Token::PassLex) => {
let token = self.analyse(slice);
if token.is_some() {
tokens.push(token.unwrap())
}
},
_ => tokens.push(curr_token)
}
} else {
break
}
}
tokens
}
fn slice(&self, slice: &str) -> Vec<String> {
let mut lex = Token::lexer(slice);
// maximum statement scope stays 4
let mut slices: Vec<String> = Vec::with_capacity(4);
loop {
let (token, slice) = (lex.next(), lex.slice());
if token.is_some() {
match token {
Some(Token::PassLex) => {
let token = self.analyse(slice);
if token.is_some() {
slices.push(slice.to_string())
}
},
_ => slices.push(slice.to_string())
}
} else {
break
}
}
slices
}
// main lexer
fn lexerize(&self, source: &str) {
let mut lex = Token::lexer(source);
let mut line: usize = 1;
loop {
let (token, _span, slice) = (lex.next(), lex.span(), lex.slice());
// println!("\n\n{:?} :: {:?}", slice, token);
match token {
// line coint
Some(Token::Newline) => line += 1,
// entry point
Some(Token::MainFunction) => {
ProgramState::set_state(
Token::MainFunction,
Operation::StateChange,
line
);
},
// end of a function
Some(Token::FunctionEnd) => {
ProgramState::set_state(
Token::FunctionEnd,
Operation::StateChange,
line
)
},
// start of a comand
Some(Token::CommandStart) => {
ProgramState::set_state(
Token::CommandStart,
Operation::StateChange,
line
)
},
// end of a command
Some(Token::CommandEnd) => {
ProgramState::set_state(
Token::CommandEnd,
Operation::StateChange,
line
)
},
Some(Token::Variable) => {
// set state to allocation
ProgramState::set_state(
Token::Variable,
Operation::Allocation,
line
);
// take full slice
let mut scope_lex = lex.clone();
let mut scope_slice = String::new();
// add variable key
scope_slice.push_str(slice);
scope_slice.push(' ');
loop {
// get arbitrary syntax
let (token, slice) = (scope_lex.next(), scope_lex.slice());
// read until end of statement
if token != Some(Token::Newline) {
scope_slice.push_str(slice);
scope_slice.push(' ')
} else {
break
}
}
// pass the complete slice to parser
let slice_parse = Parser {
token: Token::Variable,
slice: scope_slice,
};
Parser::parse(&slice_parse);
},
// stepped parsing
Some(Token::PassLex) => {
self.analyse(slice);
},
// finish point
None => process::exit(0),
// nope!
_ => (),
}
// main syntax validation
if line == 1 && token != Some(Token::MainFunction) {
push_error("Program should start with a main function.".to_string());
process::exit(1)
}
}
}
}
| true |
d68fdb210d795de6f1bb58e29b7b668561dd723c
|
Rust
|
astynax/weathe-rs
|
/src/environ/mod.rs
|
UTF-8
| 3,379 | 3.109375 | 3 |
[] |
no_license
|
//! # CmdLine and config-file handling stuff
use std;
use std::borrow::Borrow;
use std::io::Read;
use std::io::{Error, ErrorKind};
use types::Configuration;
use types::TempUnit;
extern crate docopt;
extern crate toml;
static USAGE: &'static str = "
Usage: weathe_rs [-f] [<provider_id>] [<city_id>]
weathe_rs \
-h
Options:
-h, --help Show this message
-f, \
--fahrenheits Show the temperature in the degrees of the \
Fahrenheit
(instead of the Celsius)
";
pub fn get_options() -> Configuration {
let args = docopt::Docopt::new(USAGE)
.and_then(|d| d.parse())
.unwrap_or_else(|e| e.exit());
let units = if args.get_bool("-f") {
Some(TempUnit::Fahrenheit)
} else {
None
};
let city = {
let arg = args.get_str("<city_id>");
if arg == "" {
None
} else {
Some(arg.to_string())
}
};
let provider = {
let arg = args.get_str("<provider_id>");
if arg == "" {
None
} else {
Some(arg.to_string())
}
};
Configuration::new(city, units, provider)
}
pub fn get_config() -> Configuration {
let home = std::env::home_dir().expect("Can't get $HOME");
let cfg_path = home.as_path().join(".config").join(".weathe-rs");
std::fs::File::open(cfg_path)
.and_then(|mut x| {
let mut content = String::new();
x.read_to_string(&mut content).and_then(|_| {
toml::Parser::new(content.borrow())
.parse()
.and_then(|root| {
match root.get("params") {
Some(&toml::Value::Table(ref t)) => Some(t.clone()),
_ => None,
}
})
.and_then(|params| {
let city = match params.get("city") {
Some(&toml::Value::Integer(ref s)) => Some(s.to_string()),
_ => None,
};
let units = match params.get("fahrenheits") {
Some(&toml::Value::Boolean(ref b)) => {
Some(if *b {
TempUnit::Fahrenheit
} else {
TempUnit::Celsius
})
}
_ => None,
};
let provider = match params.get("provider") {
Some(&toml::Value::String(ref s)) => Some(s.clone()),
_ => None,
};
Some(Configuration::new(city, units, provider))
})
.ok_or(Error::new(ErrorKind::Other, "Can't parse the config"))
})
})
.unwrap_or_else(|e| {
if e.raw_os_error() != Some(2) {
// file not found
panic!("Config parsing error: {:?}\n", e)
} else {
Configuration::new(None, None, None)
}
})
}
| true |
9d9bc3393e6993adf95685d8a921909125342553
|
Rust
|
gos-k/lisp-in-two-days-with-rust
|
/src/print.rs
|
UTF-8
| 2,146 | 3.703125 | 4 |
[] |
no_license
|
use super::eval::*;
fn symbol_expression(result: Value, paren: bool) -> String {
use Value::*;
match result {
Number(number) => number.to_string(),
Symbol(symbol) => symbol.to_string(),
Pair(lhs, rhs) => {
let lhs = symbol_expression(*lhs, true);
match *rhs {
Nil => {
if paren {
format!("({})", lhs)
} else {
format!("{}", lhs)
}
}
Pair(_, _) => {
let rhs = symbol_expression(*rhs, false);
if paren {
format!("({} {})", lhs, rhs)
} else {
format!("{} {}", lhs, rhs)
}
}
other => format!("({} . {})", lhs, symbol_expression(other, paren)),
}
}
T => "t".to_string(),
Nil => "nil".to_string(),
other => panic!("not impl {:?}", other),
}
}
pub fn print(result: EvalResult) {
match result {
Ok(value) => println!(" ~> {}", symbol_expression(value, true)),
Err(error) => println!(" !! {:?}", error),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_symbol_expression() {
use Value::*;
assert_eq!(symbol_expression(Number(0), true), "0".to_string());
assert_eq!(
symbol_expression(Symbol("test".to_string()), true),
"test".to_string()
);
assert_eq!(symbol_expression(cons(T, Nil), true), "(t)".to_string());
assert_eq!(
symbol_expression(cons(Number(0), Symbol("test".to_string())), true),
"(0 . test)".to_string()
);
assert_eq!(
symbol_expression(
cons(Number(0), cons(Symbol("test".to_string()), cons(T, Nil))),
true
),
"(0 test t)".to_string()
);
assert_eq!(symbol_expression(T, true), "t".to_string());
assert_eq!(symbol_expression(Nil, true), "nil".to_string());
}
}
| true |
728bd26f255a83652f5b1151689f1e91fe987de8
|
Rust
|
wrnice/rsafe
|
/src/nfs.rs
|
UTF-8
| 27,858 | 2.53125 | 3 |
[
"MIT"
] |
permissive
|
use rustc_serialize::json;
use rustc_serialize::base64::ToBase64;
use rustc_serialize::base64::FromBase64;
use std;
use std::collections::HashMap;
#[derive(Debug, RustcEncodable)]
pub struct CreateDirData {
pub dirPath: String,
pub isPrivate: bool,
pub metadata: String,
pub isVersioned: bool,
pub isPathShared: bool,
}
#[derive(Debug, RustcEncodable)]
pub struct ReadDirData {
pub dirPath: String,
pub isPathShared: bool,
}
#[derive(Debug, RustcDecodable)]
struct GetDirResponse {
id: String,
data: GetDirResponseData,
}
#[derive(Debug, RustcDecodable)]
pub struct GetDirResponseData {
pub info: DirInfo,
pub files: Vec<FileInfo>,
pub subDirectories: Vec<DirInfo>,
}
#[derive(Debug, RustcDecodable)]
pub struct DirInfo {
pub name: String,
pub createdOn: i64,
pub modifiedOn: i64,
pub isPrivate: bool,
pub isVersioned: bool,
pub metadata: String,
}
#[derive(Debug, RustcDecodable)]
pub struct FileInfo {
pub name: String,
pub createdOn: i64,
pub modifiedOn: i64,
pub metadata: String,
}
#[derive(Debug, RustcEncodable)]
pub struct CreateFileData {
pub filePath: String,
pub isPrivate: bool,
pub metadata: String,
pub isVersioned: bool,
pub isPathShared: bool,
}
#[derive(Debug, RustcEncodable)]
pub struct MoveFileData {
pub srcPath: String,
pub destPath: String,
pub retainSource: bool,
pub isSrcPathShared: bool,
pub isDestPathShared: bool,
}
#[derive(Debug, RustcEncodable)]
pub struct MoveDirData {
pub srcPath: String,
pub destPath: String,
pub retainSource: bool,
pub isSrcPathShared: bool,
pub isDestPathShared: bool,
}
#[derive(Debug, RustcEncodable)]
pub struct WriteFileData {
pub filePath: String,
pub isPathShared: bool,
pub fileContent: String,
pub offset: i64,
}
#[derive(Debug, RustcEncodable)]
pub struct ReadFileData {
pub filePath: String,
pub isPathShared: bool,
pub offset: i64,
pub length: i64
}
#[derive(Debug, RustcEncodable)]
pub struct DeleteFileData {
pub filePath: String,
pub isPathShared: bool,
}
fn get_base64_config() -> ::rustc_serialize::base64::Config {
::rustc_serialize::base64::Config {
char_set : ::rustc_serialize::base64::CharacterSet::Standard,
newline : ::rustc_serialize::base64::Newline::LF,
pad : true,
line_length: None,
}
}
#[derive(Debug, RustcDecodable)]
pub struct FileReadInfo {
pub filename: String,
pub filesize: i64,
pub filecreatedtime: i64,
pub filemodifiedtime: i64,
pub filemetadata: String,
pub filebody: String,
}
#[derive(Debug)]
pub enum ConnectionError { UnableToConnect , Unauthorized , FieldsAreMissing, BadRequest, UnknownError, InternalServerError, NotFound }
/* TODO
*
* read and write file with offset
*
* modify file info
*
* modify dir info
*
* move dir test ----- 400
*
*/
// create a directory
pub fn create_dir ( create_dir_data : CreateDirData , safe_register_resp : &super::auth::SafeRegisterResp ) -> Result< u16 , ConnectionError > {
let token = &safe_register_resp.token ;
let symm_key = &safe_register_resp.symm_key;
let symm_nonce = &safe_register_resp.symm_nonce;
let bearertoken = "Bearer ".to_string()+&token ;
println!("App: Begin creating directory...");
// Encode the request as a JSON.
let create_dir_json_str = ::rustc_serialize::json::encode(&create_dir_data).unwrap_or_else(|a| panic!("{:?}", a));
//println!("App: CreateDir encoded");
// Get raw bytes to be encrypted.
let create_dir_bytes = create_dir_json_str.into_bytes();
// Encrypt the raw bytes using the Secret Key (Nonce and Symmetric Key).
let create_dir_encrypted_bytes = ::sodiumoxide::crypto::secretbox::seal(&create_dir_bytes,
&symm_nonce,
&symm_key);
let create_dir_json_encrypted_b64 = create_dir_encrypted_bytes.to_base64(get_base64_config());
let url_nfs = "http://localhost:8100/nfs/directory";
let mut headers: HashMap<String, String> = HashMap::new();
headers.insert("Authorization".to_string(), bearertoken );
headers.insert("Content-Type".to_string(), "application/json".to_string());
headers.insert("Connection".to_string(), "close".to_string());
//println!("sending request");
//Send a request to launcher using "request" library
let res = ::request::post(&url_nfs, &mut headers, &create_dir_json_encrypted_b64.into_bytes() );
//println!("request sent");
//Error handling
match res {
Err(e) => { println!("{}", e); return Err(ConnectionError::UnableToConnect) }, // couldn't connect
Ok(res) =>
{
// Handle the response recieved from the launcher
if res.status_code == 401 {
println!("401 Unauthorized"); return Err(ConnectionError::Unauthorized)
} else if res.status_code == 400 {
println!("400 Bad Request"); return Err(ConnectionError::BadRequest)
} else if res.status_code == 500 {
println!("500 Internal Server Error"); return Err(ConnectionError::InternalServerError)
} else if res.status_code == 200 {
println!("200 Ok"); { return Ok(res.status_code) }
} else { return Err(ConnectionError::UnknownError) }
}
};
}
// move a directory
pub fn move_dir( move_dir_data : MoveDirData , safe_register_resp : &super::auth::SafeRegisterResp ) -> Result< u16 , ConnectionError > {
let token = &safe_register_resp.token ;
let symm_key = &safe_register_resp.symm_key;
let symm_nonce = &safe_register_resp.symm_nonce;
let bearertoken = "Bearer ".to_string()+&token ;
println!("App: Begin Moving Dir...");
// Encode the request as a JSON.
let move_dir_json_str = ::rustc_serialize::json::encode(&move_dir_data).unwrap_or_else(|a| panic!("{:?}", a));
//println!("App: MoveDir encoded");
// Get raw bytes to be encrypted.
let move_dir_bytes = move_dir_json_str.into_bytes();
// Encrypt the raw bytes using the Secret Key (Nonce and Symmetric Key).
let move_dir_encrypted_bytes = ::sodiumoxide::crypto::secretbox::seal(&move_dir_bytes,
&symm_nonce,
&symm_key);
let move_dir_json_encrypted_b64 = move_dir_encrypted_bytes.to_base64(get_base64_config());
let url_nfs_dir = "http://localhost:8100/nfs/movedir".to_string();
let mut headers: HashMap<String, String> = HashMap::new();
headers.insert("Authorization".to_string(), bearertoken );
headers.insert("Content-Type".to_string(), "application/json".to_string());
headers.insert("Connection".to_string(), "close".to_string());
//println!("sending request");
//Send a request to launcher using "request" library
let res = ::request::post(&url_nfs_dir, &mut headers, &move_dir_json_encrypted_b64.into_bytes() );
//println!("request sent");
//Error handling
match res {
Err(e) => { println!("{}", e); return Err(ConnectionError::UnableToConnect) }, // couldn't connect
Ok(res) =>
{
// Handle the response recieved from the launcher
if res.status_code == 401 {
println!("401 Unauthorized"); return Err(ConnectionError::Unauthorized)
} else if res.status_code == 400 {
println!("400 Bad Request"); return Err(ConnectionError::BadRequest)
} else if res.status_code == 404 {
println!("404 Not Found"); return Err(ConnectionError::NotFound)
} else if res.status_code == 500 {
println!("500 Internal Server Error"); return Err(ConnectionError::InternalServerError)
} else if res.status_code == 200 {
println!("200 Ok"); { return Ok(res.status_code) }
} else { return Err(ConnectionError::UnknownError) }
}
};
}
// read a directory
pub fn read_dir ( read_dir_data : ReadDirData , safe_register_resp : &super::auth::SafeRegisterResp ) -> Result< GetDirResponseData, ConnectionError > {
println!("App: Begin reading directory...");
let bearertoken = "Bearer ".to_string()+&safe_register_resp.token ;
// path Parameters
let requested_dir = read_dir_data.dirPath ;
let dir_path = ::url::percent_encoding::utf8_percent_encode ( &requested_dir, ::url::percent_encoding::FORM_URLENCODED_ENCODE_SET );
let is_path_shared = read_dir_data.isPathShared;
//println!("dirPath = {}",&dir_path);
// URL to send our 'ls' request to
let url_nfs = "http://localhost:8100/nfs/directory".to_string();
let url_nfs_ls = url_nfs + "/" + &dir_path + "/" + &is_path_shared.to_string();
//println!("url_nfs_ls = {}",&url_nfs_ls);
let mut headers: HashMap<String, String> = HashMap::new();
headers.insert("Authorization".to_string(), bearertoken );
headers.insert("Connection".to_string(), "close".to_string());
//println!("sending request");
//Send a request to launcher using "request" library
let res = ::request::get(&url_nfs_ls, &mut headers );
//println!("request sent");
//Error handling
match res {
Err(e) => { println!("{}", e); return Err(ConnectionError::UnableToConnect) }, // couldn't connect
Ok(res) =>
{
// Handle the response recieved from the launcher
if res.status_code == 401 {
println!("401 Unauthorized"); return Err(ConnectionError::Unauthorized)
} else if res.status_code == 400 {
println!("400 Bad Request"); return Err(ConnectionError::BadRequest)
} else if res.status_code == 500 {
println!("500 Internal Server Error"); return Err(ConnectionError::InternalServerError)
} else if res.status_code == 200 {
println!("200 Ok"); {
//this is the launcher's reply, in a b64 string
let resp_ls_dir_enc_b64 = res.body;
//we decode it from b64
let resp_ls_dir_enc = resp_ls_dir_enc_b64.from_base64().ok().unwrap();
// Decrypt the raw bytes using the Secret Key (Nonce and Symmetric Key).
let decrypted_response = ::sodiumoxide::crypto::secretbox::open(&resp_ls_dir_enc,
&safe_register_resp.symm_nonce,
&safe_register_resp.symm_key).ok().unwrap();
//println!( "decr = {:?}" , &decrypted_response );
// Get it into a valid UTF-8 String - this will be the JSON response.
let decrypted_response_json_str = String::from_utf8(decrypted_response).ok().unwrap();
//println!("App: GetDir Response JSON: {:?}", decrypted_response_json_str);
// Decode the JSON into expected response structure - in this case a directory response as
// stated in the RFC.
let get_dir_response: GetDirResponseData = ::rustc_serialize::json::decode(&decrypted_response_json_str)
.unwrap_or_else(|e| panic!("{:?}", e));
//println!("App: GetDir Response decoded.");
return Ok(get_dir_response) }
} else { return Err(ConnectionError::UnknownError) }
}
}; //match end
} //fn end
// delete a directory
pub fn delete_dir ( delete_dir_data : ReadDirData, safe_register_resp : &super::auth::SafeRegisterResp ) -> Result< u16 , ConnectionError > {
println!("App: Begin deleting directory...");
let bearertoken = "Bearer ".to_string()+&safe_register_resp.token ;
// path Parameters
let requested_dir = delete_dir_data.dirPath ;
let dir_path = ::url::percent_encoding::utf8_percent_encode ( &requested_dir, ::url::percent_encoding::FORM_URLENCODED_ENCODE_SET );
let is_path_shared = delete_dir_data.isPathShared;
println!("dirPath = {}",&dir_path);
// URL to send our 'ls' request to
let url_nfs = "http://localhost:8100/nfs/directory".to_string();
let url_nfs_del = url_nfs + "/" + &dir_path + "/" + &is_path_shared.to_string();
//println!("url_nfs_ls = {}",&url_nfs_del);
let mut headers: HashMap<String, String> = HashMap::new();
headers.insert("Authorization".to_string(), bearertoken );
headers.insert("Connection".to_string(), "close".to_string());
//println!("sending request");
//Send a request to launcher using "request" library
let res = ::request::delete(&url_nfs_del, &mut headers );
//println!("request sent");
//Error handling
match res {
Err(e) => { println!("{}", e); return Err(ConnectionError::UnableToConnect) }, // couldn't connect
Ok(res) =>
{
// Handle the response recieved from the launcher
if res.status_code == 401 {
println!("401 Unauthorized"); return Err(ConnectionError::Unauthorized)
} else if res.status_code == 400 {
println!("400 Bad Request"); return Err(ConnectionError::BadRequest)
} else if res.status_code == 500 {
println!("500 Internal Server Error"); return Err(ConnectionError::InternalServerError)
} else if res.status_code == 200 {
println!("200 Ok Directory was deleted"); { return Ok(res.status_code) }
} else { return Err(ConnectionError::UnknownError) }
}
};
} // fn end
// create an empty file
pub fn create_file( create_file_data : CreateFileData , safe_register_resp : &super::auth::SafeRegisterResp ) -> Result< u16 , ConnectionError > {
let token = &safe_register_resp.token ;
let symm_key = &safe_register_resp.symm_key;
let symm_nonce = &safe_register_resp.symm_nonce;
let bearertoken = "Bearer ".to_string()+&token ;
println!("App: Begin creating file...");
// Encode the request as a JSON.
let create_file_json_str = ::rustc_serialize::json::encode(&create_file_data).unwrap_or_else(|a| panic!("{:?}", a));
//println!("App: CreateFile encoded");
// Get raw bytes to be encrypted.
let create_file_bytes = create_file_json_str.into_bytes();
// Encrypt the raw bytes using the Secret Key (Nonce and Symmetric Key).
let create_file_encrypted_bytes = ::sodiumoxide::crypto::secretbox::seal(&create_file_bytes,
&symm_nonce,
&symm_key);
let create_file_json_encrypted_b64 = create_file_encrypted_bytes.to_base64(get_base64_config());
//println!( "encr = {}", &create_file_json_encrypted_b64 );
let url_nfs_file = "http://localhost:8100/nfs/file".to_string();
let mut headers: HashMap<String, String> = HashMap::new();
headers.insert("Authorization".to_string(), bearertoken );
headers.insert("Content-Type".to_string(), "application/json".to_string());
headers.insert("Connection".to_string(), "close".to_string());
//println!("sending request");
//Send a request to launcher using "request" library
let res = ::request::post(&url_nfs_file, &mut headers, &create_file_json_encrypted_b64.into_bytes() );
//println!("request sent");
//Error handling
match res {
Err(e) => { println!("{}", e); return Err(ConnectionError::UnableToConnect) }, // couldn't connect
Ok(res) =>
{
// Handle the response recieved from the launcher
if res.status_code == 401 {
println!("401 Unauthorized"); return Err(ConnectionError::Unauthorized)
} else if res.status_code == 400 {
println!("400 Bad Request"); return Err(ConnectionError::BadRequest)
} else if res.status_code == 404 {
println!("404 Not Found"); return Err(ConnectionError::NotFound)
} else if res.status_code == 500 {
println!("500 Internal Server Error"); return Err(ConnectionError::InternalServerError)
} else if res.status_code == 200 {
println!("200 Ok"); { return Ok(res.status_code) }
} else { return Err(ConnectionError::UnknownError) }
}
};
}
// move a file
pub fn move_file( move_file_data : MoveFileData , safe_register_resp : &super::auth::SafeRegisterResp ) -> Result< u16 , ConnectionError > {
let token = &safe_register_resp.token ;
let symm_key = &safe_register_resp.symm_key;
let symm_nonce = &safe_register_resp.symm_nonce;
let bearertoken = "Bearer ".to_string()+&token ;
println!("App: Begin moving file...");
// Encode the request as a JSON.
let move_file_json_str = ::rustc_serialize::json::encode(&move_file_data).unwrap_or_else(|a| panic!("{:?}", a));
//println!("App: MoveFile encoded");
// Get raw bytes to be encrypted.
let move_file_bytes = move_file_json_str.into_bytes();
// Encrypt the raw bytes using the Secret Key (Nonce and Symmetric Key).
let move_file_encrypted_bytes = ::sodiumoxide::crypto::secretbox::seal(&move_file_bytes,
&symm_nonce,
&symm_key);
let move_file_json_encrypted_b64 = move_file_encrypted_bytes.to_base64(get_base64_config());
//println!( "encr = {}", &move_file_json_encrypted_b64 );
let url_nfs_file = "http://localhost:8100/nfs/movefile".to_string();
let mut headers: HashMap<String, String> = HashMap::new();
headers.insert("Authorization".to_string(), bearertoken );
headers.insert("Content-Type".to_string(), "application/json".to_string());
headers.insert("Connection".to_string(), "close".to_string());
//println!("sending request");
//Send a request to launcher using "request" library
let res = ::request::post(&url_nfs_file, &mut headers, &move_file_json_encrypted_b64.into_bytes() );
//println!("request sent");
//Error handling
match res {
Err(e) => { println!("{}", e); return Err(ConnectionError::UnableToConnect) }, // couldn't connect
Ok(res) =>
{
// Handle the response recieved from the launcher
if res.status_code == 401 {
println!("401 Unauthorized"); return Err(ConnectionError::Unauthorized)
} else if res.status_code == 400 {
println!("400 Bad Request"); return Err(ConnectionError::BadRequest)
} else if res.status_code == 404 {
println!("404 Not Found"); return Err(ConnectionError::NotFound)
} else if res.status_code == 500 {
println!("500 Internal Server Error"); return Err(ConnectionError::InternalServerError)
} else if res.status_code == 200 {
println!("200 Ok"); { return Ok(res.status_code) }
} else { return Err(ConnectionError::UnknownError) }
}
};
}
// write to a file
pub fn write_file ( write_file_data : WriteFileData , safe_register_resp : &super::auth::SafeRegisterResp ) -> Result< u16 , ConnectionError > {
let token = &safe_register_resp.token ;
let symm_key = &safe_register_resp.symm_key;
let symm_nonce = &safe_register_resp.symm_nonce;
let bearertoken = "Bearer ".to_string()+&token ;
let fileContent = write_file_data.fileContent;
println!("App: Begin writing to file...");
// Encode the request as a JSON.
let write_file_json_str = ::rustc_serialize::json::encode(&fileContent).unwrap_or_else(|a| panic!("{:?}", a));
//println!("App: WriteFile encoded");
// Get raw bytes to be encrypted.
let write_file_bytes = write_file_json_str.into_bytes();
// Encrypt the raw bytes using the Secret Key (Nonce and Symmetric Key).
let write_file_encrypted_bytes = ::sodiumoxide::crypto::secretbox::seal(&write_file_bytes,
&symm_nonce,
&symm_key);
let write_file_json_encrypted_b64 = write_file_encrypted_bytes.to_base64(get_base64_config());
//println!( "encr = {}", &create_dir_json_encrypted_b64 );
// path Parameters
let requested_file = write_file_data.filePath ;
let file_path = ::url::percent_encoding::utf8_percent_encode ( &requested_file, ::url::percent_encoding::FORM_URLENCODED_ENCODE_SET );
let is_path_shared = write_file_data.isPathShared;
let offset = write_file_data.offset ; // seems to be unsupported
//println!("dirPath = {}",&dir_path);
// URL to send our 'ls' request to
let url_nfs = "http://localhost:8100/nfs/file".to_string();
let url_nfs_write = url_nfs + "/" + &file_path + "/" + &is_path_shared.to_string() + "?offset:=" + &offset.to_string() ;
//println!("url_nfs_ls = {}",&url_nfs_write);
let mut headers: HashMap<String, String> = HashMap::new();
headers.insert("Authorization".to_string(), bearertoken );
headers.insert("Content-Type".to_string(), "application/json".to_string());
headers.insert("Connection".to_string(), "close".to_string());
//println!("sending request");
//Send a request to launcher using "request" library
let res = ::request::put(&url_nfs_write, &mut headers, &write_file_json_encrypted_b64.into_bytes() );
//println!("request sent");
//Error handling
match res {
Err(e) => { println!("{}", e); return Err(ConnectionError::UnableToConnect) }, // couldn't connect
Ok(res) =>
{
// Handle the response recieved from the launcher
if res.status_code == 401 {
println!("401 Unauthorized"); return Err(ConnectionError::Unauthorized)
} else if res.status_code == 400 {
println!("400 Bad Request"); return Err(ConnectionError::BadRequest)
} else if res.status_code == 404 {
println!("404 Not Found"); return Err(ConnectionError::NotFound)
} else if res.status_code == 500 {
println!("500 Internal Server Error"); return Err(ConnectionError::InternalServerError)
} else if res.status_code == 200 {
println!("200 Ok"); { return Ok(res.status_code) }
} else { return Err(ConnectionError::UnknownError) }
}
};
}
// read a file
pub fn read_file ( read_file_data : ReadFileData , safe_register_resp : &super::auth::SafeRegisterResp ) -> Result< FileReadInfo , ConnectionError > {
println!("App: Begin reading file...");
/*
*
*
* TODO PANIC on inexistant file
*
*
*/
let bearertoken = "Bearer ".to_string()+&safe_register_resp.token ;
// path Parameters
let requested_file = read_file_data.filePath ;
let file_path = ::url::percent_encoding::utf8_percent_encode ( &requested_file, ::url::percent_encoding::FORM_URLENCODED_ENCODE_SET );
let is_path_shared = read_file_data.isPathShared;
let offset = read_file_data.offset ; // seems to be unsupported
let length = read_file_data.length ; // seems to be unsupported
// URL to send our 'ls' request to
// http://localhost:8100/0.4/nfs/file/:filePath/:isPathShared?offset=:offset&length=:length
let url_nfs = "http://localhost:8100/nfs/file".to_string();
let url_nfs1 = url_nfs + "/" + &file_path + "/" + &is_path_shared.to_string() ;
let mut url_nfs_read = url_nfs1.clone() ;
// append length and offset if needed
if length > 0 && offset > 0 {
url_nfs_read = url_nfs1 + "?offset=:" + &&offset.to_string() + "&length=:" + &&length.to_string() ; }
else if length == 0 && offset > 0 {
url_nfs_read = url_nfs1 + "?offset=:" + &&offset.to_string(); }
else if length > 0 && offset == 0 {
url_nfs_read = url_nfs1 + "?length=:" + &&length.to_string() ; };
println!("url_nfs_read = {}",&url_nfs_read);
let mut headers: HashMap<String, String> = HashMap::new();
headers.insert("Authorization".to_string(), bearertoken );
headers.insert("Content-Type".to_string(), "application/json".to_string());
headers.insert("Connection".to_string(), "close".to_string());
//println!("sending request");
//Send a request to launcher using "request" library
let res = ::request::get( &url_nfs_read, &mut headers );
//println!("request sent");
//Error handling
match res {
Err(e) => { println!("{}", e); return Err(ConnectionError::UnableToConnect) }, // couldn't connect
Ok(res) =>
{
// Handle the response recieved from the launcher
if res.status_code == 401 {
println!("401 Unauthorized"); return Err(ConnectionError::Unauthorized)
} else if res.status_code == 400 {
println!("400 Bad Request"); return Err(ConnectionError::BadRequest)
} else if res.status_code == 500 {
println!("500 Internal Server Error"); return Err(ConnectionError::InternalServerError)
} else if res.status_code == 200 {
println!("200 Ok"); {
let resp_read_file_enc_b64 = res.body;
//println!( "enc_b64 = {}", &resp_ls_dir_enc_b64 );
let resp_read_file_enc = resp_read_file_enc_b64.from_base64().ok().unwrap();
//println!( "enc = {:?}" , &resp_ls_dfile_enc );
// Decrypt the raw bytes using the Secret Key (Nonce and Symmetric Key).
let decrypted_response = ::sodiumoxide::crypto::secretbox::open(&resp_read_file_enc,
&safe_register_resp.symm_nonce,
&safe_register_resp.symm_key).ok().unwrap();
//println!( "decr = {:?}" , &decrypted_response );
// Get it into a valid UTF-8 String - this will be the JSON response.
let decrypted_response_json_str = String::from_utf8(decrypted_response).ok().unwrap();
//println!("App: GetFile Response JSON: {:?}", decrypted_response_json_str);
// Decode the JSON into expected response structure
/*
*
* TODO
*
* panics on empty file ---- EOF
*
*/
let read_file_resp_body = ::rustc_serialize::json::decode(&decrypted_response_json_str)
.unwrap_or_else(|e| panic!("{:?}", e));
//println!("App: GetFile Response decoded.");
//get headers
let headers = res.headers;
//println!( "get file headers = {:?}", headers);
let mut file_size = "";
let mut file_name = "";
let mut file_created_time = "";
let mut file_modified_time = "";
let mut file_metadata = "";
match headers.get("file-size") {
Some ( val ) => { file_size = val; },
_ => { file_size = "0"; }
}
match headers.get("file-name") {
Some ( val ) => { file_name = val; },
_ => { file_name = "None"; }
}
match headers.get("file-created-time") {
Some ( val ) => { file_created_time = val; },
_ => { file_created_time = "0"; }
}
match headers.get("file-modified-time") {
Some ( val ) => { file_modified_time = val; },
_ => { file_modified_time = "0"; }
}
match headers.get("file-metadata") {
Some ( val ) => { file_metadata = val; },
_ => { file_metadata = "None"; }
}
let file_info = FileReadInfo {
filename: file_name.to_string(),
filesize: file_size.parse().ok().expect("Wanted a number"),
filecreatedtime: file_created_time.parse().ok().expect("Wanted a number"),
filemodifiedtime: file_modified_time.parse().ok().expect("Wanted a number"),
filemetadata: file_metadata.to_string(),
filebody: read_file_resp_body,
};
return Ok( file_info ); }
} else { return Err(ConnectionError::UnknownError) } // if end
}
};//match end
} //fn end
// delete a file
pub fn delete_file ( delete_file_data : DeleteFileData, safe_register_resp : &super::auth::SafeRegisterResp ) -> Result< u16 , ConnectionError > {
println!("App: Begin deleting file...");
let bearertoken = "Bearer ".to_string()+&safe_register_resp.token ;
// path Parameters
let requested_file = delete_file_data.filePath ;
let file_path = ::url::percent_encoding::utf8_percent_encode ( &requested_file, ::url::percent_encoding::FORM_URLENCODED_ENCODE_SET );
let is_path_shared = delete_file_data.isPathShared;
//println!("filePath = {}",&file_path);
// URL to send our 'ls' request to
let url_nfs = "http://localhost:8100/nfs/file".to_string();
let url_nfs_del = url_nfs + "/" + &file_path + "/" + &is_path_shared.to_string();
//println!("url_nfs_ls = {}",&url_nfs_del);
let mut headers: HashMap<String, String> = HashMap::new();
headers.insert("Authorization".to_string(), bearertoken );
headers.insert("Connection".to_string(), "close".to_string());
//println!("sending request");
//Send a request to launcher using "request" library
let res = ::request::delete(&url_nfs_del, &mut headers );
//println!("request sent");
//Error handling
match res {
Err(e) => { println!("{}", e); return Err(ConnectionError::UnableToConnect) }, // couldn't connect
Ok(res) =>
{
// Handle the response recieved from the launcher
if res.status_code == 401 {
println!("401 Unauthorized"); return Err(ConnectionError::Unauthorized)
} else if res.status_code == 400 {
println!("400 Bad Request"); return Err(ConnectionError::BadRequest)
} else if res.status_code == 404 {
println!("404 Not Found"); return Err(ConnectionError::NotFound)
} else if res.status_code == 500 {
println!("500 Internal Server Error"); return Err(ConnectionError::InternalServerError)
} else if res.status_code == 200 {
println!("200 Ok"); { return Ok(res.status_code) }
} else { return Err(ConnectionError::UnknownError) }
}
};
}
| true |
14263e5a7e1d7f8756647f9b48be1277b0ff2b6e
|
Rust
|
matthewrsj/hello
|
/hello-world-cl.rs
|
UTF-8
| 169 | 2.71875 | 3 |
[
"Apache-2.0"
] |
permissive
|
fn main() {
// Print text to the console
println!("Hello World!");
println!("Hola mundo!");
println!("Bonjour le monde!");
println!("Hallo verden!");
}
| true |
628e42f5006703ff56780e5f8f52e2fca226f35a
|
Rust
|
Noah-Kennedy/rtfm-prototype
|
/src/main.rs
|
UTF-8
| 3,670 | 2.515625 | 3 |
[] |
no_license
|
#![no_main]
#![no_std]
// On dev builds, go to debugger on panic
#[cfg(debug_assertions)]
extern crate panic_semihosting;
// On release builds, halt on panic
#[cfg(not(debug_assertions))]
extern crate panic_halt;
use cortex_m::peripheral::DWT;
use f3::hal::gpio::GpioExt;
use f3::hal::rcc::RccExt;
use f3::hal::stm32f30x;
use f3::led::Leds;
use rtfm::cyccnt::{Instant, U32Ext, CYCCNT};
use rtfm::Monotonic;
// const LED_PERIOD: u32 = 2_000_000;
// const LED_ON_TIME: u32 = 1_000_000;
const LED_PERIOD_MILLIS: u32 = 1_000;
const LED_ON_TIME_MILLIS: u32 = 100;
const CYC_PER_MILLI: u32 = 36_00;
const LED_PERIOD_CYC: u32 = LED_PERIOD_MILLIS * CYC_PER_MILLI;
const LED_ON_TIME_CYC: u32 = LED_ON_TIME_MILLIS * CYC_PER_MILLI;
#[rtfm::app(device = stm32f30x, monotonic = rtfm::cyccnt::CYCCNT)]
const APP: () = {
struct Resources {
leds: Leds,
}
/// Initialization section
///
/// Initializes our tasks and peripherals.
#[init(schedule = [blink_led, turn_off_led])]
fn init(mut cx: init::Context) -> init::LateResources {
// Initialize (enable) the monotonic timer (CYCCNT)
cx.core.DCB.enable_trace();
// required on Cortex-M7 devices that software lock the DWT (e.g. STM32F7)
DWT::unlock();
cx.core.DWT.enable_cycle_counter();
// grab current time
let now = Instant::now();
// schedule turn on led to happen immediately after init
cx.schedule.blink_led(now).unwrap();
// schedule led turn off to occur after our duty period
cx.schedule.turn_off_led(now + LED_ON_TIME_CYC.cycles()).unwrap();
// get peripherals
let board_peripherals = stm32f30x::Peripherals::take().unwrap();
// acquire the RCC
let mut rcc = board_peripherals.RCC.constrain();
// acquire GPIOE, which operates the LEDs on this board
let led_gpio = board_peripherals.GPIOE.split(&mut rcc.ahb);
// create an LEDs object from the GPIO
let leds = f3::led::Leds::new(led_gpio);
// return resources
init::LateResources {
leds
}
}
/// Turns the LED on.
///
/// This task reschedules itself, and then turns on the LEDs.
#[task(schedule = [blink_led], resources = [leds])]
fn blink_led(cx: blink_led::Context) {
// reschedule this task
// this is done with the scheduled time rather than current clock time, preventing drift.
cx.schedule.blink_led(cx.scheduled + LED_PERIOD_CYC.cycles()).unwrap();
// grab leds
let leds: &mut Leds = cx.resources.leds;
// turn on leds
set_leds(leds, true);
}
/// Turns the LED off.
///
/// This task reschedules itself, and then turns off the LEDs.
#[task(schedule = [turn_off_led], resources = [leds])]
fn turn_off_led(cx: turn_off_led::Context) {
// reschedule this task
// this is done with the scheduled time rather than current clock time, preventing drift.
cx.schedule.turn_off_led(cx.scheduled + LED_PERIOD_CYC.cycles()).unwrap();
// grab leds
let leds: &mut Leds = cx.resources.leds;
// turn off leds
set_leds(leds, false);
}
/// Declare free interrupts
/// These are used to dispatch software-spawned tasks
/// These are interrupts not used by hardware.
extern "C" {
fn CAN_RX1();
fn CAN_RX2();
}
};
fn set_leds(leds: &mut Leds, val: bool) {
for led in leds.iter_mut() {
set_led(led, val)
}
}
fn set_led(led: &mut f3::led::Led, val: bool) {
if val {
led.on();
} else {
led.off()
}
}
| true |
e1cbad40863d73f3724c50ca0f321583143d3df8
|
Rust
|
wasmerio/wasmer
|
/lib/types/src/module.rs
|
UTF-8
| 23,996 | 2.703125 | 3 |
[
"MIT"
] |
permissive
|
// This file contains code from external sources.
// Attributions: https://github.com/wasmerio/wasmer/blob/master/ATTRIBUTIONS.md
//! Data structure for representing WebAssembly modules in a
//! `wasmer::Module`.
use crate::entity::{EntityRef, PrimaryMap};
use crate::{
CustomSectionIndex, DataIndex, ElemIndex, ExportIndex, ExportType, ExternType, FunctionIndex,
FunctionType, GlobalIndex, GlobalInit, GlobalType, ImportIndex, ImportType, LocalFunctionIndex,
LocalGlobalIndex, LocalMemoryIndex, LocalTableIndex, MemoryIndex, MemoryType, SignatureIndex,
TableIndex, TableInitializer, TableType,
};
use indexmap::IndexMap;
use rkyv::{
de::SharedDeserializeRegistry, ser::ScratchSpace, ser::Serializer,
ser::SharedSerializeRegistry, Archive, Archived, CheckBytes, Deserialize as RkyvDeserialize,
Fallible, Serialize as RkyvSerialize,
};
#[cfg(feature = "enable-serde")]
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::collections::HashMap;
use std::fmt;
use std::iter::ExactSizeIterator;
use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
#[derive(Debug, Clone, RkyvSerialize, RkyvDeserialize, Archive)]
#[archive_attr(derive(CheckBytes))]
pub struct ModuleId {
id: usize,
}
impl ModuleId {
pub fn id(&self) -> String {
format!("{}", &self.id)
}
}
impl Default for ModuleId {
fn default() -> Self {
static NEXT_ID: AtomicUsize = AtomicUsize::new(0);
Self {
id: NEXT_ID.fetch_add(1, SeqCst),
}
}
}
/// Hash key of an import
#[derive(Debug, Hash, Eq, PartialEq, Clone, Default, RkyvSerialize, RkyvDeserialize, Archive)]
#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
#[archive_attr(derive(CheckBytes, PartialEq, Eq, Hash))]
pub struct ImportKey {
/// Module name
pub module: String,
/// Field name
pub field: String,
/// Import index
pub import_idx: u32,
}
impl From<(String, String, u32)> for ImportKey {
fn from((module, field, import_idx): (String, String, u32)) -> Self {
Self {
module,
field,
import_idx,
}
}
}
#[cfg(feature = "enable-serde")]
mod serde_imports {
use crate::ImportIndex;
use crate::ImportKey;
use indexmap::IndexMap;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
type InitialType = IndexMap<ImportKey, ImportIndex>;
type SerializedType = Vec<(ImportKey, ImportIndex)>;
// IndexMap<ImportKey, ImportIndex>
// Vec<
pub fn serialize<S: Serializer>(s: &InitialType, serializer: S) -> Result<S::Ok, S::Error> {
let vec: SerializedType = s
.iter()
.map(|(a, b)| (a.clone(), b.clone()))
.collect::<Vec<_>>();
vec.serialize(serializer)
}
pub fn deserialize<'de, D: Deserializer<'de>>(
deserializer: D,
) -> Result<InitialType, D::Error> {
let serialized = <SerializedType as Deserialize>::deserialize(deserializer)?;
Ok(serialized.into_iter().collect())
}
}
/// A translated WebAssembly module, excluding the function bodies and
/// memory initializers.
#[derive(Debug, Clone, Default)]
#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
pub struct ModuleInfo {
/// A unique identifier (within this process) for this module.
///
/// We skip serialization/deserialization of this field, as it
/// should be computed by the process.
/// It's not skipped in rkyv, but that is okay, because even though it's skipped in bincode/serde
/// it's still deserialized back as a garbage number, and later override from computed by the process
#[cfg_attr(feature = "enable-serde", serde(skip_serializing, skip_deserializing))]
pub id: ModuleId,
/// The name of this wasm module, often found in the wasm file.
pub name: Option<String>,
/// Imported entities with the (module, field, index_of_the_import)
///
/// Keeping the `index_of_the_import` is important, as there can be
/// two same references to the same import, and we don't want to confuse
/// them.
#[cfg_attr(feature = "enable-serde", serde(with = "serde_imports"))]
pub imports: IndexMap<ImportKey, ImportIndex>,
/// Exported entities.
pub exports: IndexMap<String, ExportIndex>,
/// The module "start" function, if present.
pub start_function: Option<FunctionIndex>,
/// WebAssembly table initializers.
pub table_initializers: Vec<TableInitializer>,
/// WebAssembly passive elements.
pub passive_elements: HashMap<ElemIndex, Box<[FunctionIndex]>>,
/// WebAssembly passive data segments.
pub passive_data: HashMap<DataIndex, Box<[u8]>>,
/// WebAssembly global initializers.
pub global_initializers: PrimaryMap<LocalGlobalIndex, GlobalInit>,
/// WebAssembly function names.
pub function_names: HashMap<FunctionIndex, String>,
/// WebAssembly function signatures.
pub signatures: PrimaryMap<SignatureIndex, FunctionType>,
/// WebAssembly functions (imported and local).
pub functions: PrimaryMap<FunctionIndex, SignatureIndex>,
/// WebAssembly tables (imported and local).
pub tables: PrimaryMap<TableIndex, TableType>,
/// WebAssembly linear memories (imported and local).
pub memories: PrimaryMap<MemoryIndex, MemoryType>,
/// WebAssembly global variables (imported and local).
pub globals: PrimaryMap<GlobalIndex, GlobalType>,
/// Custom sections in the module.
pub custom_sections: IndexMap<String, CustomSectionIndex>,
/// The data for each CustomSection in the module.
pub custom_sections_data: PrimaryMap<CustomSectionIndex, Box<[u8]>>,
/// Number of imported functions in the module.
pub num_imported_functions: usize,
/// Number of imported tables in the module.
pub num_imported_tables: usize,
/// Number of imported memories in the module.
pub num_imported_memories: usize,
/// Number of imported globals in the module.
pub num_imported_globals: usize,
}
/// Mirror version of ModuleInfo that can derive rkyv traits
#[derive(RkyvSerialize, RkyvDeserialize, Archive)]
#[archive_attr(derive(CheckBytes))]
pub struct ArchivableModuleInfo {
name: Option<String>,
imports: IndexMap<ImportKey, ImportIndex>,
exports: IndexMap<String, ExportIndex>,
start_function: Option<FunctionIndex>,
table_initializers: Vec<TableInitializer>,
passive_elements: BTreeMap<ElemIndex, Box<[FunctionIndex]>>,
passive_data: BTreeMap<DataIndex, Box<[u8]>>,
global_initializers: PrimaryMap<LocalGlobalIndex, GlobalInit>,
function_names: BTreeMap<FunctionIndex, String>,
signatures: PrimaryMap<SignatureIndex, FunctionType>,
functions: PrimaryMap<FunctionIndex, SignatureIndex>,
tables: PrimaryMap<TableIndex, TableType>,
memories: PrimaryMap<MemoryIndex, MemoryType>,
globals: PrimaryMap<GlobalIndex, GlobalType>,
custom_sections: IndexMap<String, CustomSectionIndex>,
custom_sections_data: PrimaryMap<CustomSectionIndex, Box<[u8]>>,
num_imported_functions: usize,
num_imported_tables: usize,
num_imported_memories: usize,
num_imported_globals: usize,
}
impl From<ModuleInfo> for ArchivableModuleInfo {
fn from(it: ModuleInfo) -> Self {
Self {
name: it.name,
imports: it.imports,
exports: it.exports,
start_function: it.start_function,
table_initializers: it.table_initializers,
passive_elements: it.passive_elements.into_iter().collect(),
passive_data: it.passive_data.into_iter().collect(),
global_initializers: it.global_initializers,
function_names: it.function_names.into_iter().collect(),
signatures: it.signatures,
functions: it.functions,
tables: it.tables,
memories: it.memories,
globals: it.globals,
custom_sections: it.custom_sections,
custom_sections_data: it.custom_sections_data,
num_imported_functions: it.num_imported_functions,
num_imported_tables: it.num_imported_tables,
num_imported_memories: it.num_imported_memories,
num_imported_globals: it.num_imported_globals,
}
}
}
impl From<ArchivableModuleInfo> for ModuleInfo {
fn from(it: ArchivableModuleInfo) -> Self {
Self {
id: Default::default(),
name: it.name,
imports: it.imports,
exports: it.exports,
start_function: it.start_function,
table_initializers: it.table_initializers,
passive_elements: it.passive_elements.into_iter().collect(),
passive_data: it.passive_data.into_iter().collect(),
global_initializers: it.global_initializers,
function_names: it.function_names.into_iter().collect(),
signatures: it.signatures,
functions: it.functions,
tables: it.tables,
memories: it.memories,
globals: it.globals,
custom_sections: it.custom_sections,
custom_sections_data: it.custom_sections_data,
num_imported_functions: it.num_imported_functions,
num_imported_tables: it.num_imported_tables,
num_imported_memories: it.num_imported_memories,
num_imported_globals: it.num_imported_globals,
}
}
}
impl From<&ModuleInfo> for ArchivableModuleInfo {
fn from(it: &ModuleInfo) -> Self {
Self::from(it.clone())
}
}
impl Archive for ModuleInfo {
type Archived = <ArchivableModuleInfo as Archive>::Archived;
type Resolver = <ArchivableModuleInfo as Archive>::Resolver;
unsafe fn resolve(&self, pos: usize, resolver: Self::Resolver, out: *mut Self::Archived) {
ArchivableModuleInfo::from(self).resolve(pos, resolver, out)
}
}
impl<S: Serializer + SharedSerializeRegistry + ScratchSpace + ?Sized> RkyvSerialize<S>
for ModuleInfo
{
fn serialize(&self, serializer: &mut S) -> Result<Self::Resolver, S::Error> {
ArchivableModuleInfo::from(self).serialize(serializer)
}
}
impl<D: Fallible + ?Sized + SharedDeserializeRegistry> RkyvDeserialize<ModuleInfo, D>
for Archived<ModuleInfo>
{
fn deserialize(&self, deserializer: &mut D) -> Result<ModuleInfo, D::Error> {
let r: ArchivableModuleInfo =
RkyvDeserialize::<ArchivableModuleInfo, D>::deserialize(self, deserializer)?;
Ok(ModuleInfo::from(r))
}
}
// For test serialization correctness, everything except module id should be same
impl PartialEq for ModuleInfo {
fn eq(&self, other: &Self) -> bool {
self.name == other.name
&& self.imports == other.imports
&& self.exports == other.exports
&& self.start_function == other.start_function
&& self.table_initializers == other.table_initializers
&& self.passive_elements == other.passive_elements
&& self.passive_data == other.passive_data
&& self.global_initializers == other.global_initializers
&& self.function_names == other.function_names
&& self.signatures == other.signatures
&& self.functions == other.functions
&& self.tables == other.tables
&& self.memories == other.memories
&& self.globals == other.globals
&& self.custom_sections == other.custom_sections
&& self.custom_sections_data == other.custom_sections_data
&& self.num_imported_functions == other.num_imported_functions
&& self.num_imported_tables == other.num_imported_tables
&& self.num_imported_memories == other.num_imported_memories
&& self.num_imported_globals == other.num_imported_globals
}
}
impl Eq for ModuleInfo {}
impl ModuleInfo {
/// Allocates the module data structures.
pub fn new() -> Self {
Default::default()
}
/// Get the given passive element, if it exists.
pub fn get_passive_element(&self, index: ElemIndex) -> Option<&[FunctionIndex]> {
self.passive_elements.get(&index).map(|es| &**es)
}
/// Get the exported signatures of the module
pub fn exported_signatures(&self) -> Vec<FunctionType> {
self.exports
.iter()
.filter_map(|(_name, export_index)| match export_index {
ExportIndex::Function(i) => {
let signature = self.functions.get(*i).unwrap();
let func_type = self.signatures.get(*signature).unwrap();
Some(func_type.clone())
}
_ => None,
})
.collect::<Vec<FunctionType>>()
}
/// Get the export types of the module
pub fn exports(&'_ self) -> ExportsIterator<impl Iterator<Item = ExportType> + '_> {
let iter = self.exports.iter().map(move |(name, export_index)| {
let extern_type = match export_index {
ExportIndex::Function(i) => {
let signature = self.functions.get(*i).unwrap();
let func_type = self.signatures.get(*signature).unwrap();
ExternType::Function(func_type.clone())
}
ExportIndex::Table(i) => {
let table_type = self.tables.get(*i).unwrap();
ExternType::Table(*table_type)
}
ExportIndex::Memory(i) => {
let memory_type = self.memories.get(*i).unwrap();
ExternType::Memory(*memory_type)
}
ExportIndex::Global(i) => {
let global_type = self.globals.get(*i).unwrap();
ExternType::Global(*global_type)
}
};
ExportType::new(name, extern_type)
});
ExportsIterator::new(iter, self.exports.len())
}
/// Get the import types of the module
pub fn imports(&'_ self) -> ImportsIterator<impl Iterator<Item = ImportType> + '_> {
let iter =
self.imports
.iter()
.map(move |(ImportKey { module, field, .. }, import_index)| {
let extern_type = match import_index {
ImportIndex::Function(i) => {
let signature = self.functions.get(*i).unwrap();
let func_type = self.signatures.get(*signature).unwrap();
ExternType::Function(func_type.clone())
}
ImportIndex::Table(i) => {
let table_type = self.tables.get(*i).unwrap();
ExternType::Table(*table_type)
}
ImportIndex::Memory(i) => {
let memory_type = self.memories.get(*i).unwrap();
ExternType::Memory(*memory_type)
}
ImportIndex::Global(i) => {
let global_type = self.globals.get(*i).unwrap();
ExternType::Global(*global_type)
}
};
ImportType::new(module, field, extern_type)
});
ImportsIterator::new(iter, self.imports.len())
}
/// Get the custom sections of the module given a `name`.
pub fn custom_sections<'a>(&'a self, name: &'a str) -> impl Iterator<Item = Box<[u8]>> + 'a {
self.custom_sections
.iter()
.filter_map(move |(section_name, section_index)| {
if name != section_name {
return None;
}
Some(self.custom_sections_data[*section_index].clone())
})
}
/// Convert a `LocalFunctionIndex` into a `FunctionIndex`.
pub fn func_index(&self, local_func: LocalFunctionIndex) -> FunctionIndex {
FunctionIndex::new(self.num_imported_functions + local_func.index())
}
/// Convert a `FunctionIndex` into a `LocalFunctionIndex`. Returns None if the
/// index is an imported function.
pub fn local_func_index(&self, func: FunctionIndex) -> Option<LocalFunctionIndex> {
func.index()
.checked_sub(self.num_imported_functions)
.map(LocalFunctionIndex::new)
}
/// Test whether the given function index is for an imported function.
pub fn is_imported_function(&self, index: FunctionIndex) -> bool {
index.index() < self.num_imported_functions
}
/// Convert a `LocalTableIndex` into a `TableIndex`.
pub fn table_index(&self, local_table: LocalTableIndex) -> TableIndex {
TableIndex::new(self.num_imported_tables + local_table.index())
}
/// Convert a `TableIndex` into a `LocalTableIndex`. Returns None if the
/// index is an imported table.
pub fn local_table_index(&self, table: TableIndex) -> Option<LocalTableIndex> {
table
.index()
.checked_sub(self.num_imported_tables)
.map(LocalTableIndex::new)
}
/// Test whether the given table index is for an imported table.
pub fn is_imported_table(&self, index: TableIndex) -> bool {
index.index() < self.num_imported_tables
}
/// Convert a `LocalMemoryIndex` into a `MemoryIndex`.
pub fn memory_index(&self, local_memory: LocalMemoryIndex) -> MemoryIndex {
MemoryIndex::new(self.num_imported_memories + local_memory.index())
}
/// Convert a `MemoryIndex` into a `LocalMemoryIndex`. Returns None if the
/// index is an imported memory.
pub fn local_memory_index(&self, memory: MemoryIndex) -> Option<LocalMemoryIndex> {
memory
.index()
.checked_sub(self.num_imported_memories)
.map(LocalMemoryIndex::new)
}
/// Test whether the given memory index is for an imported memory.
pub fn is_imported_memory(&self, index: MemoryIndex) -> bool {
index.index() < self.num_imported_memories
}
/// Convert a `LocalGlobalIndex` into a `GlobalIndex`.
pub fn global_index(&self, local_global: LocalGlobalIndex) -> GlobalIndex {
GlobalIndex::new(self.num_imported_globals + local_global.index())
}
/// Convert a `GlobalIndex` into a `LocalGlobalIndex`. Returns None if the
/// index is an imported global.
pub fn local_global_index(&self, global: GlobalIndex) -> Option<LocalGlobalIndex> {
global
.index()
.checked_sub(self.num_imported_globals)
.map(LocalGlobalIndex::new)
}
/// Test whether the given global index is for an imported global.
pub fn is_imported_global(&self, index: GlobalIndex) -> bool {
index.index() < self.num_imported_globals
}
/// Get the Module name
pub fn name(&self) -> String {
match self.name {
Some(ref name) => name.to_string(),
None => "<module>".to_string(),
}
}
/// Get the imported function types of the module.
pub fn imported_function_types(&'_ self) -> impl Iterator<Item = FunctionType> + '_ {
self.functions
.values()
.take(self.num_imported_functions)
.map(move |sig_index| self.signatures[*sig_index].clone())
}
}
impl fmt::Display for ModuleInfo {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.name())
}
}
// Code inspired from
// https://www.reddit.com/r/rust/comments/9vspv4/extending_iterators_ergonomically/
/// This iterator allows us to iterate over the exports
/// and offer nice API ergonomics over it.
pub struct ExportsIterator<I: Iterator<Item = ExportType> + Sized> {
iter: I,
size: usize,
}
impl<I: Iterator<Item = ExportType> + Sized> ExportsIterator<I> {
/// Create a new `ExportsIterator` for a given iterator and size
pub fn new(iter: I, size: usize) -> Self {
Self { iter, size }
}
}
impl<I: Iterator<Item = ExportType> + Sized> ExactSizeIterator for ExportsIterator<I> {
// We can easily calculate the remaining number of iterations.
fn len(&self) -> usize {
self.size
}
}
impl<I: Iterator<Item = ExportType> + Sized> ExportsIterator<I> {
/// Get only the functions
pub fn functions(self) -> impl Iterator<Item = ExportType<FunctionType>> + Sized {
self.iter.filter_map(|extern_| match extern_.ty() {
ExternType::Function(ty) => Some(ExportType::new(extern_.name(), ty.clone())),
_ => None,
})
}
/// Get only the memories
pub fn memories(self) -> impl Iterator<Item = ExportType<MemoryType>> + Sized {
self.iter.filter_map(|extern_| match extern_.ty() {
ExternType::Memory(ty) => Some(ExportType::new(extern_.name(), *ty)),
_ => None,
})
}
/// Get only the tables
pub fn tables(self) -> impl Iterator<Item = ExportType<TableType>> + Sized {
self.iter.filter_map(|extern_| match extern_.ty() {
ExternType::Table(ty) => Some(ExportType::new(extern_.name(), *ty)),
_ => None,
})
}
/// Get only the globals
pub fn globals(self) -> impl Iterator<Item = ExportType<GlobalType>> + Sized {
self.iter.filter_map(|extern_| match extern_.ty() {
ExternType::Global(ty) => Some(ExportType::new(extern_.name(), *ty)),
_ => None,
})
}
}
impl<I: Iterator<Item = ExportType> + Sized> Iterator for ExportsIterator<I> {
type Item = ExportType;
fn next(&mut self) -> Option<Self::Item> {
self.iter.next()
}
}
/// This iterator allows us to iterate over the imports
/// and offer nice API ergonomics over it.
pub struct ImportsIterator<I: Iterator<Item = ImportType> + Sized> {
iter: I,
size: usize,
}
impl<I: Iterator<Item = ImportType> + Sized> ImportsIterator<I> {
/// Create a new `ImportsIterator` for a given iterator and size
pub fn new(iter: I, size: usize) -> Self {
Self { iter, size }
}
}
impl<I: Iterator<Item = ImportType> + Sized> ExactSizeIterator for ImportsIterator<I> {
// We can easily calculate the remaining number of iterations.
fn len(&self) -> usize {
self.size
}
}
impl<I: Iterator<Item = ImportType> + Sized> ImportsIterator<I> {
/// Get only the functions
pub fn functions(self) -> impl Iterator<Item = ImportType<FunctionType>> + Sized {
self.iter.filter_map(|extern_| match extern_.ty() {
ExternType::Function(ty) => Some(ImportType::new(
extern_.module(),
extern_.name(),
ty.clone(),
)),
_ => None,
})
}
/// Get only the memories
pub fn memories(self) -> impl Iterator<Item = ImportType<MemoryType>> + Sized {
self.iter.filter_map(|extern_| match extern_.ty() {
ExternType::Memory(ty) => Some(ImportType::new(extern_.module(), extern_.name(), *ty)),
_ => None,
})
}
/// Get only the tables
pub fn tables(self) -> impl Iterator<Item = ImportType<TableType>> + Sized {
self.iter.filter_map(|extern_| match extern_.ty() {
ExternType::Table(ty) => Some(ImportType::new(extern_.module(), extern_.name(), *ty)),
_ => None,
})
}
/// Get only the globals
pub fn globals(self) -> impl Iterator<Item = ImportType<GlobalType>> + Sized {
self.iter.filter_map(|extern_| match extern_.ty() {
ExternType::Global(ty) => Some(ImportType::new(extern_.module(), extern_.name(), *ty)),
_ => None,
})
}
}
impl<I: Iterator<Item = ImportType> + Sized> Iterator for ImportsIterator<I> {
type Item = ImportType;
fn next(&mut self) -> Option<Self::Item> {
self.iter.next()
}
}
| true |
2081392ef27ec05395cd9e2cd28c9b7cb55bdd3e
|
Rust
|
Abhinickz/learn_rust
|
/temperature/src/main.rs
|
UTF-8
| 2,578 | 3.78125 | 4 |
[] |
no_license
|
use std::io;
fn main() {
// Take input to choose correct option using this loop.
loop {
println!("Enter \"1\" to Convert °F => °C");
println!("Enter \"2\" to Convert °C => °F");
let mut option = String::new();
io::stdin()
.read_line(&mut option)
.expect("Failed to read line");
let option: i8 = match option.trim().parse() {
Ok(num) => num,
Err(_) => {
println!("You entered a Non-Number: {}", option);
continue;
}
};
// Match the option and call corresopnding code.
match option {
1 | 2 => {
match option {
1 => {
f_to_c(1);
}
2 => {
c_to_f(2);
}
_ => {}
}
// all things done, now exit the loop.
break;
}
_ => {
// In case of other option than 1 or 2 continue with the option input loop.
continue;
}
}
}
}
fn f_to_c(opt: i8) {
let temp_f: f32 = input_temperature(opt);
println!("temp in °F: {}", temp_f);
println!("temp in °C: {}", (temp_f - 32.0) * 0.5556);
}
fn c_to_f(opt: i8) {
let temp_c: f32 = input_temperature(opt);
println!("temp in °C: {}", temp_c);
println!("temp in °F: {}", (temp_c * 9.0 / 5.0) + 32.0);
}
fn input_temperature(opt: i8) -> f32 {
// Dynamically generate string based on option.
let str = match opt {
1 => "°F",
2 => "°C",
_ => "", // Default case needed.
};
let mut temp = String::new();
println!("Enter temperature in {}:", str);
io::stdin()
.read_line(&mut temp)
.expect("Failed to read line");
let temp: f32 = match temp.trim().parse() {
Ok(num) => num,
Err(_) => {
println!("You entered a Non-floating number: {}", temp);
input_temperature(opt) // Recursive call in case of input error for temperature.
}
};
// Instead of using return keyword, temp could be written to return.
return temp; // temp
}
/*
Output:
[01:45:25 abhasker@wsl -> temperature$ cargo run
Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs
Running `target/debug/temperature`
Enter "1" to Convert °F => °C
Enter "2" to Convert °C => °F
2
Enter temperature in °C:
37.0
temp in °C: 37
temp in °C: 98.6
*/
| true |
8fcf3892cc105af0cd1a79135600fb0f1782011c
|
Rust
|
ashtuchkin/rypt
|
/tests/util.rs
|
UTF-8
| 3,721 | 2.828125 | 3 |
[
"MIT"
] |
permissive
|
#![allow(dead_code)]
use failure::{bail, Fallible};
use rand::distributions::Distribution;
use rand::{Rng, RngCore};
pub use rypt::util::to_hex_string;
use std::fs::File;
use std::io::{Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
use std::process::Command;
use std::{env, fs};
pub fn random_str(mut rng: &mut dyn rand::RngCore, len: usize) -> String {
rand::distributions::Alphanumeric
.sample_iter(&mut rng)
.take(len)
.collect()
}
pub fn random_bytes(rng: &mut dyn rand::RngCore, len: usize) -> Vec<u8> {
let mut bytes = vec![0u8; len];
rng.fill(bytes.as_mut_slice());
bytes
}
pub fn temp_filename(rng: &mut dyn RngCore, extension: &str) -> PathBuf {
env::temp_dir()
.join(random_str(rng, 10))
.with_extension(extension)
}
pub fn create_temp_file(rng: &mut dyn RngCore, extension: &str) -> Fallible<(PathBuf, Vec<u8>)> {
let temp_file = temp_filename(rng, extension);
let contents = random_bytes(rng, 10_000_000);
fs::write(&temp_file, &contents)?;
Ok((temp_file, contents))
}
pub fn create_temp_file_secret(rng: &mut dyn RngCore) -> Fallible<PathBuf> {
let temp_file = temp_filename(rng, ".secret");
let contents = to_hex_string(random_bytes(rng, 32));
fs::write(&temp_file, &contents)?;
Ok(temp_file)
}
pub fn main_binary_path() -> Fallible<PathBuf> {
// Assume current function is called from an integration test, which itself is compiled to a
// binary in the 'deps' subfolder of the folder that contains the main binary.
let mut path = std::env::current_exe()?;
path.pop();
if path.ends_with("deps") {
path.pop();
}
let binary_path = path.join(format!(
"{}{}",
env!("CARGO_PKG_NAME"),
std::env::consts::EXE_SUFFIX
));
if !binary_path.is_file() {
bail!("Main binary not found: {}", binary_path.to_string_lossy());
}
Ok(binary_path)
}
pub fn main_cmd<I>(args: I) -> Fallible<Command>
where
I: IntoIterator,
I::Item: AsRef<std::ffi::OsStr>,
{
let mut cmd = Command::new(main_binary_path()?);
cmd.args(args);
Ok(cmd)
}
// As stdin only can read from File, let's create a temp file with provided contents, then feed it
// to the stdin. File will be automatically deleted after close.
pub fn file_from_buf(val: impl AsRef<[u8]>) -> Fallible<File> {
let mut file = tempfile::tempfile()?;
file.write_all(val.as_ref())?;
file.sync_all()?;
file.seek(SeekFrom::Start(0))?;
Ok(file)
}
pub trait CommandExt {
fn stdin_buf(&mut self, val: impl AsRef<[u8]>) -> Fallible<&mut Self>;
fn tty_override(
&mut self,
stdin_is_tty: bool,
stdout_is_tty: bool,
stderr_is_tty: bool,
) -> &mut Self;
}
impl CommandExt for Command {
fn stdin_buf(&mut self, val: impl AsRef<[u8]>) -> Fallible<&mut Self> {
Ok(self.stdin(file_from_buf(val)?))
}
fn tty_override(
&mut self,
stdin_is_tty: bool,
stdout_is_tty: bool,
stderr_is_tty: bool,
) -> &mut Self {
let mut cmd = self;
if stdin_is_tty {
cmd = cmd.env("RYPT_STDIN_TTY_OVERRIDE", "1");
}
if stdout_is_tty {
cmd = cmd.env("RYPT_STDOUT_TTY_OVERRIDE", "1");
}
if stderr_is_tty {
cmd = cmd.env("RYPT_STDERR_TTY_OVERRIDE", "1");
}
cmd
}
}
#[cfg(unix)]
pub fn symlink(src: impl AsRef<Path>, dest: impl AsRef<Path>) -> Fallible<()> {
std::os::unix::fs::symlink(src, dest)?;
Ok(())
}
#[cfg(windows)]
pub fn symlink(src: impl AsRef<Path>, dest: impl AsRef<Path>) -> Fallible<()> {
std::os::windows::fs::symlink_file(src, dest)?;
Ok(())
}
| true |
2d2b25d89753faa2d2cfbe5edb31162fc496a0b6
|
Rust
|
shun-shobon/atcoder-old
|
/abs/src/bin/abc088b.rs
|
UTF-8
| 383 | 2.765625 | 3 |
[] |
no_license
|
use proconio::input;
fn main() {
input! {
n: usize,
mut a: [usize; n],
}
a.sort_by(|x, y| x.cmp(y).reverse());
let (alice, bob) = a.iter().enumerate().fold((0, 0), |(a_acc, b_acc), (i, x)| {
if i % 2 == 0 {
(a_acc + x, b_acc)
} else {
(a_acc, b_acc + x)
}
});
println!("{}", alice - bob);
}
| true |
8428553f0cdd93569c985f1f8ae549b5c177ee93
|
Rust
|
jaems33/advanced_rust
|
/functions_and_procedures/src/main.rs
|
UTF-8
| 1,118 | 3.78125 | 4 |
[] |
no_license
|
fn some_function(param_a: f32, param_b: i32) -> f32 {
println!("This is a some function");
// Type casting
//Can also do this 10f32 or 10 as f32
let value = param_a + param_b as f32 + 10_f32;
value
}
fn some_procedure(param_a: f32) {
println!("You provided {}", param_a);
}
fn some_str_slice_procedure(param: &str){
println!("I'm in a procedure: {}", param);
}
fn some_string_procedure(param: &String){
println!("I'm in a procedure: {}", param);
}
// Technically a procedure most of the time
fn main() {
let value = some_function(10.2, 30392);
println!("Value was: {}", value);
some_procedure(10f32);
some_str_slice_procedure("Sample String Slice");
let message = String::from("I am a string but with ampersand I'm a borrow");
/*
Rust co-erces a String to a string slice if it knows that a function
or procedure does not change the data.some_string_procedure.
If the compiler detects potential threading or memory issues it will complain.
*/
some_str_slice_procedure(&message);
some_string_procedure(&message);
}
| true |
00ee8fb3647e6268806b2b8dcdd9dc3c68626717
|
Rust
|
spacemeshos/svm
|
/crates/host/types/src/transaction/mod.rs
|
UTF-8
| 1,511 | 2.53125 | 3 |
[
"LicenseRef-scancode-free-unknown",
"MIT"
] |
permissive
|
use std::fmt;
mod context;
mod envelope;
mod id;
mod layer;
pub use context::Context;
pub use envelope::Envelope;
pub use id::TransactionId;
pub use layer::Layer;
use crate::Address;
/// An in-memory representation of an `Call Account` transaction.
#[derive(PartialEq, Clone)]
pub struct Transaction {
/// The `version`.
pub version: u16,
/// The target `Address`.
pub target: Address,
/// Function's name to execute
pub func_name: String,
/// Transaction's `VerifyData`
pub verifydata: Vec<u8>,
/// Transaction's `CallData`
pub calldata: Vec<u8>,
}
impl Transaction {
#[doc(hidden)]
pub fn target(&self) -> &Address {
&self.target
}
#[doc(hidden)]
pub fn func_name(&self) -> &str {
&self.func_name
}
#[doc(hidden)]
pub fn verifydata(&self) -> &[u8] {
&self.verifydata
}
#[doc(hidden)]
pub fn calldata(&self) -> &[u8] {
&self.calldata
}
}
impl fmt::Debug for Transaction {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let verifydata = self.verifydata.iter().take(4).collect::<Vec<_>>();
let calldata = self.calldata.iter().take(4).collect::<Vec<_>>();
f.debug_struct("Transaction")
.field("version", &self.version)
.field("target", self.target())
.field("verifydata", &verifydata)
.field("calldata", &calldata)
.field("function", &self.func_name())
.finish()
}
}
| true |
f4730ad58e1c63999fc13a307e12e9cf085af2fd
|
Rust
|
geo-ant/fluent-comparisons
|
/macro_expansion_tests/none_of_expansion.rs
|
UTF-8
| 332 | 3.25 | 3 |
[
"MIT"
] |
permissive
|
use fluent_comparisons::none_of;
struct Dummy {
pub length : usize,
}
pub fn something() {
let first = none_of!({1,2,3}<4);
let v = Dummy {length : 2};
let second = none_of!( {v.length,2_usize.pow(2),3*4+1} == v.length);
let square = |x|x*x;
let third = none_of!({4+4+1,square(7*2),120_i32.pow(2)}<=8);
}
| true |
f72bccd624268d220161307bb7867ca38268a8d4
|
Rust
|
fergusbarratt/PhysicsAlgorithms
|
/dmrg/src/main.rs
|
UTF-8
| 1,635 | 2.859375 | 3 |
[
"MIT"
] |
permissive
|
extern crate nalgebra;
use nalgebra::{DMat, DVec};
use std::ops::{Add, Sub, Mul};
trait Conjugable {
fn conj(&self) -> Self;
}
impl Conjugable for f64 {
fn conj(&self) -> f64 {
*self
}
}
#[derive(Debug, Clone)]
struct Operator<T: Mul + Add + Sub + Copy> {
mat_rep: DMat<T>,
}
#[derive(Debug, Clone)]
struct Bra<T>
where T: Mul + Add + Sub + Copy
{
mat_rep : DVec<T>,
}
#[derive(Debug, Clone)]
struct Ket<T>
where T: Mul + Add + Sub + Copy
{
mat_rep : DVec<T>,
}
impl<T> Mul<Operator<T>> for Bra<T>
where T: Mul + Add + Sub + Copy
{
type Output = Bra<T>;
fn mul(self, f:Operator<T>) -> Bra<T> {
Bra { mat_rep : self.mat_rep * f.mat_rep }
}
}
impl<T> Mul<Ket<T>> for Operator<T>
where T: Mul + Add + Sub + Copy
{
type Output = Ket<T>;
fn mul(self, f:Ket<T>) -> Ket<T> {
Ket { mat_rep : self.mat_rep * f.mat_rep }
}
}
impl<T> Mul<Operator<T>> for Operator<T>
where T: Mul + Add + Sub + Copy
{
type Output = Operator<T>;
fn mul(self, f:Operator<T>) -> Operator<T> {
Operator { mat_rep : self.mat_rep * f.mat_rep }
}
}
impl<T> Mul<Ket<T>> for Bra<T>
where T: Mul + Add + Sub + Copy + Conjugable
{
type Output = T;
fn mul(self, f:Ket<T>) -> T {
let mut ret: T = 0.0;
for (ai, bi) in self.mat_rep.zip(f.mat_rep) {
ret += ai*bi;
}
ret
}
}
fn main() {
let op = Operator {mat_rep: DMat::from_fn(4, 4, |i, j| i as f64 + j as f64)};
let st = Ket {mat_rep: DVec::from_fn(4, |i| i as f64)};
println!("{:?}", op);
println!("{:?}", st);
}
| true |
133b144ba181ba6cc8deab2c443f515296636c56
|
Rust
|
bvssvni/wave_timeline
|
/src/lib.rs
|
UTF-8
| 9,383 | 2.5625 | 3 |
[
"MIT"
] |
permissive
|
extern crate graphics;
extern crate input;
extern crate rect;
use graphics::{ Context, Graphics };
use input::{ GenericEvent };
mod drawutils;
mod rectangle_box;
pub mod timeline_split;
pub struct Timeline {
pub frames: u32,
pub current_frame: u32,
pub hover_frame: Option<u32>,
pub start_frame: u32,
pub bounds: [u32; 4],
pub settings: TimelineSettings,
pub hover_goto_start: bool,
pub hover_goto_end: bool,
}
pub struct TimelineSettings {
pub offset: Offset,
pub frame_size: [f64; 2],
pub frame_offset_x: f64,
pub left_to_goto_start: f64,
pub right_to_goto_end: f64,
pub lift_hover_frame: f64,
}
pub struct Offset {
pub left: f64,
pub right: f64,
pub top: f64,
}
pub struct ComputedTimelineSettings {
pub width_for_frames: f64,
pub max_visible_frames: u32,
pub end_frame: u32,
}
impl TimelineSettings {
pub fn new() -> TimelineSettings {
TimelineSettings {
offset: Offset {
left: 20.0, right: 20.0, top: 20.0,
},
frame_size: [20.0, 20.0],
frame_offset_x: 5.0,
left_to_goto_start: 5.0,
right_to_goto_end: 5.0,
lift_hover_frame: 15.0,
}
}
}
impl ComputedTimelineSettings {
pub fn new(timeline: &Timeline, settings: &TimelineSettings)
-> ComputedTimelineSettings
{
use std::cmp::min;
let width_for_frames = timeline.bounds[2] as f64
- settings.offset.left - settings.offset.right;
let max_visible_frames: u32 =
if width_for_frames < settings.frame_size[0] {
0
} else {
1
+ (
(width_for_frames - settings.frame_size[0])
/ (settings.frame_size[0] + settings.frame_offset_x)
) as u32
};
let end_frame = min(
timeline.frames,
timeline.start_frame + max_visible_frames
);
ComputedTimelineSettings {
width_for_frames: width_for_frames,
max_visible_frames: max_visible_frames,
end_frame: end_frame
}
}
}
impl Timeline {
pub fn new_frames_bounds(frames: u32, bounds: [u32; 4]) -> Timeline {
Timeline {
frames: frames,
current_frame: 0,
hover_frame: None,
start_frame: 0,
bounds: bounds,
settings: TimelineSettings::new(),
hover_goto_start: false,
hover_goto_end: false,
}
}
pub fn event<E: GenericEvent>(&mut self, e: &E) {
use input::{ MouseCursorEvent, PressEvent };
if let Some(pos) = e.mouse_cursor_args() {
// Detect hover frame.
{
let computed_settings = ComputedTimelineSettings::new(self,
&self.settings);
let left_to_frame: f64 = self.settings.offset.left;
let frame_width: f64 = self.settings.frame_size[0];
let frame_offset_x: f64 = self.settings.frame_offset_x;
let end_frame: u32 = computed_settings.end_frame;
let (x, y) = (pos[0], pos[1]);
let left = self.bounds[0] as f64 + left_to_frame;
let right = left + end_frame as f64 * (frame_width + frame_offset_x);
let top = self.bounds[1] as f64;
let bottom = top + self.bounds[3] as f64;
if x < left || x > right
|| y < top || y > bottom {
self.hover_frame = None;
} else {
let i: u32 = ((x - left) / (frame_width + frame_offset_x)) as u32;
self.hover_frame = Some(i);
}
}
// Detect hover over goto start and goto end buttons.
{
let left_to_goto_start = self.settings.left_to_goto_start;
let right_to_goto_end = self.settings.right_to_goto_end;
let top_to_frame = self.settings.offset.top;
let frame_width = self.settings.frame_size[0];
let frame_height = self.settings.frame_size[1];
let outside = |bounds: [f64; 4]| {
let (x, y) = (pos[0], pos[1]);
(x < bounds[0] || y < bounds[1]
|| x > bounds[0] + bounds[2] || y > bounds[1] + bounds[3])
};
self.hover_goto_start = !outside([
self.bounds[0] as f64 + left_to_goto_start,
self.bounds[1] as f64 + top_to_frame,
frame_width,
frame_height
]);
self.hover_goto_end = !outside([
self.bounds[0] as f64 + self.bounds[2] as f64
- right_to_goto_end - frame_width,
self.bounds[1] as f64 + top_to_frame,
frame_width,
frame_height
]);
}
}
if let Some(button) = e.press_args() {
use input::{ Button, MouseButton };
if button == Button::Mouse(MouseButton::Left) {
if self.hover_goto_start {
println!("TEST goto start");
} else if self.hover_goto_end {
println!("TEST goto end");
}
}
}
}
pub fn draw_timeline<G: Graphics>(&self, c: &Context, g: &mut G) {
use std::cmp::min;
let left_to_frame: f64 = self.settings.offset.left;
let right_to_frame: f64 = self.settings.offset.right;
let top_to_frame: f64 = self.settings.offset.top;
let frame_width: f64 = self.settings.frame_size[0];
let frame_height: f64 = self.settings.frame_size[1];
let frame_offset_x: f64 = self.settings.frame_offset_x;
let left_to_goto_start: f64 = self.settings.left_to_goto_start;
let right_to_goto_end: f64 = self.settings.right_to_goto_end;
let lift_hover_frame: f64 = self.settings.lift_hover_frame;
let computed_settings = ComputedTimelineSettings::new(self, &self.settings);
let slide_offset: f64 = 0.0;
let width_for_frames = computed_settings.width_for_frames;
let max_visible_frames: u32 = computed_settings.max_visible_frames;
let end_frame = computed_settings.end_frame;
let blue = [0.0, 0.0, 1.0, 1.0];
let red = [1.0, 0.0, 0.0, 1.0];
// Draw bounds to see where the control is.
{
use graphics::Rectangle;
let bounds = [
self.bounds[0] as f64,
self.bounds[1] as f64,
self.bounds[2] as f64,
self.bounds[3] as f64
];
Rectangle::new_border([0.0, 0.0, 1.0, 1.0], 0.5)
.draw(bounds, &c.draw_state, c.transform, g);
}
// Draw a sequence of squares for each frame.
{
use graphics::Rectangle;
let frame_bounds = |i: u32, lift: f64| [
self.bounds[0] as f64 + left_to_frame
+ i as f64 * (frame_width + frame_offset_x)
- slide_offset,
self.bounds[1] as f64 + top_to_frame - lift,
frame_width,
frame_height
];
let rect = Rectangle::new_border(blue, 0.5);
for i in 0..end_frame - self.start_frame {
// Don't draw the hover frame.
if Some(i) == self.hover_frame { continue; }
let bounds = frame_bounds(i, 0.0);
rect.draw(bounds, &c.draw_state, c.transform, g);
}
if let Some(i) = self.hover_frame {
let bounds = frame_bounds(i, lift_hover_frame);
rect.draw(bounds, &c.draw_state, c.transform, g);
}
}
// Draw navigate to start or end buttons.
{
use graphics::Line;
use graphics::math::*;
let line = Line::new([0.0, 0.0, 1.0, 1.0], 0.5);
let at_beginning: bool = self.start_frame == 0;
drawutils::draw_goto_end(
at_beginning,
[
self.bounds[0] as f64 + left_to_goto_start + frame_width,
self.bounds[1] as f64 + top_to_frame
],
[
-frame_width * 0.5,
frame_height
],
&Line::new(if self.hover_goto_start { red } else { blue }, 0.5),
c, g
);
let at_end: bool = end_frame >= self.frames;
drawutils::draw_goto_end(
at_end,
[
self.bounds[0] as f64 + self.bounds[2] as f64
- right_to_goto_end - frame_width,
self.bounds[1] as f64 + top_to_frame
],
[
frame_width * 0.5,
frame_height
],
&Line::new(if self.hover_goto_end { red } else { blue }, 0.5),
c, g
);
}
}
pub fn draw_drag<G: Graphics>(&self, c: &Context, g: &mut G) {
}
}
| true |
046bc4b3094ae37f26b52305566511a151a19fca
|
Rust
|
zhnlk/jvm
|
/crates/vm/src/util/attributes.rs
|
UTF-8
| 2,411 | 2.609375 | 3 |
[
"Apache-2.0"
] |
permissive
|
use classfile::{AttributeType, BytesRef};
pub fn assemble_annotation(attrs: &[AttributeType]) -> Option<Vec<u8>> {
let mut vis = None;
let mut in_vis = None;
for it in attrs.iter() {
match it {
AttributeType::RuntimeVisibleAnnotations { raw, .. } => {
vis = Some(raw.clone());
}
AttributeType::RuntimeInvisibleAnnotations { raw, .. } => {
in_vis = Some(raw.clone());
}
_ => (),
}
}
do_assemble(vis, in_vis)
}
pub fn assemble_param_annotation(attrs: &[AttributeType]) -> Option<Vec<u8>> {
let mut vis = None;
let mut in_vis = None;
for it in attrs.iter() {
match it {
AttributeType::RuntimeVisibleParameterAnnotations { raw, .. } => {
vis = Some(raw.clone());
}
AttributeType::RuntimeInvisibleParameterAnnotations { raw, .. } => {
in_vis = Some(raw.clone());
}
_ => (),
}
}
do_assemble(vis, in_vis)
}
pub fn assemble_type_annotation(attrs: &[AttributeType]) -> Option<Vec<u8>> {
let mut vis = None;
let mut in_vis = None;
for it in attrs.iter() {
match it {
AttributeType::RuntimeVisibleTypeAnnotations { raw, .. } => {
vis = Some(raw.clone());
}
AttributeType::RuntimeInvisibleTypeAnnotations { raw, .. } => {
in_vis = Some(raw.clone());
}
_ => (),
}
}
do_assemble(vis, in_vis)
}
pub fn assemble_annotation_default(attrs: &[AttributeType]) -> Option<Vec<u8>> {
let mut vis = None;
for it in attrs.iter() {
if let AttributeType::AnnotationDefault { raw, .. } = it {
vis = Some(raw.clone());
}
}
do_assemble(vis, None)
}
pub fn get_signature(attrs: &[AttributeType]) -> u16 {
for it in attrs.iter() {
if let AttributeType::Signature { signature_index } = it {
return *signature_index;
}
}
0
}
fn do_assemble(vis: Option<BytesRef>, in_vis: Option<BytesRef>) -> Option<Vec<u8>> {
let mut raw = None;
if let Some(v) = vis {
raw = Some(Vec::from(v.as_slice()));
}
if let Some(v) = in_vis {
if let Some(raw) = raw.as_mut() {
raw.extend_from_slice(v.as_slice());
}
}
raw
}
| true |
80b259e131ce6d674c3f25752c71fa943c544079
|
Rust
|
ygf11/rsocks
|
/protocol/src/packet.rs
|
UTF-8
| 18,803 | 2.578125 | 3 |
[
"MIT"
] |
permissive
|
use crate::packet::ReplyType::*;
use crate::packet::AddressType::{Ipv4, Domain, Ipv6};
use crate::packet::CmdType::{Connect, Bind, Udp};
use crate::packet::AuthType::*;
use crate::packet::SubVersion::V0;
use std::borrow::Borrow;
use std::ops::BitAnd;
/// this packet is for authentication method
/// selecting request when client finishes connecting.
#[derive(Debug, PartialEq)]
pub struct AuthSelectRequest {
version: Version,
n_methods: u8,
methods: Vec<AuthType>,
}
pub fn parse_auth_select_request_packet(data: &[u8]) -> Result<Option<AuthSelectRequest>, String> {
let len = data.len();
if len < 2 {
return Ok(None);
}
// version
let mut version = parse_version(data.get(0).cloned())?;
// num of methods
let n_methods = data.get(1).cloned().unwrap();
let num = n_methods;
// verify data len
let total: usize = usize::from(2 + n_methods);
if data.len() < total {
return Ok(None);
}
let mut i = 0;
let mut methods = Vec::<AuthType>::new();
while i < num {
let index = usize::from(2 + i);
let method = parse_auth_type(data.get(index).cloned())?;
methods.push(method);
i = i + 1;
}
let result = AuthSelectRequest {
version,
n_methods,
methods,
};
Ok(Some(result))
}
pub fn encode_auth_select_request(request: AuthSelectRequest) -> Result<Vec<u8>, &'static str> {
let mut data = Vec::<u8>::new();
let version_num = encode_version(&request.version)?;
data.push(version_num);
data.push(request.n_methods);
let methods = request.methods;
for i in 0..methods.len() {
let auth_type = methods.get(i);
let auth_num = encode_auth_type(auth_type.unwrap())?;
data.push(auth_num);
}
Ok(data)
}
impl AuthSelectRequest {
pub fn new(version: Version, n_methods: u8, methods: Vec<AuthType>) -> AuthSelectRequest {
AuthSelectRequest {
version,
n_methods,
methods,
}
}
pub fn version(&self) -> &Version {
&self.version
}
pub fn n_methods(&self) -> u8 {
self.n_methods
}
pub fn methods(&self) -> &Vec<AuthType> {
&self.methods
}
}
/// this packet is for authentication method selecting reply from server
pub struct AuthSelectReply {
version: Version,
method: AuthType,
}
pub fn parse_auth_select_reply_packet(data: &[u8]) -> Result<Option<AuthSelectReply>, &'static str> {
let len = data.len();
if len != 2 {
return Ok(None);
}
let version = parse_version(data.get(0).cloned())?;
let method = parse_auth_type(data.get(1).cloned())?;
let result = AuthSelectReply {
version,
method,
};
Ok(Some(result))
}
pub fn encode_auth_select_reply(reply: &AuthSelectReply) -> Result<Vec<u8>, &'static str> {
let version_num = encode_version(reply.version())?;
let auth_num = encode_auth_type(reply.auth_type())?;
let mut buffer = Vec::<u8>::new();
buffer.push(version_num);
buffer.push(auth_num);
Ok(buffer)
}
impl AuthSelectReply {
pub fn new(version: Version, auth_type: AuthType) -> AuthSelectReply {
AuthSelectReply {
version,
method: auth_type,
}
}
pub fn version(&self) -> &Version {
&self.version
}
pub fn auth_type(&self) -> &AuthType {
&self.method
}
}
/// this packet is for target destination service request from client
pub struct DstServiceRequest {
version: Version,
cmd: CmdType,
reserve: u8,
address_type: AddressType,
address: String,
port: u16,
}
pub fn parse_dst_service_request(data: &[u8]) -> Result<Option<(DstServiceRequest, u8)>, &str> {
let len = data.len();
if len < 4 {
return Ok(None);
}
let version = parse_version(data.get(0).cloned())?;
let cmd = parse_cmd(data.get(1).cloned())?;
let reserve = match data.get(2).cloned() {
Some(num) => num,
None => 0
};
let address_type = parse_address_type(data.get(3).cloned())?;
let (address, address_len) = match parse_dst_address(&data[4..data.len()],
&address_type)? {
Some(result) => result,
None => return Ok(None)
};
let len: usize = usize::from(address_len);
if data.len() < len + 6 {
return Ok(None);
}
let port = get_port(data.get(4 + len..6 + len).unwrap())?;
let result = DstServiceRequest {
version,
cmd,
reserve,
address_type,
address,
port,
};
Ok(Some((result, address_len)))
}
pub fn parse_dst_address(data: &[u8], addr_type: &AddressType) -> Result<Option<(String, u8)>, &'static str> {
let len = data.len();
match addr_type {
Ipv4 => {
if len < 4 {
return Ok(None);
}
let address = get_ipv4_from_bytes(data.get(0..4).unwrap())?;
//let port: u16 = get_port(data.get(4..6).unwrap())?;
Ok((Some((address, 4))))
}
Ipv6 => {
if len < 16 {
return Ok(None);
}
let address = get_ipv6_from_bytes(data.get(0..16).unwrap())?;
//let port = get_port(data.get(16..18).unwrap())?;
//let port: u16 = (data[17] as u16 | (data[18] as u16) << 8);
Ok(Some((address, 16)))
}
Domain => {
let addr_len = usize::from(data.get(0).cloned().unwrap());
if len < addr_len {
return Ok(None);
}
let byte_array = data.get(1..addr_len + 1).unwrap();
let address = get_domain_from_bytes(byte_array)?;
//let port = get_port(data.get(addr_len + 1..addr_len + 3).unwrap())?;
// let port: u16 = (data[addr_len + 1] as u16 | (data[addr_len + 2] as u16) << 8);
let len = addr_len + 1;
Ok(Some((address, len as u8)))
}
}
}
pub fn get_domain_from_bytes(bytes: &[u8]) -> Result<String, &'static str> {
parse_string_from_bytes(bytes)
}
pub fn get_ipv4_from_bytes(bytes: &[u8]) -> Result<String, &'static str> {
let first = bytes[0].to_string();
let second = bytes[1].to_string();
let third = bytes[2].to_string();
let forth = bytes[3].to_string();
let mut result = String::new();
result.push_str(first.as_str());
result.push('.');
result.push_str(second.as_str());
result.push('.');
result.push_str(third.as_str());
result.push('.');
result.push_str(forth.as_str());
Ok(result)
}
pub fn get_ipv6_from_bytes(bytes: &[u8]) -> Result<String, &'static str> {
// todo parse bytes to ipv6
Ok(String::new())
}
pub fn get_port(bytes: &[u8]) -> Result<u16, &'static str> {
let len = bytes.len();
let high = bytes[0].clone();
let low = bytes[1].clone();
let port = (low as u16 | (high as u16) << 8);
Ok(port)
}
pub fn encode_dst_service_request(request: DstServiceRequest) -> Result<Vec<u8>, &'static str> {
let mut data = Vec::<u8>::new();
let version = encode_version(&request.version)?;
let cmd_type = encode_cmd(&request.cmd)?;
let reserve = request.reserve;
let address_type = encode_address_type(&request.address_type)?;
// ipv4
let mut address = encode_address_with_type(request.address, &request.address_type)?;
data.push(version);
data.push(cmd_type);
data.push(0);
data.push(address_type);
data.append(&mut address);
let port = request.port;
let low_bit = port.bitand(0x00FF) as u8;
let high_bit = (port >> 8) as u8;
data.push(high_bit);
data.push(low_bit);
Ok(data)
}
impl DstServiceRequest {
pub fn new(version: Version, cmd: CmdType, reserve: u8, address_type: AddressType
, address: String, port: u16) -> DstServiceRequest {
DstServiceRequest {
version,
cmd,
reserve,
address_type,
address,
port,
}
}
pub fn version(&self) -> &Version {
&self.version
}
pub fn cmd(&self) -> &CmdType {
&self.cmd
}
pub fn address_type(&self) -> &AddressType {
&self.address_type
}
pub fn address(&self) -> String {
self.address.to_string()
}
pub fn port(&self) -> u16 {
self.port
}
}
/// his packet is for target destination service request from server
pub struct DstServiceReply {
version: Version,
reply: ReplyType,
reserve: u8,
address_type: AddressType,
address: String,
port: u16,
}
pub fn parse_dst_service_reply(data: &[u8]) -> Result<Option<DstServiceReply>, &'static str> {
let len = data.len();
if len < 4 {
return Ok(None);
}
let version = parse_version(data.get(0).cloned())?;
let reply = parse_reply_type(data.get(1).cloned())?;
let reserve = match data.get(2).cloned() {
Some(num) => num,
None => 0
};
let address_type = parse_address_type(data.get(3).cloned())?;
let (address, address_len) = match parse_dst_address(&data[4..data.len()],
&address_type)? {
Some(result) => result,
None => return Ok(None)
};
let len: usize = usize::from(address_len);
let port = get_port(data.get(4 + len..6 + len).unwrap())?;
let result = DstServiceReply {
version,
reply,
reserve,
address_type,
address,
port,
};
Ok(Some(result))
}
pub fn encode_dst_service_reply(dst_reply: DstServiceReply) -> Result<Vec<u8>, &'static str> {
let mut data = Vec::<u8>::new();
let version = encode_version(&dst_reply.version)?;
let reply = encode_reply_type(&dst_reply.reply)?;
let address_type = encode_address_type(&dst_reply.address_type)?;
let mut address =
encode_address_with_type(dst_reply.address, &dst_reply.address_type)?;
data.push(version);
data.push(reply);
data.push(0);
data.push(address_type);
if dst_reply.address_type == AddressType::Domain {
let address_len = address.len() as u8;
data.push(address_len);
}
data.append(&mut address);
let port = dst_reply.port;
let low_bit = port.bitand(0x00FF) as u8;
let high_bit = (port >> 8) as u8;
data.push(high_bit);
data.push(low_bit);
Ok(data)
}
pub fn encode_address_with_type(address: String, address_type: &AddressType)
-> Result<Vec<u8>, &'static str> {
match address_type {
Ipv4 => encode_address_for_ipv4(address),
Domain => encode_address_as_domain(address),
Ipv6 => Err("ipv6 is not support in encoding."),
}
}
pub fn encode_address_as_domain(address: String) -> Result<Vec<u8>, &'static str> {
Ok(address.as_bytes().to_vec())
}
pub fn encode_address_for_ipv4(address: String) -> Result<Vec<u8>, &'static str> {
let list: Vec<_> = address.split(".").collect();
let mut result = Vec::<u8>::new();
for i in 0..list.len() {
let num: u8 = match list.get(i).unwrap().parse() {
Ok(value) => Ok(value),
Err(e) => Err("parse address error.")
}?;
result.push(num);
}
Ok(result)
}
impl DstServiceReply {
pub fn new(version: Version, reply: ReplyType
, address_type: AddressType, address: String, port: u16) -> DstServiceReply {
DstServiceReply {
version,
reply,
reserve: 0,
address_type,
address,
port,
}
}
}
pub struct UserPassAuthRequest {
version: SubVersion,
u_len: u8,
name: String,
p_len: u8,
password: String,
}
impl UserPassAuthRequest {
pub fn version(&self) -> &SubVersion {
&self.version
}
pub fn u_len(&self) -> u8 {
self.u_len
}
pub fn name(&self) -> &String {
&self.name
}
pub fn p_len(&self) -> u8 {
self.p_len
}
pub fn password(&self) -> &String {
&self.password
}
}
pub fn parse_user_auth_request(data: &[u8]) -> Result<UserPassAuthRequest, &'static str> {
let len = data.len();
if len < 2 {
return Err("data not enough when parsing auth request.");
}
let version = parse_sub_version(data.get(0).cloned())?;
let (u_len, name) = parse_len_and_string(&data[1..])?;
let start = usize::from(2 + u_len);
let (p_len, password) = parse_len_and_string(&data[start..])?;
let result = UserPassAuthRequest {
version,
u_len,
name,
p_len,
password,
};
Ok(result)
}
pub fn parse_len_and_string(data: &[u8]) -> Result<(u8, String), &'static str> {
let total = data.len();
if total == 0 {
return Err("data is not enough.");
}
let len = match data.get(0).cloned() {
Some(size) => Ok(size),
None => Err("len is none")
}?;
if total < usize::from(1 + len) {
return Err("data is not enough.");
}
let end = usize::from(len + 1);
let name = parse_string_from_bytes(data.get(1..end).unwrap())?;
Ok((len, name))
}
pub fn parse_string_from_bytes(data: &[u8]) -> Result<String, &'static str> {
match std::str::from_utf8(data) {
Ok(addr) => Ok(String::from(addr)),
Err(e) => Err("err from bytes to utf8 string.")
}
}
pub struct UserPassAuthReply {
version: SubVersion,
status: AuthResult,
}
impl UserPassAuthReply {
pub fn version(&self) -> &SubVersion {
&self.version
}
pub fn status(&self) -> &AuthResult {
&self.status
}
}
pub fn parse_user_auth_reply(data: &[u8]) -> Result<UserPassAuthReply, &'static str> {
let len = data.len();
if len != 2 {
return Err("data not enough.");
}
let version = parse_sub_version(data.get(0).cloned())?;
let status = parse_auth_result(data.get(1).cloned())?;
let result = UserPassAuthReply {
version,
status,
};
Ok(result)
}
/// socks version
#[derive(Debug, PartialEq)]
pub enum Version {
Socks5,
Others,
}
/// sub negotiation version
#[derive(Debug, PartialEq)]
pub enum SubVersion {
V0,
Others,
}
pub fn parse_version(version: Option<u8>) -> Result<Version, &'static str> {
match version {
Some(5) => Ok(Version::Socks5),
Some(_) => Ok(Version::Others),
None => Err("empty version num.")
}
}
pub fn encode_version(version: &Version) -> Result<u8, &'static str> {
match version {
Version::Socks5 => Ok(5),
// never
Version::Others => Err("proxy only support version 5.")
}
}
fn parse_sub_version(version: Option<u8>) -> Result<SubVersion, &'static str> {
match version {
Some(0) => Ok(V0),
Some(_) => Ok(SubVersion::Others),
None => Err("empty sub version num.")
}
}
/// auth type enum
#[derive(Debug, PartialEq)]
pub enum AuthType {
Non,
Gssapi,
NamePassword,
IanaAssigned,
Reserved,
NonAccept,
}
pub fn parse_auth_type(auth: Option<u8>) -> Result<AuthType, &'static str> {
match auth {
Some(0) => Ok(Non),
Some(1) => Ok(Gssapi),
Some(2) => Ok(NamePassword),
Some(3) => Ok(IanaAssigned),
Some(0x80) => Ok(Reserved),
Some(0xff) => Ok(NonAccept),
_ => return Err("auth method not supported.")
}
}
pub fn encode_auth_type(auth_type: &AuthType) -> Result<u8, &'static str> {
match auth_type {
Non => Ok(0),
NamePassword => Ok(2),
_ => Err("auth method not supported."),
}
}
/// cmd type enum
pub enum CmdType {
Connect,
Bind,
Udp,
}
pub fn parse_cmd(cmd: Option<u8>) -> Result<CmdType, &'static str> {
match cmd {
Some(1) => Ok(Connect),
Some(2) => Ok(Bind),
Some(3) => Ok(Udp),
_ => Err("cmd type not support.")
}
}
pub fn encode_cmd(cmd_type: &CmdType) -> Result<u8, &'static str> {
match cmd_type {
Connect => Ok(1),
Bind => Ok(2),
Udp => Ok(3),
_ => Err("cmd type not support.")
}
}
/// address type enum
#[derive(Debug, PartialEq)]
pub enum AddressType {
Ipv4,
Domain,
Ipv6,
}
fn parse_address_type(addr_type: Option<u8>) -> Result<AddressType, &'static str> {
match addr_type {
Some(1) => Ok(Ipv4),
Some(3) => Ok(Domain),
Some(4) => Ok(Ipv6),
_ => Err("address type not support.")
}
}
pub fn encode_address_type(address_type: &AddressType) -> Result<u8, &'static str> {
match address_type {
Ipv4 => Ok(1),
Domain => Ok(3),
Ipv6 => Ok(4)
}
}
#[derive(Debug, PartialEq)]
pub enum AuthResult {
Success,
Failure,
}
fn parse_auth_result(result: Option<u8>) -> Result<AuthResult, &'static str> {
match result {
Some(0) => Ok(AuthResult::Success),
Some(_) => Ok(AuthResult::Failure),
_ => Err("auth reply is empty.")
}
}
/// reply type enum
#[derive(Debug, PartialEq)]
pub enum ReplyType {
Success,
ServerFailure,
ConnectionNotAllowed,
NetWorkUnReachable,
HostUnreachable,
ConnectionRefuse,
TTLExpired,
CmdNotSupport,
AddressTypeNotSupport,
Others,
}
pub fn encode_reply_type(reply_type: &ReplyType) -> Result<u8, &'static str> {
match reply_type {
Success => Ok(0),
ServerFailure => Ok(1),
ConnectionNotAllowed => Ok(2),
NetWorkUnReachable => Ok(3),
HostUnreachable => Ok(4),
ConnectionRefuse => Ok(5),
TTLExpired => Ok(6),
CmdNotSupport => Ok(7),
AddressTypeNotSupport => Ok(8),
ReplyType::Others => Ok(9),
}
}
fn parse_reply_type(reply_type: Option<u8>) -> Result<ReplyType, &'static str> {
match reply_type {
Some(0) => Ok(Success),
Some(1) => Ok(ServerFailure),
Some(2) => Ok(ConnectionNotAllowed),
Some(3) => Ok(NetWorkUnReachable),
Some(4) => Ok(HostUnreachable),
Some(5) => Ok(ConnectionRefuse),
Some(6) => Ok(TTLExpired),
Some(7) => Ok(CmdNotSupport),
Some(8) => Ok(AddressTypeNotSupport),
Some(9) => Ok(ReplyType::Others),
_ => Err("reply type not support.")
}
}
/// client stage transfer enum
pub enum ClientStage {
Init,
SendAuthSelect,
AuthSelectFinish,
// todo add sub session of auth
SendRequest,
RequestFinish,
SendContentRequest,
ContentFinish,
}
/// server stage transfer enum
#[derive(Debug, PartialEq)]
pub enum ServerStage {
Init,
AuthSelectFinish,
RequestFinish,
ReceiveContent,
ContentFinish,
}
| true |
b8cb74aa5bc73a6d7871ca1a336df0a5d85071e9
|
Rust
|
justinpombrio/synless
|
/language/src/ast/ast_ref.rs
|
UTF-8
| 2,388 | 3.25 | 3 |
[] |
no_license
|
use super::ast::{Id, NodeData};
use super::text::Text;
use crate::language::{Arity, LanguageSet};
use forest::{Bookmark, TreeRef};
use partial_pretty_printer::{PrettyDoc, ValidNotation};
/// An immutable reference to a node in an AST.
#[derive(Clone, Copy)]
pub struct AstRef<'f, 'l> {
pub(super) lang: &'f LanguageSet<'l>,
pub(super) tree_ref: TreeRef<'f, NodeData<'l>, Text>,
}
impl<'f, 'l> AstRef<'f, 'l> {
/// Get the arity of this node.
pub fn arity(self) -> &'l Arity {
let node = self.tree_ref.data();
&node.grammar.construct(node.construct_id).arity
}
/// Save a bookmark to return to later.
pub fn bookmark(self) -> Bookmark {
self.tree_ref.bookmark()
}
/// Return to a previously saved bookmark, as long as that bookmark's node
/// is present somewhere in this tree. This will work even if the Tree has
/// been modified since the bookmark was created. However, this method will
/// return `None` if the bookmark's node has since been deleted, or if it is
/// currently located in a different tree.
pub fn lookup_bookmark(self, mark: Bookmark) -> Option<AstRef<'f, 'l>> {
self.tree_ref.lookup_bookmark(mark).map(|tr| AstRef {
lang: self.lang,
tree_ref: tr,
})
}
}
impl<'d> PrettyDoc<'d> for AstRef<'d, 'd> {
type Id = Id;
fn id(self) -> Self::Id {
self.tree_ref.data().id
}
fn notation(self) -> &'d ValidNotation {
let node = self.tree_ref.data();
// TODO: No HashMap lookups while pretty printing!
let lang_name = &node.grammar.language_name();
&self
.lang
.current_notation_set(lang_name)
.lookup(node.construct_id)
}
/// Get this node's number of children, or `None` if it contains text instead.
fn num_children(self) -> Option<usize> {
if self.tree_ref.is_leaf() {
None
} else {
Some(self.tree_ref.num_children())
}
}
/// Get this node's text, or panic.
fn unwrap_text(self) -> &'d str {
assert!(self.arity().is_texty());
self.tree_ref.leaf().as_str()
}
/// Get this node's i'th child, or panic.
fn unwrap_child(self, i: usize) -> Self {
AstRef {
lang: self.lang,
tree_ref: self.tree_ref.child(i),
}
}
}
| true |
64c16f3dd55a2e89466592756dd38b4c8b02897c
|
Rust
|
cubicdaiya/onp
|
/rust/src/diff.rs
|
UTF-8
| 1,841 | 3.203125 | 3 |
[
"MIT"
] |
permissive
|
use std::cmp::max;
pub struct Diff {
a: String,
b: String,
m: usize,
n: usize,
}
pub fn build_diff(mut a: String, mut b: String) -> Diff {
if a.chars().count() > b.chars().count() {
let t = a;
a = b;
b = t;
}
return Diff {
a: a.to_string(),
b: b.to_string(),
m: a.chars().count(),
n: b.chars().count(),
};
}
impl Diff {
fn snake(&self, mut x: isize, mut y: isize) -> isize {
while x >= 0
&& y >= 0
&& x < self.m as isize
&& y < self.n as isize
&& self.a.chars().nth(x as usize).unwrap() == self.b.chars().nth(y as usize).unwrap()
{
x = x + 1;
y = y + 1;
}
return y;
}
pub fn ed(&self) -> usize {
let offset: usize = self.m + 1;
let delta: usize = self.n - self.m;
let size = self.m + self.n + 3;
let mut fp: Vec<isize> = vec![-1; size];
let mut p: usize = 0;
loop {
let mut k = offset - p;
while k <= delta + offset - 1 {
let y = max(fp[k - 1] + 1, fp[k + 1]);
fp[k] = self.snake(y - (k as isize) + (offset as isize), y);
k = k + 1;
}
let mut l = delta + p;
while l >= delta + 1 {
let y = max(fp[l + offset - 1] + 1, fp[l + 1 + offset]);
fp[l + offset] = self.snake(y - (l as isize), y);
l = l - 1;
}
let y = max(fp[delta + offset - 1] + 1, fp[delta + 1 + offset]);
fp[delta + offset] = self.snake(y - (delta as isize), y);
if fp[delta + offset] >= (self.n as isize) {
break;
}
p = p + 1;
}
return delta + 2 * p;
}
}
| true |
e30f9d7823b68fc0e2a449011f8caea90f0d0212
|
Rust
|
komu/rpbrtir
|
/src/textures/checkerboard.rs
|
UTF-8
| 3,178 | 3.171875 | 3 |
[] |
no_license
|
use core::{
texture::{Texture, TextureMapping2D, TextureMapping3D},
differential_geometry::DifferentialGeometry,
math::floor_to_int,
types::Float,
};
use std::sync::Arc;
pub struct Checkerboard2DTexture<T> {
mapping: Box<TextureMapping2D>,
tex1: Arc<Texture<T>>,
tex2: Arc<Texture<T>>,
aa_method: AAMethod,
}
pub struct Checkerboard3DTexture<T> {
mapping: Box<TextureMapping3D>,
tex1: Arc<Texture<T>>,
tex2: Arc<Texture<T>>,
}
#[derive(PartialEq, Eq)]
pub enum AAMethod {
None,
ClosedForm,
}
impl<T> Checkerboard2DTexture<T> {
pub fn new(mapping: Box<TextureMapping2D>,
tex1: Arc<Texture<T>>,
tex2: Arc<Texture<T>>,
aa_method: AAMethod) -> Checkerboard2DTexture<T> {
Checkerboard2DTexture { mapping, tex1, tex2, aa_method }
}
}
impl<T> Texture<T> for Checkerboard2DTexture<T> {
fn evaluate(&self, dg: &DifferentialGeometry) -> T {
let r = self.mapping.map(dg);
if self.aa_method == AAMethod::None {
if (floor_to_int(r.s) + floor_to_int(r.t)) % 2 == 0 {
self.tex1.evaluate(dg)
} else {
self.tex2.evaluate(dg)
}
} else {
// Compute closed-form box-filtered _Checkerboard2DTexture_ value
// Evaluate single check if filter is entirely inside one of them
let ds = r.dsdx.abs().max(r.dsdy.abs());
let dt = r.dtdx.abs().max(r.dtdy.abs());
let s0 = r.s - ds;
let s1 = r.s + ds;
let t0 = r.t - dt;
let t1 = r.t + dt;
if floor_to_int(s0) == floor_to_int(s1) && floor_to_int(t0) == floor_to_int(t1) {
// Point sample _Checkerboard2DTexture_
return if floor_to_int(r.s) + floor_to_int(r.t) % 2 == 0 {
self.tex1.evaluate(dg)
} else {
self.tex2.evaluate(dg)
};
}
// Apply box filter to checkerboard region
let sint = (bumpint(s1) - bumpint(s0)) / (2.0 * ds);
let tint = (bumpint(t1) - bumpint(t0)) / (2.0 * dt);
let mut area2 = sint + tint - 2.0 * sint * tint;
if ds > 1.0 || dt > 1.0 {
area2 = 0.5;
}
unimplemented!() // TODO
// return self.tex1.evaluate(dg) * (1.0 - area2) + self.tex2.evaluate(dg) * area2;
}
}
}
fn bumpint(x: Float) -> Float {
(x / 2.0).floor() + 2.0 * ((x / 2.0) - (x / 2.0).floor() - 0.5).max(0.0)
}
impl<T> Checkerboard3DTexture<T> {
pub fn new(mapping: Box<TextureMapping3D>,
tex1: Arc<Texture<T>>,
tex2: Arc<Texture<T>>) -> Checkerboard3DTexture<T> {
Checkerboard3DTexture { mapping, tex1, tex2 }
}
}
impl<T> Texture<T> for Checkerboard3DTexture<T> {
fn evaluate(&self, dg: &DifferentialGeometry) -> T {
let (p, _, _) = self.mapping.map(dg);
return if (floor_to_int(p.x) + floor_to_int(p.y) + floor_to_int(p.z)) % 2 == 0 {
self.tex1.evaluate(dg)
} else {
self.tex2.evaluate(dg)
};
}
}
| true |
0a497c9367917c1decacaa9e8bed668571f5450c
|
Rust
|
Giovan/lumen
|
/liblumen_compiler/src/config.rs
|
UTF-8
| 2,122 | 2.703125 | 3 |
[
"Apache-2.0"
] |
permissive
|
use std::collections::{HashMap, VecDeque};
use std::convert::Into;
use std::path::PathBuf;
use std::str::FromStr;
use std::sync::{Arc, Mutex};
use failure::{format_err, Error};
use libeir_diagnostics::{CodeMap, ColorChoice};
use libeir_syntax_erl::ParseConfig;
/// Determines which type of compilation to perform,
/// either parsing modules from BEAM files, or by
/// parsing modules from Erlang source code.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd)]
pub enum CompilerMode {
Erlang,
}
impl FromStr for CompilerMode {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"erl" => Ok(CompilerMode::Erlang),
_ => Err(format_err!("invalid file type {}", s)),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Verbosity {
Debug,
Info,
Warning,
Error,
Silent,
}
impl Verbosity {
pub fn from_level(level: isize) -> Self {
if level < 0 {
return Verbosity::Silent;
}
match level {
0 => Verbosity::Warning,
1 => Verbosity::Info,
_ => Verbosity::Debug,
}
}
}
/// This structure holds all top-level compiler options
/// and configuration; it is passed through all phases
/// of compilation
#[derive(Debug, Clone)]
pub struct CompilerSettings {
pub mode: CompilerMode,
pub color: ColorChoice,
pub source_dir: PathBuf,
pub output_dir: PathBuf,
//pub defines: HashMap<Symbol, MacroDef>,
pub warnings_as_errors: bool,
pub no_warn: bool,
pub verbosity: Verbosity,
pub code_path: Vec<PathBuf>,
pub include_path: VecDeque<PathBuf>,
pub codemap: Arc<Mutex<CodeMap>>,
}
impl Into<ParseConfig> for CompilerSettings {
fn into(self) -> ParseConfig {
ParseConfig {
codemap: self.codemap.clone(),
warnings_as_errors: self.warnings_as_errors,
no_warn: self.no_warn,
code_paths: self.code_path.clone().into(),
include_paths: self.include_path.clone(),
macros: None,
}
}
}
| true |
01e6b8003ea32b972a32183bdacb7df9a658d3ec
|
Rust
|
avs-simulator/ascod-comm
|
/ascod-comm-data/src/turret_messages/turret_input_card0.rs
|
UTF-8
| 3,293 | 2.765625 | 3 |
[
"MIT"
] |
permissive
|
use c2rust_bitfields::BitfieldStruct;
use static_assertions::assert_eq_size;
pub const SIZE_TURRET_INPUT_CARD0: usize = 10;
#[repr(C, packed)]
#[derive(BitfieldStruct, Clone, Debug)]
pub struct TurretInputCard0 {
#[bitfield(name = "tracking_dual_override", ty = "libc::uint16_t", bits = "0..=9")]
#[bitfield(name = "dual_override_x", ty = "libc::uint16_t", bits = "10..=19")]
#[bitfield(name = "dual_override_y", ty = "libc::uint16_t", bits = "20..=29")]
#[bitfield(name = "volume_radio_commander", ty = "libc::uint16_t", bits = "30..=39")]
#[bitfield(name = "tracking_gunner_control", ty = "libc::uint16_t", bits = "40..=49")]
#[bitfield(name = "gunner_control_elevation", ty = "libc::uint16_t", bits = "50..=59")]
#[bitfield(name = "gunner_control_traverse", ty = "libc::uint16_t", bits = "60..=69")]
#[bitfield(name = "manual_traverse", ty = "libc::uint16_t", bits = "70..=79")]
raw: [u8; SIZE_TURRET_INPUT_CARD0],
}
assert_eq_size!(TurretInputCard0, [u8; SIZE_TURRET_INPUT_CARD0]);
impl Default for TurretInputCard0 {
fn default() -> Self {
Self {
raw: [0; SIZE_TURRET_INPUT_CARD0],
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_default_has_all_zero() {
let turret_input_card0 = TurretInputCard0::default();
assert_eq!(turret_input_card0.tracking_dual_override(), 0);
assert_eq!(turret_input_card0.dual_override_x(), 0);
assert_eq!(turret_input_card0.dual_override_y(), 0);
assert_eq!(turret_input_card0.volume_radio_commander(), 0);
assert_eq!(turret_input_card0.tracking_gunner_control(), 0);
assert_eq!(turret_input_card0.gunner_control_elevation(), 0);
assert_eq!(turret_input_card0.gunner_control_traverse(), 0);
assert_eq!(turret_input_card0.manual_traverse(), 0);
}
#[test]
fn test_set_field_partially() {
let expected_result = 0x03AB;
let mut turret_input_card0 = TurretInputCard0::default();
turret_input_card0.set_dual_override_x(expected_result);
assert_eq!(turret_input_card0.dual_override_x(), expected_result);
assert_eq!(turret_input_card0.raw[0], 0x00);
assert_eq!(turret_input_card0.raw[1], 0xAC);
assert_eq!(turret_input_card0.raw[2], 0x0E);
}
#[test]
fn test_set_field_partially_with_cropped_overflow() {
let overflowing_value = 0x07AB;
let expected_result = 0x03AB;
let mut turret_input_card0 = TurretInputCard0::default();
turret_input_card0.set_dual_override_x(overflowing_value);
assert_eq!(turret_input_card0.dual_override_x(), expected_result);
assert_eq!(turret_input_card0.raw[0], 0x00);
assert_eq!(turret_input_card0.raw[1], 0xAC);
assert_eq!(turret_input_card0.raw[2], 0x0E);
}
#[test]
fn test_set_last_field() {
let expected_result = 0x03FF;
let mut turret_input_card0 = TurretInputCard0::default();
turret_input_card0.set_manual_traverse(expected_result);
assert_eq!(turret_input_card0.manual_traverse(), expected_result);
assert_eq!(turret_input_card0.raw[7], 0x00);
assert_eq!(turret_input_card0.raw[8], 0xC0);
assert_eq!(turret_input_card0.raw[9], 0xFF);
}
}
| true |
21571c9f6100a5e7ebc03ea0f8b9f1e29750359c
|
Rust
|
lilith645/DelinquentFood
|
/src/modules/system_interface/text_field.rs
|
UTF-8
| 4,858 | 2.9375 | 3 |
[] |
no_license
|
use maat_graphics::math;
use maat_graphics::DrawCall;
use cgmath::Vector2;
use cgmath::Vector4;
#[derive(Clone, PartialEq)]
pub struct TextField {
name: String,
text: String,
font: String,
wrap: bool,
centered: bool,
position: Vector2<f32>,
size: Vector2<f32>,
colour: Vector4<f32>,
editable: bool,
editing: bool,
}
impl TextField {
pub fn new_text_field(name: String, position: Vector2<f32>, size: Vector2<f32>, colour: Vector4<f32>, centered: bool, text: String, font: String) -> TextField {
TextField {
name: name,
text: text,
font: font,
wrap: false,
centered: centered,
position: position,
size: size,
colour: colour,
editable: false,
editing: false,
}
}
pub fn _new_text_field_editable(name: String, position: Vector2<f32>, size: Vector2<f32>, colour: Vector4<f32>, centered: bool, text: String, font: String) -> TextField {
println!("editable made");
TextField {
editable: true,
.. TextField::new_text_field(name, position, size, colour, centered, text, font)
}
}
pub fn _new_empty() -> TextField {
TextField {
name: "".to_string(),
text: "".to_string(),
font: "".to_string(),
wrap: false,
centered: false,
position: Vector2::new(0.0, 0.0),
size: Vector2::new(0.0, 0.0),
colour: Vector4::new(0.0, 0.0, 0.0, 0.0),
editable: false,
editing: false
}
}
pub fn is_touching(&self, at_location: Vector2<f32>) -> bool {
let size = self.size;
let width = size.x*0.06*self.text.len() as f32;
let height = size.y*0.15;
let center_x = self.position.x;
let center_y = self.position.y+height*0.5;
math::box_collision(Vector4::new(center_x, center_y, width, height), Vector4::new(at_location.x, at_location.y, 1.0, 1.0))
}
pub fn _get_all(&self) -> (String, String, String, bool, bool, Vector2<f32>, Vector2<f32>, Vector4<f32>) {
let name = self.name.to_string();
let text = self.text.to_string();
let font = self.font.to_string();
let wrap = self.wrap;
let centered = self.centered;
let pos = self.position;
let size = self.size;
let colour = self.colour;
(name, text, font, wrap, centered, pos, size, colour)
}
pub fn _wrap_text(mut self, should_wrap: bool) -> TextField {
self.wrap = should_wrap;
self
}
pub fn name_matches(&self, name: &String) -> bool {
&self.name == name
}
pub fn _set_colour(&mut self, new_colour: Vector4<f32>) {
self.colour = new_colour;
}
pub fn _set_name(&mut self, new_name: &String) {
self.name = new_name.to_string();
}
pub fn update_text(&mut self, new_text: String) {
self.text = new_text;
}
pub fn _set_text_size(&mut self, new_size: Vector2<f32>) {
self.size = new_size;
}
pub fn get_location(&self) -> Vector2<f32> {
self.position
}
pub fn set_location(&mut self, new_location: Vector2<f32>) {
self.position = new_location;
}
pub fn get_text(&self) -> String {
self.text.clone()
}
pub fn _get_colour(&self) -> Vector4<f32> {
self.colour
}
pub fn _get_size(&self) -> f32 {
self.size.x
}
pub fn _get_name(&self) -> String {
self.name.to_string()
}
pub fn update(&mut self, _delta_time: f32, mouse_pos: Vector2<f32>, left_mouse: bool, keys_pressed_this_frame: &Vec<String>) {
if self.editable {
if self.editing {
for i in 0..keys_pressed_this_frame.len() {
if keys_pressed_this_frame[i] == "Backspace" {
self.text.pop();
} else if keys_pressed_this_frame[i] == "Enter" {
self.text = self.text.to_owned() + &"\n";
} else {
self.text = self.text.to_owned() + &keys_pressed_this_frame[i].to_string();
}
}
}
if left_mouse {
if self.is_touching(mouse_pos) {
self.editing = true;
} else {
self.editing = false;
}
}
}
}
pub fn draw(&self, draw_calls: &mut Vec<DrawCall>) {
let pos = self.position;
let _size = self.size;
let text = self.text.clone();
let font = self.font.clone();
let colour = self.colour;
let _wrap = self.wrap;
let size = self.size;
let _width = size.x*0.06*self.text.len() as f32;
let height = size.y*0.15;
let _center_x = self.position.x;
let _center_y = self.position.y+height*0.5;
// draw_calls.push(DrawCall::draw_coloured(Vector2::new(center_x,center_y), Vector2::new(width, height), Vector4::new(1.0, 1.0, 1.0, 1.0), 90.0));
if self.centered {
draw_calls.push(DrawCall::draw_text_basic_centered(pos, size, colour, text , font));
} else {
draw_calls.push(DrawCall::draw_text_basic(pos, size, colour, text , font));
}
}
}
| true |
18c93f66f4fe8997b3803b7f1ad0e9a5c1631b21
|
Rust
|
rust-lang/rust-installer
|
/src/generator.rs
|
UTF-8
| 6,039 | 2.515625 | 3 |
[
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] |
permissive
|
use super::Scripter;
use super::Tarballer;
use crate::compression::CompressionFormats;
use crate::util::*;
use anyhow::{bail, format_err, Context, Result};
use std::collections::BTreeSet;
use std::io::Write;
use std::path::Path;
actor! {
#[derive(Debug)]
pub struct Generator {
/// The name of the product, for display
#[clap(value_name = "NAME")]
product_name: String = "Product",
/// The name of the component, distinct from other installed components
#[clap(value_name = "NAME")]
component_name: String = "component",
/// The name of the package, tarball
#[clap(value_name = "NAME")]
package_name: String = "package",
/// The directory under lib/ where the manifest lives
#[clap(value_name = "DIR")]
rel_manifest_dir: String = "packagelib",
/// The string to print after successful installation
#[clap(value_name = "MESSAGE")]
success_message: String = "Installed.",
/// Places to look for legacy manifests to uninstall
#[clap(value_name = "DIRS")]
legacy_manifest_dirs: String = "",
/// Directory containing files that should not be installed
#[clap(value_name = "DIR")]
non_installed_overlay: String = "",
/// Path prefixes of directories that should be installed/uninstalled in bulk
#[clap(value_name = "DIRS")]
bulk_dirs: String = "",
/// The directory containing the installation medium
#[clap(value_name = "DIR")]
image_dir: String = "./install_image",
/// The directory to do temporary work
#[clap(value_name = "DIR")]
work_dir: String = "./workdir",
/// The location to put the final image and tarball
#[clap(value_name = "DIR")]
output_dir: String = "./dist",
/// The formats used to compress the tarball
#[clap(value_name = "FORMAT", default_value_t)]
compression_formats: CompressionFormats,
}
}
impl Generator {
/// Generates the actual installer tarball
pub fn run(self) -> Result<()> {
create_dir_all(&self.work_dir)?;
let package_dir = Path::new(&self.work_dir).join(&self.package_name);
if package_dir.exists() {
remove_dir_all(&package_dir)?;
}
// Copy the image and write the manifest
let component_dir = package_dir.join(&self.component_name);
create_dir_all(&component_dir)?;
copy_and_manifest(self.image_dir.as_ref(), &component_dir, &self.bulk_dirs)?;
// Write the component name
let components = package_dir.join("components");
writeln!(create_new_file(components)?, "{}", self.component_name)
.context("failed to write the component file")?;
// Write the installer version (only used by combine-installers.sh)
let version = package_dir.join("rust-installer-version");
writeln!(
create_new_file(version)?,
"{}",
crate::RUST_INSTALLER_VERSION
)
.context("failed to write new installer version")?;
// Copy the overlay
if !self.non_installed_overlay.is_empty() {
copy_recursive(self.non_installed_overlay.as_ref(), &package_dir)?;
}
// Generate the install script
let output_script = package_dir.join("install.sh");
let mut scripter = Scripter::default();
scripter
.product_name(self.product_name)
.rel_manifest_dir(self.rel_manifest_dir)
.success_message(self.success_message)
.legacy_manifest_dirs(self.legacy_manifest_dirs)
.output_script(path_to_str(&output_script)?.into());
scripter.run()?;
// Make the tarballs
create_dir_all(&self.output_dir)?;
let output = Path::new(&self.output_dir).join(&self.package_name);
let mut tarballer = Tarballer::default();
tarballer
.work_dir(self.work_dir)
.input(self.package_name)
.output(path_to_str(&output)?.into())
.compression_formats(self.compression_formats.clone());
tarballer.run()?;
Ok(())
}
}
/// Copies the `src` directory recursively to `dst`, writing `manifest.in` too.
fn copy_and_manifest(src: &Path, dst: &Path, bulk_dirs: &str) -> Result<()> {
let mut manifest = create_new_file(dst.join("manifest.in"))?;
let bulk_dirs: Vec<_> = bulk_dirs
.split(',')
.filter(|s| !s.is_empty())
.map(Path::new)
.collect();
let mut paths = BTreeSet::new();
copy_with_callback(src, dst, |path, file_type| {
// We need paths to be compatible with both Unix and Windows.
if path
.components()
.filter_map(|c| c.as_os_str().to_str())
.any(|s| s.contains('\\'))
{
bail!(
"rust-installer doesn't support '\\' in path components: {:?}",
path
);
}
// Normalize to Unix-style path separators.
let normalized_string;
let mut string = path.to_str().ok_or_else(|| {
format_err!(
"rust-installer doesn't support non-Unicode paths: {:?}",
path
)
})?;
if string.contains('\\') {
normalized_string = string.replace('\\', "/");
string = &normalized_string;
}
if file_type.is_dir() {
// Only manifest directories that are explicitly bulk.
if bulk_dirs.contains(&path) {
paths.insert(format!("dir:{}\n", string));
}
} else {
// Only manifest files that aren't under bulk directories.
if !bulk_dirs.iter().any(|d| path.starts_with(d)) {
paths.insert(format!("file:{}\n", string));
}
}
Ok(())
})?;
for path in paths {
manifest.write_all(path.as_bytes())?;
}
Ok(())
}
| true |
4d8fa0acc8a785ed6c0b03700e98f9a8fe435b29
|
Rust
|
gridbugs/advent-of-code-2019
|
/day4-2/src/main.rs
|
UTF-8
| 1,323 | 3.671875 | 4 |
[] |
no_license
|
struct DigitsReversed(u32);
impl Iterator for DigitsReversed {
type Item = u32;
fn next(&mut self) -> Option<Self::Item> {
if self.0 == 0 {
return None;
}
let digit = self.0 % 10;
self.0 /= 10;
Some(digit)
}
}
fn is_valid(password: u32) -> bool {
if password < 100000 || password >= 1000000 {
return false;
}
let mut adjacent_count = 0;
let mut adjacent_pair = false;
for (right, left) in DigitsReversed(password).zip(DigitsReversed(password / 10)) {
if right < left {
return false;
} else if left == right {
adjacent_count += 1;
} else {
if adjacent_count == 1 {
adjacent_pair = true;
}
adjacent_count = 0;
}
}
return adjacent_pair || adjacent_count == 1;
}
fn main() {
let num_valid = (183564..657474).filter(|&n| is_valid(n)).count();
println!("{}", num_valid);
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn examples() {
assert!(is_valid(111122));
assert!(is_valid(112222));
assert!(is_valid(112345));
assert!(is_valid(123345));
assert!(is_valid(112233));
assert!(!is_valid(111111));
assert!(!is_valid(123444));
}
}
| true |
7aca2156cdd3a789f64dd01d743211ce57f87151
|
Rust
|
CNife/leetcode
|
/rust/finished/src/flood_fill.rs
|
UTF-8
| 1,434 | 3.34375 | 3 |
[] |
no_license
|
use std::collections::VecDeque;
pub fn flood_fill(mut image: Vec<Vec<i32>>, sr: i32, sc: i32, new_color: i32) -> Vec<Vec<i32>> {
let (m, n) = (image.len(), image[0].len());
let (sr, sc) = (sr as usize, sc as usize);
let origin_color = image[sr][sc];
if origin_color == new_color {
return image;
}
let mut queue = VecDeque::new();
queue.push_back((sr, sc));
while !queue.is_empty() {
let (r, c) = queue.pop_front().unwrap();
image[r][c] = new_color;
macro_rules! next {
($predicate: expr, $r: expr, $c: expr) => {
if $predicate && image[$r][$c] == origin_color {
queue.push_back(($r, $c));
}
};
}
next!(r > 0, r - 1, c);
next!(r < m - 1, r + 1, c);
next!(c > 0, r, c - 1);
next!(c < n - 1, r, c + 1);
}
image
}
#[test]
fn test() {
let cases = vec![
(
vec![vec![1, 1, 1], vec![1, 1, 0], vec![1, 0, 1]],
1,
1,
2,
vec![vec![2, 2, 2], vec![2, 2, 0], vec![2, 0, 1]],
),
(
vec![vec![0, 0, 0], vec![0, 1, 1]],
1,
1,
1,
vec![vec![0, 0, 0], vec![0, 1, 1]],
),
];
for (image, sr, sc, new_color, expect) in cases {
assert_eq!(flood_fill(image, sr, sc, new_color), expect);
}
}
| true |
42739ad77818f6080b360556c7feab67cd2da218
|
Rust
|
Elabajaba/bevy-inspector-egui
|
/examples/rapier2d.rs
|
UTF-8
| 2,075 | 2.5625 | 3 |
[
"MIT"
] |
permissive
|
use bevy::prelude::*;
use bevy_inspector_egui::{widgets::InspectorQuery, InspectorPlugin};
use bevy_rapier2d::physics::{RapierConfiguration, RapierPhysicsPlugin, RigidBodyHandleComponent};
use bevy_rapier2d::rapier::dynamics::RigidBodyBuilder;
use bevy_rapier2d::rapier::geometry::ColliderBuilder;
use bevy_rapier2d::rapier::na::Vector2;
fn main() {
App::build()
.add_plugins(DefaultPlugins)
.add_plugin(InspectorPlugin::<
InspectorQuery<&'static mut RigidBodyHandleComponent>,
>::new())
.add_plugin(RapierPhysicsPlugin)
.add_startup_system(spawn_player.system())
.run();
}
// The float value is the player movemnt speed in 'pixels/second'.
struct Player(f32);
fn spawn_player(
mut commands: Commands,
mut materials: ResMut<Assets<ColorMaterial>>,
mut rapier_config: ResMut<RapierConfiguration>,
) {
// Set gravity to 0.0 and spawn camera.
rapier_config.gravity = Vector2::zeros();
commands
.spawn()
.insert_bundle(OrthographicCameraBundle::new_2d());
let sprite_size_x = 40.0;
let sprite_size_y = 40.0;
// While we want our sprite to look ~40 px square, we want to keep the physics units smaller
// to prevent float rounding problems. To do this, we set the scale factor in RapierConfiguration
// and divide our sprite_size by the scale.
rapier_config.scale = 20.0;
let collider_size_x = sprite_size_x / rapier_config.scale;
let collider_size_y = sprite_size_y / rapier_config.scale;
// Spawn entity with `Player` struct as a component for access in movement query.
commands
.spawn()
.insert_bundle(SpriteBundle {
material: materials.add(Color::rgb(0.0, 0.0, 0.0).into()),
sprite: Sprite::new(Vec2::new(sprite_size_x, sprite_size_y)),
..Default::default()
})
.insert(RigidBodyBuilder::new_dynamic())
.insert(ColliderBuilder::cuboid(
collider_size_x / 2.0,
collider_size_y / 2.0,
))
.insert(Player(300.0));
}
| true |
024b5137a51e88f8f9d91e0b3492aa9c706f4e42
|
Rust
|
hydro-project/hydroflow
|
/hydroflow_lang/src/union_find.rs
|
UTF-8
| 2,137 | 3.59375 | 4 |
[
"Apache-2.0"
] |
permissive
|
//! Union-find data structure, see [`UnionFind`].
use slotmap::{Key, SecondaryMap};
/// Union-find data structure.
///
/// Used to efficiently track sets of equivalent items.
///
/// <https://en.wikipedia.org/wiki/Disjoint-set_data_structure>
#[derive(Default, Clone)]
pub struct UnionFind<K>
where
K: Key,
{
links: SecondaryMap<K, K>,
}
impl<K> UnionFind<K>
where
K: Key,
{
/// Creates a new `UnionFind`, same as [`Default::default()`].
#[allow(dead_code)]
pub fn new() -> Self {
Self::default()
}
/// Creates a new `UnionFind` with the given key capacity pre-allocated.
pub fn with_capacity(capacity: usize) -> Self {
Self {
links: SecondaryMap::with_capacity(capacity),
}
}
/// Combines two items `a` and `b` as equivalent, in the same set.
pub fn union(&mut self, a: K, b: K) {
let i = self.find(a);
let j = self.find(b);
if i == j {
return;
}
self.links[i] = j;
}
/// Finds the "representative" item for `k`. Each set of equivalent items is represented by one
/// of its member items.
pub fn find(&mut self, k: K) -> K {
if let Some(next) = self.links.insert(k, k) {
if k == next {
return k;
}
self.links[k] = self.find(next);
}
self.links[k]
}
/// Returns if `a` and `b` are equivalent, i.e. in the same set.
pub fn same_set(&mut self, a: K, b: K) -> bool {
self.find(a) == self.find(b)
}
}
#[cfg(test)]
mod test {
use slotmap::SlotMap;
use super::*;
#[test]
fn test_basic() {
let mut sm = SlotMap::new();
let a = sm.insert(());
let b = sm.insert(());
let c = sm.insert(());
let d = sm.insert(());
let mut uf = UnionFind::new();
assert!(!uf.same_set(a, b));
uf.union(a, b);
assert!(uf.same_set(a, b));
uf.union(c, a);
assert!(uf.same_set(b, c));
assert!(!uf.same_set(a, d));
assert!(!uf.same_set(b, d));
assert!(!uf.same_set(d, c));
}
}
| true |
cbe915a04fece8de3798a306e79cba2486d6ddd3
|
Rust
|
splashofcrimson/Advent-Of-Code
|
/src/day03.rs
|
UTF-8
| 4,050 | 3.203125 | 3 |
[] |
no_license
|
use std::fs::File;
use std::io::{prelude::*, BufReader};
use std::collections::{HashSet, HashMap};
struct Claim {
id: i32,
x: i32,
y: i32,
width: i32,
height: i32,
}
fn read_from_file() -> Vec<String> {
let buf = BufReader::new(File::open("input/day03.txt").unwrap());
buf.lines()
.map(|l| l.unwrap())
.collect()
}
pub fn five() {
let mut split_claim: Vec<String>;
let mut coordinates: Vec<String>;
let mut bounds: Vec<String>;
let mut claims = HashMap::new();
let mut square_inches : i32 = 0;
let buf = read_from_file();
for claim in &buf {
split_claim = claim.split(" ")
.map(|s| s.to_string())
.collect();
coordinates = split_claim[2 as usize].split(",")
.map(|s| s.to_string())
.collect();
bounds = split_claim[3 as usize].split("x")
.map(|s| s.to_string())
.collect();
let c = Claim {
id: split_claim[0 as usize].clone().trim_matches('#').parse().unwrap(),
x: coordinates[0 as usize].clone().parse().unwrap(),
y: coordinates[1 as usize].clone().trim_matches(':').parse().unwrap(),
width: bounds[0 as usize].clone().parse().unwrap(),
height: bounds[1 as usize].clone().parse().unwrap(),
};
for x in (c.x+1)..=(c.x+c.width) {
for y in (c.y+1)..=(c.y+c.height) {
let coordinate = (x, y);
if !claims.contains_key(&coordinate) {
claims.insert(coordinate, 1);
}
else {
match claims.get(&coordinate) {
Some(&count) => {
if count == 1 {
claims.insert(coordinate, 2);
square_inches += 1;
}
},
_ => println!("ERROR"),
}
}
}
}
}
// println!("{}", square_inches);
}
pub fn six() {
let mut split_claim: Vec<String>;
let mut coordinates: Vec<String>;
let mut bounds: Vec<String>;
let mut claims = HashMap::new();
let mut claim_ids = HashSet::new();
let mut flag_id = 0;
let buf = read_from_file();
for claim in &buf {
split_claim = claim.split(" ")
.map(|s| s.to_string())
.collect();
coordinates = split_claim[2 as usize].split(",")
.map(|s| s.to_string())
.collect();
bounds = split_claim[3 as usize].split("x")
.map(|s| s.to_string())
.collect();
let c = Claim {
id: split_claim[0 as usize].clone().trim_matches('#').parse().unwrap(),
x: coordinates[0 as usize].clone().parse().unwrap(),
y: coordinates[1 as usize].clone().trim_matches(':').parse().unwrap(),
width: bounds[0 as usize].clone().parse().unwrap(),
height: bounds[1 as usize].clone().parse().unwrap(),
};
for x in (c.x+1)..=(c.x+c.width) {
for y in (c.y+1)..=(c.y+c.height) {
let coordinate = (x, y);
if !claims.contains_key(&coordinate) {
claims.insert(coordinate, c.id);
claim_ids.insert(c.id);
}
else {
match claims.get(&coordinate) {
Some(&id) => {
flag_id = id;
if claim_ids.contains(&flag_id) {
claim_ids.remove(&flag_id);
}
},
_ => println!("ERROR"),
}
}
}
}
if flag_id != 0 {
if claim_ids.contains(&c.id) {
claim_ids.remove(&c.id);
}
}
flag_id = 0;
}
println!("{:?}", claim_ids);
}
| true |
2f7568af283cca5746514df6305cc4916608533a
|
Rust
|
C-Saunders/advent-of-code-2018
|
/problem04/src/parser.rs
|
UTF-8
| 2,971 | 3.359375 | 3 |
[] |
no_license
|
use regex::Regex;
use std::result::Result;
pub enum LineType {
NewGuard,
FallAsleep,
WakeUp,
}
pub fn get_line_data(line: &str) -> Result<(usize, LineType), String> {
if let Some(id) = get_guard_id(line) {
return Ok((id, LineType::NewGuard));
}
if let Some(min) = get_fall_asleep_minute(line) {
return Ok((min, LineType::FallAsleep));
}
if let Some(min) = get_wake_up_minute(line) {
return Ok((min, LineType::WakeUp));
}
Err("Unable to parse line".to_owned())
}
const DATE_SECTION: &'static str =
r"^\[(?P<date>\d{4}-\d{2}-\d{2}) (?P<hour>\d{2}):(?P<minute>\d{2})\]";
fn get_guard_id(line: &str) -> Option<usize> {
lazy_static! {
static ref PARSE_EXPR: Regex =
Regex::new(&(DATE_SECTION.clone().to_owned() + r" Guard #(?P<id>\d+) begins shift$"))
.unwrap();
}
PARSE_EXPR.captures(line).map(|caps| caps["id"].parse::<usize>().unwrap())
}
fn get_fall_asleep_minute(line: &str) -> Option<usize> {
lazy_static! {
static ref PARSE_EXPR: Regex =
Regex::new(&(DATE_SECTION.clone().to_owned() + r" falls asleep$")).unwrap();
}
PARSE_EXPR.captures(line).map(|caps| caps["minute"].parse::<usize>().unwrap())
}
fn get_wake_up_minute(line: &str) -> Option<usize> {
lazy_static! {
static ref PARSE_EXPR: Regex =
Regex::new(&(DATE_SECTION.clone().to_owned() + r" wakes up$")).unwrap();
}
PARSE_EXPR.captures(line).map(|caps| caps["minute"].parse::<usize>().unwrap())
}
#[cfg(test)]
mod get_guard_id_tests {
use super::get_guard_id;
#[test]
fn has_guard_id() {
assert_eq!(
get_guard_id("[1518-11-01 00:00] Guard #10 begins shift"),
Some(10)
);
}
#[test]
fn no_guard_id() {
assert_eq!(get_guard_id("[1518-11-01 00:05] falls asleep"), None);
assert_eq!(get_guard_id("[1518-11-01 00:25] wakes up"), None);
}
}
#[cfg(test)]
mod get_fall_asleep_minute_tests {
use super::get_fall_asleep_minute;
#[test]
fn has_fall_asleep_minute() {
assert_eq!(
get_fall_asleep_minute("[1518-11-01 00:05] falls asleep"),
Some(5)
);
}
#[test]
fn no_fall_asleep_minute() {
assert_eq!(
get_fall_asleep_minute("[1518-11-01 00:00] Guard #10 begins shift"),
None
);
assert_eq!(get_fall_asleep_minute("[1518-11-01 00:25] wakes up"), None);
}
}
#[cfg(test)]
mod get_wake_up_minute_tests {
use super::get_wake_up_minute;
#[test]
fn has_fall_asleep_minute() {
assert_eq!(get_wake_up_minute("[1518-11-01 00:25] wakes up"), Some(25));
}
#[test]
fn no_fall_asleep_minute() {
assert_eq!(
get_wake_up_minute("[1518-11-01 00:00] Guard #10 begins shift"),
None
);
assert_eq!(get_wake_up_minute("[1518-11-01 00:05] falls asleep"), None);
}
}
| true |
886044b151d2f82a58aee78ada53dfd072c69c3d
|
Rust
|
hamadakafu/rsTFHE
|
/src/trgsw/tests.rs
|
UTF-8
| 2,475 | 2.59375 | 3 |
[
"Apache-2.0"
] |
permissive
|
use quickcheck_macros::quickcheck;
use std::num::Wrapping;
use super::*;
use crate::params;
use crate::torus::Torus01Poly;
/// decompositionを完璧に戻すことができるのか?
/// -> できない bgで小さい値は丸められている
#[quickcheck]
fn test_decomposition(fixes: Vec<Wrapping<u32>>) -> bool {
if fixes.len() == 0 {
return true;
}
let N = params::N;
let l = 3;
let bg = 64;
let bgbit = 6;
let fixes: Vec<Wrapping<u32>> = fixes.into_iter().cycle().take(N).collect();
let poly = Torus01Poly::new_with_fix(fixes);
let decomp = decomposition(l, bg, bgbit, &poly);
let h: Vec<Torus01Poly> = (1..l + 1)
.map(|i| {
let mut coef = vec![Wrapping(0); N];
coef[0] = Wrapping(1 << (32 - bgbit * i));
Torus01Poly::new_with_fix(coef)
})
.collect();
let mut acc = Torus01Poly::new_with_fix(vec![Wrapping(0); N]);
for (dd, hh) in decomp.iter().zip(h.iter()) {
acc = &acc + &(hh * dd);
}
// if poly != acc {
// dbg!(&poly, &acc);
// }
for (real, expect) in acc.coef.iter().zip(poly.coef.iter()) {
if real > expect {
assert!((*real - *expect).fix.0 < (1 << (32 - bgbit * l)));
} else {
assert!((*expect - *real).fix.0 < (1 << (32 - bgbit * l)));
}
}
return true;
}
#[quickcheck]
fn test_cmux(mut m: u8) -> bool {
m %= 2;
let l = params::l;
let bg = params::bg;
let bgbit = params::bgbit;
let N = 4;
use crate::trlwe;
let s = trlwe::gen_s(N);
let mut errors = torus::Torus01Poly::new_with_fix(vec![Wrapping(0); N]);
let zeros = (0..l * 2)
.map(|_| {
let m = vec![0; N];
let (c, e) = trlwe::encrypt_torus(m, &s);
errors = &errors + &e;
c
})
.collect();
let trgsw = TRGSW::new_with_bin(l, bg as u32, bgbit, m, zeros);
// 定数項が0のTRLWE
let d_0 = {
let m = vec![0; N];
let (c, e) = trlwe::encrypt_bin(m, &s);
c
};
assert_eq!(trlwe::decrypt_bin(d_0.clone(), &s)[0], 0);
// 定数項が1のTRLWE
let d_1 = {
let mut m = vec![0; N];
m[0] = 1;
let (c, e) = trlwe::encrypt_bin(m, &s);
c
};
assert_eq!(trlwe::decrypt_bin(d_1.clone(), &s)[0], 1);
let c_trlwe = trgsw.cmux(d_0, d_1);
let m_hats = trlwe::decrypt_bin(c_trlwe, &s);
m == m_hats[0]
}
| true |
ee1a08bcb8948cf8833e8b28a06aa4cb5b6b10f9
|
Rust
|
alamminsalo/radio
|
/src/main.rs
|
UTF-8
| 2,175 | 3.015625 | 3 |
[] |
no_license
|
extern crate notify_rust;
extern crate chrono;
extern crate rand;
use std::env;
use std::fs;
use rand::{thread_rng, Rng};
mod audiostream;
fn random_file(dir: &str) -> Option<String> {
let paths = fs::read_dir(dir).unwrap();
let mut files: Vec<String> = vec![];
for path in paths {
files.push(String::from(path.unwrap().path().to_str().unwrap()));
}
if files.len() <= 0 {
return None;
}
let idx = thread_rng().gen_range(0, files.len());
Some(files.get(idx).unwrap().clone())
}
fn current_timestamp() -> String {
chrono::Local::now().format("[%H:%M:%S]").to_string()
}
fn notify(title: &str, icon: Option<String>) {
println!("{} {}\n", current_timestamp(), title);
let notify = notify_rust::Notification::new()
.summary("Now playing")
.body(title)
.icon(&icon.unwrap_or(String::new()))
.show();
}
fn main() {
let args: Vec<String> = env::args().collect();
if args.len() < 2 {
panic!("No argument");
}
let mut uri: Option<String> = None;
let mut icondir: Option<String> = None;
let mut icon: Option<String> = None;
//Parse args
let mut iter = args.into_iter().peekable();
while let Some(arg) = iter.next() {
if arg == "--icondir" {
icondir = Some(iter.next().unwrap().clone());
}
else if arg == "--icon" {
icon = Some(iter.next().unwrap().clone());
}
else if iter.peek() == None {
uri = Some(arg);
}
}
if uri == None {
panic!("No uri supplied!");
}
//Closure callback
let callback = |title: &str| {
let mut iconOpt: Option<String> = None;
if icon != None {
iconOpt = Some(icon.iter().next().unwrap().clone());
}
else if icondir != None {
iconOpt = random_file(&icondir.iter().next().unwrap());
}
notify(title, iconOpt);
};
//Clear term screen
let output = std::process::Command::new("clear").output().unwrap();
print!("{}", String::from_utf8_lossy(&output.stdout));
audiostream::open(&uri.unwrap(), &callback);
}
| true |
04b4fa1bd87437b08aa7a89fe619cf62e0c214da
|
Rust
|
loiclec/fuzzcheck-rs
|
/fuzzcheck/src/mutators/map.rs
|
UTF-8
| 11,022 | 3.046875 | 3 |
[
"MIT"
] |
permissive
|
use std::any::Any;
use std::marker::PhantomData;
use crate::Mutator;
/// [`MapMutator`] provides a way to transform a mutator outputting values of
/// type `From` into a mutator outputting values of type `To`, provided that a
/// mutator for values of type `To` exists, and it is possible to convert from
/// `From` to `To`.
///
/// If you are trying to _add_ additional information to a type (for example, if
/// you were transforming a type `T` to `(T, CtxDerivedFromT)`) then you should
/// use [`AndMapMutator`], which is more efficient for this usecase.
pub struct MapMutator<From, To, M, Parse, Map, Cplx>
where
From: Clone + 'static,
To: Clone + 'static,
M: Mutator<From>,
Parse: Fn(&To) -> Option<From>,
Map: Fn(&From) -> To,
Cplx: Fn(&To, f64) -> f64,
{
pub mutator: M,
pub parse: Parse,
pub map: Map,
pub cplx: Cplx,
_phantom: PhantomData<(To, From)>,
}
impl<From, To, M, Parse, Map, Cplx> MapMutator<From, To, M, Parse, Map, Cplx>
where
From: Clone + 'static,
To: Clone + 'static,
M: Mutator<From>,
Parse: Fn(&To) -> Option<From>,
Map: Fn(&From) -> To,
Cplx: Fn(&To, f64) -> f64,
{
#[no_coverage]
pub fn new(mutator: M, parse: Parse, map: Map, cplx: Cplx) -> Self {
Self {
mutator,
parse,
map,
cplx,
_phantom: PhantomData,
}
}
}
pub struct Cache<From, M>
where
From: Clone + 'static,
M: Mutator<From>,
{
from_value: From,
from_cache: M::Cache,
}
impl<From, M> Clone for Cache<From, M>
where
From: Clone + 'static,
M: Mutator<From>,
{
#[no_coverage]
fn clone(&self) -> Self {
Self {
from_value: self.from_value.clone(),
from_cache: self.from_cache.clone(),
}
}
}
impl<From, To, M, Parse, Map, Cplx> Mutator<To> for MapMutator<From, To, M, Parse, Map, Cplx>
where
From: Clone + 'static,
To: Clone + 'static,
M: Mutator<From>,
Parse: Fn(&To) -> Option<From>,
Map: Fn(&From) -> To,
Cplx: Fn(&To, f64) -> f64,
Self: 'static,
{
#[doc(hidden)]
type Cache = Cache<From, M>;
#[doc(hidden)]
type MutationStep = M::MutationStep;
#[doc(hidden)]
type ArbitraryStep = M::ArbitraryStep;
#[doc(hidden)]
type UnmutateToken = M::UnmutateToken;
#[doc(hidden)]
#[no_coverage]
fn initialize(&self) {
self.mutator.initialize();
}
#[doc(hidden)]
#[no_coverage]
fn default_arbitrary_step(&self) -> Self::ArbitraryStep {
self.mutator.default_arbitrary_step()
}
#[doc(hidden)]
#[no_coverage]
fn is_valid(&self, value: &To) -> bool {
if let Some(from_value) = (self.parse)(value) {
self.mutator.is_valid(&from_value)
} else {
false
}
}
#[doc(hidden)]
#[no_coverage]
fn validate_value(&self, to_value: &To) -> Option<Self::Cache> {
let from_value = (self.parse)(to_value)?;
let from_cache = self.mutator.validate_value(&from_value)?;
Some(Cache { from_value, from_cache })
}
#[doc(hidden)]
#[no_coverage]
fn default_mutation_step(&self, _value: &To, cache: &Self::Cache) -> Self::MutationStep {
self.mutator.default_mutation_step(&cache.from_value, &cache.from_cache)
}
#[doc(hidden)]
#[no_coverage]
fn global_search_space_complexity(&self) -> f64 {
self.mutator.global_search_space_complexity()
}
#[doc(hidden)]
#[no_coverage]
fn max_complexity(&self) -> f64 {
self.mutator.max_complexity()
}
#[doc(hidden)]
#[no_coverage]
fn min_complexity(&self) -> f64 {
self.mutator.min_complexity()
}
#[doc(hidden)]
#[no_coverage]
fn complexity(&self, value: &To, cache: &Self::Cache) -> f64 {
let orig_cplx = self.mutator.complexity(&cache.from_value, &cache.from_cache);
(self.cplx)(value, orig_cplx)
}
#[doc(hidden)]
#[no_coverage]
fn ordered_arbitrary(&self, step: &mut Self::ArbitraryStep, max_cplx: f64) -> Option<(To, f64)> {
let (from_value, orig_cplx) = self.mutator.ordered_arbitrary(step, max_cplx)?;
let to_value = (self.map)(&from_value);
let cplx = (self.cplx)(&to_value, orig_cplx);
Some((to_value, cplx))
}
#[doc(hidden)]
#[no_coverage]
fn random_arbitrary(&self, max_cplx: f64) -> (To, f64) {
let (from_value, orig_cplx) = self.mutator.random_arbitrary(max_cplx);
let to_value = (self.map)(&from_value);
let cplx = (self.cplx)(&to_value, orig_cplx);
(to_value, cplx)
}
#[doc(hidden)]
#[no_coverage]
fn ordered_mutate(
&self,
value: &mut To,
cache: &mut Self::Cache,
step: &mut Self::MutationStep,
subvalue_provider: &dyn crate::SubValueProvider,
max_cplx: f64,
) -> Option<(Self::UnmutateToken, f64)> {
let (token, orig_cplx) = self.mutator.ordered_mutate(
&mut cache.from_value,
&mut cache.from_cache,
step,
subvalue_provider,
max_cplx,
)?;
*value = (self.map)(&cache.from_value);
Some((token, (self.cplx)(value, orig_cplx)))
}
#[doc(hidden)]
#[no_coverage]
fn random_mutate(&self, value: &mut To, cache: &mut Self::Cache, max_cplx: f64) -> (Self::UnmutateToken, f64) {
let (token, orig_cplx) = self
.mutator
.random_mutate(&mut cache.from_value, &mut cache.from_cache, max_cplx);
*value = (self.map)(&cache.from_value);
(token, (self.cplx)(value, orig_cplx))
}
#[doc(hidden)]
#[no_coverage]
fn unmutate(&self, value: &mut To, cache: &mut Self::Cache, t: Self::UnmutateToken) {
self.mutator.unmutate(&mut cache.from_value, &mut cache.from_cache, t);
*value = (self.map)(&cache.from_value);
}
#[doc(hidden)]
#[no_coverage]
fn visit_subvalues<'a>(&self, _value: &'a To, cache: &'a Self::Cache, visit: &mut dyn FnMut(&'a dyn Any, f64)) {
self.mutator
.visit_subvalues(&cache.from_value, &cache.from_cache, visit)
}
}
pub struct AndMapMutator<From, To, M, Map>
where
From: Clone + 'static,
To: Clone + 'static,
M: Mutator<From>,
Map: Fn(&From, &mut To),
{
pub mutator: M,
pub map: Map,
storage_to: To,
_phantom: PhantomData<(To, From)>,
}
impl<From, To, M, Map> AndMapMutator<From, To, M, Map>
where
From: Clone + 'static,
To: Clone + 'static,
M: Mutator<From>,
Map: Fn(&From, &mut To),
{
#[no_coverage]
pub fn new(mutator: M, map: Map, storage: To) -> Self {
Self {
mutator,
map,
storage_to: storage,
_phantom: PhantomData,
}
}
}
impl<From, To, M, Map> Mutator<(To, From)> for AndMapMutator<From, To, M, Map>
where
From: Clone + 'static,
To: Clone + 'static,
M: Mutator<From>,
Map: Fn(&From, &mut To),
Self: 'static,
{
#[doc(hidden)]
type Cache = M::Cache;
#[doc(hidden)]
type MutationStep = M::MutationStep;
#[doc(hidden)]
type ArbitraryStep = M::ArbitraryStep;
#[doc(hidden)]
type UnmutateToken = M::UnmutateToken;
#[doc(hidden)]
#[no_coverage]
fn initialize(&self) {
self.mutator.initialize();
}
#[doc(hidden)]
#[no_coverage]
fn default_arbitrary_step(&self) -> Self::ArbitraryStep {
self.mutator.default_arbitrary_step()
}
#[doc(hidden)]
#[no_coverage]
fn is_valid(&self, value: &(To, From)) -> bool {
self.mutator.is_valid(&value.1)
}
#[doc(hidden)]
#[no_coverage]
fn validate_value(&self, value: &(To, From)) -> Option<Self::Cache> {
let (_, from_value) = value;
let from_cache = self.mutator.validate_value(from_value)?;
Some(from_cache)
}
#[doc(hidden)]
#[no_coverage]
fn default_mutation_step(&self, value: &(To, From), cache: &Self::Cache) -> Self::MutationStep {
let (_, from_value) = value;
self.mutator.default_mutation_step(from_value, cache)
}
#[doc(hidden)]
#[no_coverage]
fn global_search_space_complexity(&self) -> f64 {
self.mutator.global_search_space_complexity()
}
#[doc(hidden)]
#[no_coverage]
fn max_complexity(&self) -> f64 {
self.mutator.max_complexity()
}
#[doc(hidden)]
#[no_coverage]
fn min_complexity(&self) -> f64 {
self.mutator.min_complexity()
}
#[doc(hidden)]
#[no_coverage]
fn complexity(&self, value: &(To, From), cache: &Self::Cache) -> f64 {
let (_, from_value) = value;
self.mutator.complexity(from_value, cache)
}
#[doc(hidden)]
#[no_coverage]
fn ordered_arbitrary(&self, step: &mut Self::ArbitraryStep, max_cplx: f64) -> Option<((To, From), f64)> {
let (from_value, cplx) = self.mutator.ordered_arbitrary(step, max_cplx)?;
let mut to_value = self.storage_to.clone();
(self.map)(&from_value, &mut to_value);
Some(((to_value, from_value), cplx))
}
#[doc(hidden)]
#[no_coverage]
fn random_arbitrary(&self, max_cplx: f64) -> ((To, From), f64) {
let (from_value, cplx) = self.mutator.random_arbitrary(max_cplx);
let mut to_value = self.storage_to.clone();
(self.map)(&from_value, &mut to_value);
((to_value, from_value), cplx)
}
#[doc(hidden)]
#[no_coverage]
fn ordered_mutate(
&self,
value: &mut (To, From),
cache: &mut Self::Cache,
step: &mut Self::MutationStep,
subvalue_provider: &dyn crate::SubValueProvider,
max_cplx: f64,
) -> Option<(Self::UnmutateToken, f64)> {
let (to_value, from_value) = value;
let (token, cplx) = self
.mutator
.ordered_mutate(from_value, cache, step, subvalue_provider, max_cplx)?;
(self.map)(from_value, to_value);
Some((token, cplx))
}
#[doc(hidden)]
#[no_coverage]
fn random_mutate(
&self,
value: &mut (To, From),
cache: &mut Self::Cache,
max_cplx: f64,
) -> (Self::UnmutateToken, f64) {
let (to_value, from_value) = value;
let (token, cplx) = self.mutator.random_mutate(from_value, cache, max_cplx);
(self.map)(from_value, to_value);
(token, cplx)
}
#[doc(hidden)]
#[no_coverage]
fn unmutate(&self, value: &mut (To, From), cache: &mut Self::Cache, t: Self::UnmutateToken) {
let (to_value, from_value) = value;
self.mutator.unmutate(from_value, cache, t);
(self.map)(from_value, to_value);
}
#[doc(hidden)]
#[no_coverage]
fn visit_subvalues<'a>(
&self,
value: &'a (To, From),
cache: &'a Self::Cache,
visit: &mut dyn FnMut(&'a dyn Any, f64),
) {
let (_, from_value) = value;
self.mutator.visit_subvalues(from_value, cache, visit)
}
}
| true |
2b694e8f85c61f3f2944df12d6f359dcd74237c9
|
Rust
|
Ryan1729/rote
|
/libs/text_buffer/src/test_macros.rs
|
UTF-8
| 3,943 | 2.59375 | 3 |
[
"Apache-2.0",
"MIT"
] |
permissive
|
use super::*;
use macros::fmt_debug;
#[macro_export]
macro_rules! r {
($s:expr) => {
Rope::from_str(&$s)
};
}
#[macro_export]
macro_rules! c_r {
($s:expr) => {
CursoredRope::from(Rope::from_str(&$s))
};
}
#[macro_export]
macro_rules! t_b {
($s:expr) => {{
let t: TextBuffer = $s.into();
t
}};
($s:expr, $cursors: expr) => {{
let mut t: TextBuffer = $s.into();
t.set_cursors_from_vec1($cursors);
t
}};
}
#[macro_export]
macro_rules! cursor_assert {
(
$buffer:expr
$(, p: $pos: expr)?
$(, h: $highlight_position: expr)?
$(, s: $state: pat)?
$(,)?) => {{
let c = $buffer.borrow_cursors().first();
$(
assert_eq!(c.get_position(), $pos, "positions do not match");
)*
$(
assert_eq!(
c.get_highlight_position(),
$highlight_position.into(),
"highlight positions do not match"
);
)*
$(
match c.state {
$state => {},
_ => panic!("{:?} does not match {}", c.state, stringify!($state))
}
)*
}};
}
pub struct IgnoringStateSingle<'cursor>(pub &'cursor Cursor);
fmt_debug!(<'a> for IgnoringStateSingle<'a>:
IgnoringStateSingle(cursor) in
"{{ position: {:?}, highlight_position: {:?}, sticky_offset: {:?} }}",
cursor.get_position(), cursor.get_highlight_position(), cursor.sticky_offset
);
impl<'a, 'b> PartialEq<IgnoringStateSingle<'b>> for IgnoringStateSingle<'a> {
fn eq(&self, other: &IgnoringStateSingle<'b>) -> bool {
self.0.get_position() == other.0.get_position()
&& self.0.get_highlight_position() == other.0.get_highlight_position()
&& self.0.sticky_offset == other.0.sticky_offset
}
}
pub struct IgnoringState<'cursors>(pub &'cursors Cursors);
fmt_debug!(<'a> for IgnoringState<'a>:
IgnoringState(cursors) in "{:?}", cursors.iter().map(IgnoringStateSingle).collect::<Vec<_>>()
);
impl<'a, 'b> PartialEq<IgnoringState<'b>> for IgnoringState<'a> {
fn eq(&self, other: &IgnoringState<'b>) -> bool {
self.0.iter().map(IgnoringStateSingle).collect::<Vec<_>>()
== other.0.iter().map(IgnoringStateSingle).collect::<Vec<_>>()
}
}
pub struct IgnoringHistory<'buffer>(pub &'buffer TextBuffer);
fmt_debug!(<'a> for IgnoringHistory<'a>:
IgnoringHistory(b) in "{{ rope: {:?}, cursors: {:?} }}", b.borrow_rope(), IgnoringState(b.borrow_cursors())
);
impl<'a, 'b> PartialEq<IgnoringHistory<'b>> for IgnoringHistory<'a> {
fn eq(&self, other: &IgnoringHistory<'b>) -> bool {
self.0.borrow_rope() == other.0.borrow_rope()
&& IgnoringState(self.0.borrow_cursors()) == IgnoringState(other.0.borrow_cursors())
}
}
#[macro_export]
macro_rules! assert_text_buffer_eq_ignoring_history {
($left:expr, $right:expr) => {
assert_eq!(
$crate::test_macros::IgnoringHistory(&$left),
$crate::test_macros::IgnoringHistory(&$right),
stringify!($left != $right (ignoring history))
);
};
}
#[macro_export]
macro_rules! text_buffer_eq_ignoring_history {
($left:expr, $right:expr) => {
$crate::test_macros::IgnoringHistory(&$left)
== $crate::test_macros::IgnoringHistory(&$right)
};
}
#[macro_export]
macro_rules! assert_text_buffer_rope_eq {
($left:expr, $right:expr) => {
assert_eq!(
$left.borrow_rope(),
$right.borrow_rope(),
stringify!($left != $right (ignoring everything but the rope))
);
};
}
#[macro_export]
macro_rules! text_buffer_rope_eq {
($left:expr, $right:expr) => {
$left.rope == $right.rope
};
}
| true |
16387eaf71b36a86c2f70eaaf113feddfc4a3cad
|
Rust
|
stereobooster/emcache
|
/src/storage/tests.rs
|
UTF-8
| 12,747 | 3.140625 | 3 |
[
"MIT"
] |
permissive
|
use platform::time::sleep_secs;
use platform::time::time_now;
use super::Cache;
use super::CacheError;
use super::Key;
use super::Value;
#[test]
fn test_cas_id() {
let mut value = value!(1);
assert_eq!(0, *value.get_cas_id());
value.set_item(vec![2]);
assert_eq!(1, *value.get_cas_id());
value.set_flags(15);
assert_eq!(2, *value.get_cas_id());
value.set_exptime(0.0);
assert_eq!(3, *value.get_cas_id());
// Touch is never due to a client changing it, just us
value.touch();
assert_eq!(3, *value.get_cas_id());
}
#[test]
fn test_set_one_key() {
let mut cache = Cache::new(1024);
let key = key!(1, 2, 3);
let mut value = value!(4, 5, 6);
value.set_flags(15);
// First set it
let rv = cache.set(key.clone(), value.clone());
assert!(rv.is_ok());
// Then test for it
let rv = cache.contains_key(&key);
assert_eq!(rv.unwrap(), true);
// Check the size of the cache
assert_eq!(1, cache.len());
// Test for a key that was not set
let rv = cache.contains_key(&key!(9, 8));
assert_eq!(rv.unwrap(), false);
// Now fetch it
{
let value_found = cache.get(&key).unwrap();
assert_eq!(value, *value_found);
}
// Now remove it
let value_popped = cache.remove(&key).unwrap();
assert_eq!(value, value_popped);
// Now test for it
let rv = cache.contains_key(&key);
assert_eq!(rv.unwrap(), false);
// Check the size of the cache
assert_eq!(0, cache.len());
}
#[test]
fn test_key_not_found() {
let mut cache = Cache::new(1024);
// Set a key
let rv = cache.set(key!(1), value!(9));
assert!(rv.is_ok());
// Retrieve a different key
let rv = cache.get(&key!(2));
assert_eq!(rv.unwrap_err(), CacheError::KeyNotFound);
}
#[test]
fn test_store_beyond_capacity_lru() {
let item_size = key!(1).mem_size() as u64 + value!(1).mem_size() as u64;
let mut cache = Cache::new(item_size);
// we've now reached capacity
let rv = cache.set(key!(1), value!(8));
assert!(rv.is_ok());
assert_eq!(cache.len(), 1);
// write another key
let rv = cache.set(key!(2), value!(9));
assert!(rv.is_ok());
assert_eq!(cache.len(), 1);
// the first key is gone
{
let rv = cache.contains_key(&key!(1));
assert_eq!(rv.unwrap(), false);
}
{
let rv = cache.get(&key!(1));
assert!(rv.is_err());
}
// the second key is present
{
let rv = cache.contains_key(&key!(2));
assert_eq!(rv.unwrap(), true);
}
{
let rv = cache.get(&key!(2));
assert!(rv.is_ok());
}
// try to set an item that's bigger than the whole cache
let rv = cache.set(key!(2, 3), value!(9, 10, 11));
assert!(rv.is_err());
assert_eq!(cache.len(), 1);
// make sure the previous set attempt didn't evict anything
let rv = cache.contains_key(&key!(2));
assert_eq!(rv.unwrap(), true);
}
#[test]
fn test_multiple_evictions() {
// Get a cache just big enough to store two items with short key/val
let item_size = key!(1).mem_size() as u64 + value!(1).mem_size() as u64;
let mut cache = Cache::new(item_size * 2);
// Set a key
let rv = cache.set(key!(1), value!(8));
assert!(rv.is_ok());
assert_eq!(cache.len(), 1);
assert_eq!(cache.get_stats().evictions, 0);
// Set another key
let rv = cache.set(key!(2), value!(9));
assert!(rv.is_ok());
assert_eq!(cache.len(), 2);
assert_eq!(cache.get_stats().evictions, 0);
// Set an item so big it forces everything else to be evicted
let rv = cache.set(key!(3), value!(9, 10, 11));
assert!(rv.is_ok());
assert_eq!(cache.len(), 1);
assert_eq!(cache.get_stats().evictions, 2);
}
#[test]
fn test_exceed_item_size_limits() {
let mut cache = Cache::new(1024);
cache.with_key_maxlen(1)
.with_value_maxlen(1);
// contains_key: use a key that is too long
{
let rv = cache.contains_key(&key!(1, 2));
assert_eq!(rv.unwrap_err(), CacheError::KeyTooLong);
}
// get: use a key that is too long
{
let rv = cache.get(&key!(1, 2));
assert_eq!(rv.unwrap_err(), CacheError::KeyTooLong);
}
// remove: use a key that is too long
{
let rv = cache.remove(&key!(1, 2));
assert_eq!(rv.unwrap_err(), CacheError::KeyTooLong);
}
// set: use a key that is too long
{
let rv = cache.set(key!(1, 2), value!(9));
assert_eq!(rv.unwrap_err(), CacheError::KeyTooLong);
}
// set: use a value that is too long
{
let rv = cache.set(key!(1), value!(9, 8));
assert_eq!(rv.unwrap_err(), CacheError::ValueTooLong);
}
}
#[test]
fn test_key_expired_lifetime() {
// our cache has a lifetime of 0 secs - all keys are dead on store
let mut cache = Cache::new(1024);
cache.with_item_lifetime(0.0);
let key = key!(1);
let value = value!(9);
// set a key
let rv = cache.set(key.clone(), value);
assert!(rv.is_ok());
// try to retrieve it - it has expired
let rv = cache.get(&key);
assert_eq!(rv.unwrap_err(), CacheError::KeyNotFound);
}
#[test]
fn test_key_explicit_exptime() {
// our cache has infinite lifetime
let mut cache = Cache::new(1024);
let key = key!(1);
let mut value = value!(9);
// set exptime in the past
value.set_exptime(time_now() - 1.0);
// set a key
let rv = cache.set(key.clone(), value);
assert!(rv.is_ok());
// try to retrieve it - it has expired
let rv = cache.get(&key);
assert_eq!(rv.unwrap_err(), CacheError::KeyNotFound);
}
// this is a slow test that relies on sleeps
#[ignore]
#[test]
fn test_key_kept_alive_on_access() {
// our cache has a lifetime of 2 secs
let mut cache = Cache::new(1024);
cache.with_item_lifetime(2.0);
let key = key!(1);
let value = value!(9);
let rv = cache.set(key.clone(), value.clone());
assert!(rv.is_ok());
// sleep 1.5 secs - not long enough to expire key
sleep_secs(1.5);
// access key - it's there
assert!(cache.get(&key).is_ok());
// sleep 1 secs - not long enough to expire key
sleep_secs(1.0);
// access key - it's now been 2.5s since it was set, but it's been accessed
// so we've kept it alive
assert!(cache.get(&key).is_ok());
// sleep 2.5 secs - long enough to expire key
sleep_secs(2.5);
// access key - it's gone
assert!(cache.get(&key).is_err());
}
// this is a slow test that relies on sleeps
#[ignore]
#[test]
fn test_flush_all() {
// our cache has a lifetime of 2 secs
let mut cache = Cache::new(1024);
cache.with_item_lifetime(2.0);
// this item lives for 3s
let key1 = key!(1);
let mut value1 = value!(9);
value1.set_exptime(time_now() + 3.0);
let rv = cache.set(key1.clone(), value1.clone());
assert!(rv.is_ok());
// this item lives until cache lifetime
let key2 = key!(2);
let value2 = value!(8);
let rv = cache.set(key2.clone(), value2.clone());
assert!(rv.is_ok());
// make all items dead in one second
cache.flush_all(time_now() + 1.0).unwrap();
// sleep until flush time kicks in
sleep_secs(1.5);
// access both keys - both have expired
assert!(cache.get(&key1).is_err());
assert!(cache.get(&key2).is_err());
// set a new item that came after flush_all
let key3 = key!(3);
let value3 = value!(7);
let rv = cache.set(key3.clone(), value3.clone());
assert!(rv.is_ok());
// it was not expired
assert!(cache.get(&key3).is_ok());
}
#[test]
fn test_metrics() {
// NOTE: The most crucial metric is bytes, so make sure to test every data
// path that affects it.
let item_size = key!(1).mem_size() as u64 + value!(1, 2).mem_size() as u64;
let mut cache = Cache::new(item_size);
assert_eq!(cache.get_stats().bytes, 0);
assert_eq!(cache.get_stats().total_items, 0);
// Set a key
cache.set(key!(1), value!(2, 3)).unwrap();
assert_eq!(cache.get_stats().bytes, item_size);
assert_eq!(cache.get_stats().evictions, 0);
assert_eq!(cache.get_stats().get_hits, 0);
assert_eq!(cache.get_stats().get_misses, 0);
assert_eq!(cache.get_stats().delete_hits, 0);
assert_eq!(cache.get_stats().delete_misses, 0);
assert_eq!(cache.get_stats().total_items, 1);
// Set a different key, evicting the first
cache.set(key!(5), value!(6, 7)).unwrap();
assert_eq!(cache.get_stats().bytes, item_size);
assert_eq!(cache.get_stats().evictions, 1);
assert_eq!(cache.get_stats().get_hits, 0);
assert_eq!(cache.get_stats().get_misses, 0);
assert_eq!(cache.get_stats().delete_hits, 0);
assert_eq!(cache.get_stats().delete_misses, 0);
assert_eq!(cache.get_stats().total_items, 2);
// Re-set the key with a different value
cache.set(key!(5), value!(6, 8)).unwrap();
assert_eq!(cache.get_stats().bytes, item_size);
assert_eq!(cache.get_stats().evictions, 1);
assert_eq!(cache.get_stats().get_hits, 0);
assert_eq!(cache.get_stats().get_misses, 0);
assert_eq!(cache.get_stats().delete_hits, 0);
assert_eq!(cache.get_stats().delete_misses, 0);
assert_eq!(cache.get_stats().total_items, 3);
// Retrieve the key successfully
cache.get(&key!(5)).unwrap();
assert_eq!(cache.get_stats().bytes, item_size);
assert_eq!(cache.get_stats().evictions, 1);
assert_eq!(cache.get_stats().get_hits, 1);
assert_eq!(cache.get_stats().get_misses, 0);
assert_eq!(cache.get_stats().delete_hits, 0);
assert_eq!(cache.get_stats().delete_misses, 0);
assert_eq!(cache.get_stats().total_items, 3);
// Test for the key successfully
cache.contains_key(&key!(5)).unwrap();
assert_eq!(cache.get_stats().bytes, item_size);
assert_eq!(cache.get_stats().evictions, 1);
assert_eq!(cache.get_stats().get_hits, 2);
assert_eq!(cache.get_stats().get_misses, 0);
assert_eq!(cache.get_stats().delete_hits, 0);
assert_eq!(cache.get_stats().delete_misses, 0);
assert_eq!(cache.get_stats().total_items, 3);
// Retrieve a key that doesn't exist
cache.get(&key!(17)).unwrap_err();
assert_eq!(cache.get_stats().bytes, item_size);
assert_eq!(cache.get_stats().evictions, 1);
assert_eq!(cache.get_stats().get_hits, 2);
assert_eq!(cache.get_stats().get_misses, 1);
assert_eq!(cache.get_stats().delete_hits, 0);
assert_eq!(cache.get_stats().delete_misses, 0);
assert_eq!(cache.get_stats().total_items, 3);
// Create an expired value
let mut value = value!(11, 12);
value.set_exptime(time_now() - 1.0);
// Set a key that expires immediately
cache.set(key!(9), value).unwrap();
assert_eq!(cache.get_stats().bytes, item_size);
assert_eq!(cache.get_stats().evictions, 2);
assert_eq!(cache.get_stats().get_hits, 2);
assert_eq!(cache.get_stats().get_misses, 1);
assert_eq!(cache.get_stats().delete_hits, 0);
assert_eq!(cache.get_stats().delete_misses, 0);
assert_eq!(cache.get_stats().total_items, 4);
// Retrieve expired key
cache.get(&key!(9)).unwrap_err();
assert_eq!(cache.get_stats().bytes, 0);
assert_eq!(cache.get_stats().evictions, 2);
assert_eq!(cache.get_stats().get_hits, 2);
assert_eq!(cache.get_stats().get_misses, 2);
assert_eq!(cache.get_stats().delete_hits, 0);
assert_eq!(cache.get_stats().delete_misses, 0);
assert_eq!(cache.get_stats().total_items, 4);
// Set another key
cache.set(key!(21), value!(12, 13)).unwrap();
assert_eq!(cache.get_stats().bytes, item_size);
assert_eq!(cache.get_stats().evictions, 2);
assert_eq!(cache.get_stats().get_hits, 2);
assert_eq!(cache.get_stats().get_misses, 2);
assert_eq!(cache.get_stats().delete_hits, 0);
assert_eq!(cache.get_stats().delete_misses, 0);
assert_eq!(cache.get_stats().total_items, 5);
// Delete it
cache.remove(&key!(21)).unwrap();
assert_eq!(cache.get_stats().bytes, 0);
assert_eq!(cache.get_stats().evictions, 2);
assert_eq!(cache.get_stats().get_hits, 2);
assert_eq!(cache.get_stats().get_misses, 2);
assert_eq!(cache.get_stats().delete_hits, 1);
assert_eq!(cache.get_stats().delete_misses, 0);
assert_eq!(cache.get_stats().total_items, 5);
// Try to delete it again
cache.remove(&key!(21)).unwrap_err();
assert_eq!(cache.get_stats().bytes, 0);
assert_eq!(cache.get_stats().evictions, 2);
assert_eq!(cache.get_stats().get_hits, 2);
assert_eq!(cache.get_stats().get_misses, 2);
assert_eq!(cache.get_stats().delete_hits, 1);
assert_eq!(cache.get_stats().delete_misses, 1);
assert_eq!(cache.get_stats().total_items, 5);
}
| true |
0dc0ddf7b97c8b2f091038f6f4710641bba01fc6
|
Rust
|
fultonm/leetcodes
|
/rust/two_sum/src/main.rs
|
UTF-8
| 685 | 3.328125 | 3 |
[] |
no_license
|
use std::convert::TryInto;
fn main() {
println!("Hello, world!");
let my_nums = vec![0, 4, 2, 0];
let my_target = 0;
let ans = Solution::two_sum(my_nums, my_target);
println!("ans is {:?}", ans);
}
struct Solution {}
impl Solution {
pub fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> {
let (a, b) = dp(0usize, nums.len(), target, &nums);
vec![a.try_into().unwrap(), b.try_into().unwrap()]
}
}
fn dp(a: usize, b: usize, t: i32, n: &Vec<i32>) -> (usize, usize) {
if a + 1 >= b {
return (0, 0);
}
for i in a + 1..b {
if n[a] + n[i] == t {
return (a, i);
}
}
dp(a + 1, b, t, n)
}
| true |
86f208bdf4c90b9e438615bdf2c8d3e524ae4e3c
|
Rust
|
brace-rs/brace-rs
|
/crates/brace-web-auth/src/lib/action/update.rs
|
UTF-8
| 1,447 | 2.796875 | 3 |
[
"Apache-2.0",
"MIT"
] |
permissive
|
use actix::{Handler, Message};
use brace_db::{Database, DatabaseInner};
use failure::{format_err, Error};
use futures::future::Future;
use crate::model::User;
use crate::util::hash;
static QUERY: &str = r#"
UPDATE users
SET email = $2, password = $3, created = $4, updated = $5
WHERE id = $1
RETURNING id, email, password, created, updated
"#;
pub fn update(database: &Database, user: User) -> impl Future<Item = User, Error = Error> {
database
.send(Update(user))
.map_err(|err| format_err!("{}", err))
.and_then(|res| res)
}
pub struct Update(pub User);
impl Message for Update {
type Result = Result<User, Error>;
}
impl Handler<Update> for DatabaseInner {
type Result = Result<User, Error>;
fn handle(&mut self, msg: Update, _: &mut Self::Context) -> Self::Result {
let conn = self.0.get()?;
let rows = conn.query(
QUERY,
&[
&msg.0.id,
&msg.0.email,
&hash(&msg.0.password)?,
&msg.0.created,
&msg.0.updated,
],
)?;
if rows.is_empty() {
return Err(format_err!("Row not returned"));
}
let row = rows.get(0);
Ok(User {
id: row.get(0),
email: row.get(1),
password: row.get(2),
created: row.get(3),
updated: row.get(4),
})
}
}
| true |
4e23418da400205807abaf730f09298793d62a7d
|
Rust
|
cen5bin/io_utils
|
/src/stream/buffered_stream.rs
|
UTF-8
| 2,631 | 3.109375 | 3 |
[] |
no_license
|
use std::ops::Drop;
use std::intrinsics::copy_nonoverlapping;
use super::OutputStream;
pub struct BufferedOutputStream<T: OutputStream> {
buf: Vec<u8>,
pos: usize,
output_stream: T,
}
impl<T> BufferedOutputStream<T>
where T: OutputStream {
pub fn new(output_stream: T) -> Self {
BufferedOutputStream {
buf: vec![0u8; 8192],
pos: 0,
output_stream,
}
}
pub fn with_capacity(output_stream: T, capacity: usize) -> Self {
BufferedOutputStream {
buf: vec![0u8; capacity],
pos: 0,
output_stream,
}
}
}
impl<T> OutputStream for BufferedOutputStream<T>
where T: OutputStream {
fn write(&mut self, buf: &[u8]) {
self.write_slice(buf, 0, buf.len());
}
fn write_slice(&mut self, buf: &[u8], off: usize, len: usize) {
if len > self.buf.capacity() - self.pos {
self.flush();
if len > self.buf.len() {
self.output_stream.write_slice(buf, off, len);
return;
}
}
unsafe {
let ptr = buf.as_ptr().offset(off as isize);
let dst = self.buf.as_mut_ptr().offset(self.pos as isize);
copy_nonoverlapping(ptr, dst, len);
self.pos += len;
}
}
fn flush(&mut self) {
self.output_stream.write_slice(&self.buf, 0, self.pos);
self.pos = 0;
self.output_stream.flush();
}
}
impl<T> Drop for BufferedOutputStream<T>
where T: OutputStream {
fn drop(&mut self) {
self.flush();
}
}
#[cfg(test)]
mod tests {
use super::*;
use super::super::{FileOutputStream, InputStream, FileInputStream};
use ::fs::*;
use std::str;
use std::thread;
use std::time::Duration;
#[test]
fn test_buffered_output_stream() {
let test_file = "test_buffered_output_stream";
let mut bos = BufferedOutputStream::new(FileOutputStream::new(test_file).unwrap());
let buf = "abcdefg";
let mut s = String::new();
let mut len = 0;
for _ in 0..10000 {
len += buf.as_bytes().len();
bos.write(buf.as_bytes());
s += buf;
}
bos.flush();
println!("total len: {}", len);
let mut fis = FileInputStream::new(test_file).unwrap();
let mut res = vec![0u8; len];
let mut left = len;
while left > 0 {
left -= fis.read_to(&mut res, len - left, left);
}
assert_eq!(str::from_utf8(&res).unwrap(), s.as_str());
rm(test_file);
}
}
| true |
741db77cc16a6101a2c88e7f1c5cab20eb2be3eb
|
Rust
|
dfrankland/mk20d7
|
/src/mcg/c2/mod.rs
|
UTF-8
| 20,043 | 2.703125 | 3 |
[
"MIT"
] |
permissive
|
#[doc = r" Value read from the register"]
pub struct R {
bits: u8,
}
#[doc = r" Value to write to the register"]
pub struct W {
bits: u8,
}
impl super::C2 {
#[doc = r" Modifies the contents of the register"]
#[inline]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,
{
let bits = self.register.get();
let r = R { bits: bits };
let mut w = W { bits: bits };
f(&r, &mut w);
self.register.set(w.bits);
}
#[doc = r" Reads the contents of the register"]
#[inline]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
#[doc = r" Writes to the register"]
#[inline]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
let mut w = W::reset_value();
f(&mut w);
self.register.set(w.bits);
}
#[doc = r" Writes the reset value to the register"]
#[inline]
pub fn reset(&self) {
self.write(|w| w)
}
}
#[doc = "Possible values of the field `IRCS`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum IRCSR {
#[doc = "Slow internal reference clock selected."]
_0,
#[doc = "Fast internal reference clock selected."]
_1,
}
impl IRCSR {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
IRCSR::_0 => false,
IRCSR::_1 => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> IRCSR {
match value {
false => IRCSR::_0,
true => IRCSR::_1,
}
}
#[doc = "Checks if the value of the field is `_0`"]
#[inline]
pub fn is_0(&self) -> bool {
*self == IRCSR::_0
}
#[doc = "Checks if the value of the field is `_1`"]
#[inline]
pub fn is_1(&self) -> bool {
*self == IRCSR::_1
}
}
#[doc = "Possible values of the field `LP`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum LPR {
#[doc = "FLL (or PLL) is not disabled in bypass modes."]
_0,
#[doc = "FLL (or PLL) is disabled in bypass modes (lower power)"]
_1,
}
impl LPR {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
LPR::_0 => false,
LPR::_1 => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> LPR {
match value {
false => LPR::_0,
true => LPR::_1,
}
}
#[doc = "Checks if the value of the field is `_0`"]
#[inline]
pub fn is_0(&self) -> bool {
*self == LPR::_0
}
#[doc = "Checks if the value of the field is `_1`"]
#[inline]
pub fn is_1(&self) -> bool {
*self == LPR::_1
}
}
#[doc = "Possible values of the field `EREFS0`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum EREFS0R {
#[doc = "External reference clock requested."]
_0,
#[doc = "Oscillator requested."]
_1,
}
impl EREFS0R {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
EREFS0R::_0 => false,
EREFS0R::_1 => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> EREFS0R {
match value {
false => EREFS0R::_0,
true => EREFS0R::_1,
}
}
#[doc = "Checks if the value of the field is `_0`"]
#[inline]
pub fn is_0(&self) -> bool {
*self == EREFS0R::_0
}
#[doc = "Checks if the value of the field is `_1`"]
#[inline]
pub fn is_1(&self) -> bool {
*self == EREFS0R::_1
}
}
#[doc = "Possible values of the field `HGO0`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum HGO0R {
#[doc = "Configure crystal oscillator for low-power operation."]
_0,
#[doc = "Configure crystal oscillator for high-gain operation."]
_1,
}
impl HGO0R {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
HGO0R::_0 => false,
HGO0R::_1 => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> HGO0R {
match value {
false => HGO0R::_0,
true => HGO0R::_1,
}
}
#[doc = "Checks if the value of the field is `_0`"]
#[inline]
pub fn is_0(&self) -> bool {
*self == HGO0R::_0
}
#[doc = "Checks if the value of the field is `_1`"]
#[inline]
pub fn is_1(&self) -> bool {
*self == HGO0R::_1
}
}
#[doc = "Possible values of the field `RANGE0`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum RANGE0R {
#[doc = "Encoding 0 - Low frequency range selected for the crystal oscillator ."]
_00,
#[doc = "Encoding 1 - High frequency range selected for the crystal oscillator ."]
_01,
#[doc = r" Reserved"]
_Reserved(u8),
}
impl RANGE0R {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
match *self {
RANGE0R::_00 => 0,
RANGE0R::_01 => 1,
RANGE0R::_Reserved(bits) => bits,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: u8) -> RANGE0R {
match value {
0 => RANGE0R::_00,
1 => RANGE0R::_01,
i => RANGE0R::_Reserved(i),
}
}
#[doc = "Checks if the value of the field is `_00`"]
#[inline]
pub fn is_00(&self) -> bool {
*self == RANGE0R::_00
}
#[doc = "Checks if the value of the field is `_01`"]
#[inline]
pub fn is_01(&self) -> bool {
*self == RANGE0R::_01
}
}
#[doc = "Possible values of the field `LOCRE0`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum LOCRE0R {
#[doc = "Interrupt request is generated on a loss of OSC0 external reference clock."]
_0,
#[doc = "Generate a reset request on a loss of OSC0 external reference clock"]
_1,
}
impl LOCRE0R {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
LOCRE0R::_0 => false,
LOCRE0R::_1 => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> LOCRE0R {
match value {
false => LOCRE0R::_0,
true => LOCRE0R::_1,
}
}
#[doc = "Checks if the value of the field is `_0`"]
#[inline]
pub fn is_0(&self) -> bool {
*self == LOCRE0R::_0
}
#[doc = "Checks if the value of the field is `_1`"]
#[inline]
pub fn is_1(&self) -> bool {
*self == LOCRE0R::_1
}
}
#[doc = "Values that can be written to the field `IRCS`"]
pub enum IRCSW {
#[doc = "Slow internal reference clock selected."]
_0,
#[doc = "Fast internal reference clock selected."]
_1,
}
impl IRCSW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
IRCSW::_0 => false,
IRCSW::_1 => true,
}
}
}
#[doc = r" Proxy"]
pub struct _IRCSW<'a> {
w: &'a mut W,
}
impl<'a> _IRCSW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: IRCSW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Slow internal reference clock selected."]
#[inline]
pub fn _0(self) -> &'a mut W {
self.variant(IRCSW::_0)
}
#[doc = "Fast internal reference clock selected."]
#[inline]
pub fn _1(self) -> &'a mut W {
self.variant(IRCSW::_1)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 0;
self.w.bits &= !((MASK as u8) << OFFSET);
self.w.bits |= ((value & MASK) as u8) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `LP`"]
pub enum LPW {
#[doc = "FLL (or PLL) is not disabled in bypass modes."]
_0,
#[doc = "FLL (or PLL) is disabled in bypass modes (lower power)"]
_1,
}
impl LPW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
LPW::_0 => false,
LPW::_1 => true,
}
}
}
#[doc = r" Proxy"]
pub struct _LPW<'a> {
w: &'a mut W,
}
impl<'a> _LPW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: LPW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "FLL (or PLL) is not disabled in bypass modes."]
#[inline]
pub fn _0(self) -> &'a mut W {
self.variant(LPW::_0)
}
#[doc = "FLL (or PLL) is disabled in bypass modes (lower power)"]
#[inline]
pub fn _1(self) -> &'a mut W {
self.variant(LPW::_1)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 1;
self.w.bits &= !((MASK as u8) << OFFSET);
self.w.bits |= ((value & MASK) as u8) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `EREFS0`"]
pub enum EREFS0W {
#[doc = "External reference clock requested."]
_0,
#[doc = "Oscillator requested."]
_1,
}
impl EREFS0W {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
EREFS0W::_0 => false,
EREFS0W::_1 => true,
}
}
}
#[doc = r" Proxy"]
pub struct _EREFS0W<'a> {
w: &'a mut W,
}
impl<'a> _EREFS0W<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: EREFS0W) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "External reference clock requested."]
#[inline]
pub fn _0(self) -> &'a mut W {
self.variant(EREFS0W::_0)
}
#[doc = "Oscillator requested."]
#[inline]
pub fn _1(self) -> &'a mut W {
self.variant(EREFS0W::_1)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 2;
self.w.bits &= !((MASK as u8) << OFFSET);
self.w.bits |= ((value & MASK) as u8) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `HGO0`"]
pub enum HGO0W {
#[doc = "Configure crystal oscillator for low-power operation."]
_0,
#[doc = "Configure crystal oscillator for high-gain operation."]
_1,
}
impl HGO0W {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
HGO0W::_0 => false,
HGO0W::_1 => true,
}
}
}
#[doc = r" Proxy"]
pub struct _HGO0W<'a> {
w: &'a mut W,
}
impl<'a> _HGO0W<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: HGO0W) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Configure crystal oscillator for low-power operation."]
#[inline]
pub fn _0(self) -> &'a mut W {
self.variant(HGO0W::_0)
}
#[doc = "Configure crystal oscillator for high-gain operation."]
#[inline]
pub fn _1(self) -> &'a mut W {
self.variant(HGO0W::_1)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 3;
self.w.bits &= !((MASK as u8) << OFFSET);
self.w.bits |= ((value & MASK) as u8) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `RANGE0`"]
pub enum RANGE0W {
#[doc = "Encoding 0 - Low frequency range selected for the crystal oscillator ."]
_00,
#[doc = "Encoding 1 - High frequency range selected for the crystal oscillator ."]
_01,
}
impl RANGE0W {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> u8 {
match *self {
RANGE0W::_00 => 0,
RANGE0W::_01 => 1,
}
}
}
#[doc = r" Proxy"]
pub struct _RANGE0W<'a> {
w: &'a mut W,
}
impl<'a> _RANGE0W<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: RANGE0W) -> &'a mut W {
unsafe { self.bits(variant._bits()) }
}
#[doc = "Encoding 0 - Low frequency range selected for the crystal oscillator ."]
#[inline]
pub fn _00(self) -> &'a mut W {
self.variant(RANGE0W::_00)
}
#[doc = "Encoding 1 - High frequency range selected for the crystal oscillator ."]
#[inline]
pub fn _01(self) -> &'a mut W {
self.variant(RANGE0W::_01)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 3;
const OFFSET: u8 = 4;
self.w.bits &= !((MASK as u8) << OFFSET);
self.w.bits |= ((value & MASK) as u8) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `LOCRE0`"]
pub enum LOCRE0W {
#[doc = "Interrupt request is generated on a loss of OSC0 external reference clock."]
_0,
#[doc = "Generate a reset request on a loss of OSC0 external reference clock"]
_1,
}
impl LOCRE0W {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
LOCRE0W::_0 => false,
LOCRE0W::_1 => true,
}
}
}
#[doc = r" Proxy"]
pub struct _LOCRE0W<'a> {
w: &'a mut W,
}
impl<'a> _LOCRE0W<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: LOCRE0W) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Interrupt request is generated on a loss of OSC0 external reference clock."]
#[inline]
pub fn _0(self) -> &'a mut W {
self.variant(LOCRE0W::_0)
}
#[doc = "Generate a reset request on a loss of OSC0 external reference clock"]
#[inline]
pub fn _1(self) -> &'a mut W {
self.variant(LOCRE0W::_1)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 7;
self.w.bits &= !((MASK as u8) << OFFSET);
self.w.bits |= ((value & MASK) as u8) << OFFSET;
self.w
}
}
impl R {
#[doc = r" Value of the register as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
self.bits
}
#[doc = "Bit 0 - Internal Reference Clock Select"]
#[inline]
pub fn ircs(&self) -> IRCSR {
IRCSR::_from({
const MASK: bool = true;
const OFFSET: u8 = 0;
((self.bits >> OFFSET) & MASK as u8) != 0
})
}
#[doc = "Bit 1 - Low Power Select"]
#[inline]
pub fn lp(&self) -> LPR {
LPR::_from({
const MASK: bool = true;
const OFFSET: u8 = 1;
((self.bits >> OFFSET) & MASK as u8) != 0
})
}
#[doc = "Bit 2 - External Reference Select"]
#[inline]
pub fn erefs0(&self) -> EREFS0R {
EREFS0R::_from({
const MASK: bool = true;
const OFFSET: u8 = 2;
((self.bits >> OFFSET) & MASK as u8) != 0
})
}
#[doc = "Bit 3 - High Gain Oscillator Select"]
#[inline]
pub fn hgo0(&self) -> HGO0R {
HGO0R::_from({
const MASK: bool = true;
const OFFSET: u8 = 3;
((self.bits >> OFFSET) & MASK as u8) != 0
})
}
#[doc = "Bits 4:5 - Frequency Range Select"]
#[inline]
pub fn range0(&self) -> RANGE0R {
RANGE0R::_from({
const MASK: u8 = 3;
const OFFSET: u8 = 4;
((self.bits >> OFFSET) & MASK as u8) as u8
})
}
#[doc = "Bit 7 - Loss of Clock Reset Enable"]
#[inline]
pub fn locre0(&self) -> LOCRE0R {
LOCRE0R::_from({
const MASK: bool = true;
const OFFSET: u8 = 7;
((self.bits >> OFFSET) & MASK as u8) != 0
})
}
}
impl W {
#[doc = r" Reset value of the register"]
#[inline]
pub fn reset_value() -> W {
W { bits: 128 }
}
#[doc = r" Writes raw bits to the register"]
#[inline]
pub unsafe fn bits(&mut self, bits: u8) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bit 0 - Internal Reference Clock Select"]
#[inline]
pub fn ircs(&mut self) -> _IRCSW {
_IRCSW { w: self }
}
#[doc = "Bit 1 - Low Power Select"]
#[inline]
pub fn lp(&mut self) -> _LPW {
_LPW { w: self }
}
#[doc = "Bit 2 - External Reference Select"]
#[inline]
pub fn erefs0(&mut self) -> _EREFS0W {
_EREFS0W { w: self }
}
#[doc = "Bit 3 - High Gain Oscillator Select"]
#[inline]
pub fn hgo0(&mut self) -> _HGO0W {
_HGO0W { w: self }
}
#[doc = "Bits 4:5 - Frequency Range Select"]
#[inline]
pub fn range0(&mut self) -> _RANGE0W {
_RANGE0W { w: self }
}
#[doc = "Bit 7 - Loss of Clock Reset Enable"]
#[inline]
pub fn locre0(&mut self) -> _LOCRE0W {
_LOCRE0W { w: self }
}
}
| true |
06a0f875ec65f9b2b9dd98ac4284a1b4a19b0232
|
Rust
|
bdalrhm/rmc
|
/src/test/cbmc/Assert/ZeroValid/main.rs
|
UTF-8
| 851 | 3.046875 | 3 |
[
"MIT",
"Apache-2.0",
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause",
"BSD-2-Clause",
"NCSA"
] |
permissive
|
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0 OR MIT
// The function zeroed() calls assert_zero_valid to mark that it is only defined to assign an
// all-zero bit pattern to a type T if this is a valid value. So the following is safe.
use std::mem;
#[repr(C)]
#[derive(PartialEq, Eq)]
struct S {
a: u8,
b: u16,
}
fn do_test<T: std::cmp::Eq>(init: T, expected: T) {
let mut x: T = init;
x = unsafe { mem::zeroed() };
assert!(expected == x);
}
fn main() {
do_test::<bool>(true, false);
do_test::<i8>(-42, 0);
do_test::<i16>(-42, 0);
do_test::<i32>(-42, 0);
do_test::<i64>(-42, 0);
do_test::<u8>(42, 0);
do_test::<u16>(42, 0);
do_test::<u32>(42, 0);
do_test::<u64>(42, 0);
do_test::<S>(S { a: 42, b: 42 }, S { a: 0, b: 0 });
}
| true |
82b3c7a7c248f4e79cb6a7dd960010b94f2f3ae9
|
Rust
|
CorbyAsCode/rust_poc_projects
|
/ecs_query/src/main.rs
|
UTF-8
| 6,905 | 2.703125 | 3 |
[] |
no_license
|
use rusoto_core::credential::ChainProvider;
#[allow(dead_code)]
use rusoto_core::request::HttpClient;
use rusoto_core::Region;
use rusoto_ecs::{
DescribeServicesRequest, Ecs, EcsClient, ListServicesRequest, ListTasksRequest, Service,
};
use std::collections::HashMap;
use std::process;
use std::time::{Duration, Instant};
fn main() {
let mut chain = ChainProvider::new();
chain.set_timeout(Duration::from_millis(200));
let ecs_client = EcsClient::new_with(
HttpClient::new().expect("failed to create request dispatcher"),
chain,
Region::UsEast1,
);
get_services_with_tasks(&ecs_client);
}
fn split_last_string(s: &String) -> String {
match s.rsplit("/").next() {
None => String::new(),
Some(elem) => String::from(elem),
}
}
/*
fn get_images_of_task_definition<'a>(
ecs_client: &'a EcsClient,
task_definitions: Vec<String>,
) //-> impl Future<Item = Vec<String>, Error = Error> + 'a {
{
let get_images_futures = task_definitions.into_iter().map(move |td| {
let task_definition_req = DescribeTaskDefinitionRequest {
task_definition: td,
include: Some(Vec::new()),
};
ecs_client
.describe_task_definition(task_definition_req)
.map(|task_definition_res| {
task_definition_res
.task_definition
.and_then(|td| td.container_definitions)
.and_then(|cds| cds.last().cloned())
.and_then(|cd| cd.image)
.and_then(|image| Some(image))
})
});
join_all(get_images_futures)
.map(|found_images| found_images.into_iter().flatten().collect())
.map_err(|err| err.into())
}
*/
fn get_all_services(ecs_client: &EcsClient, cluster: &String) -> Vec<String> {
let service_request = ListServicesRequest {
cluster: Some(cluster.clone()),
max_results: Some(100),
..Default::default()
};
match ecs_client.list_services(service_request).sync() {
Err(e) => {
println!("Error: {}", e);
process::exit(1);
}
Ok(services) => services
.service_arns
.unwrap()
.iter()
.map(|arn| split_last_string(arn))
.collect(),
}
}
fn describe_services(
ecs_client: &EcsClient,
cluster: &String,
service_names: Vec<String>,
) -> Vec<Service> {
let mut describe_services: Vec<Service> = Vec::new();
for service_name_group in service_names.chunks(10) {
let desc_service_req = DescribeServicesRequest {
cluster: Some(cluster.clone()),
services: service_name_group.to_vec(),
..Default::default()
};
describe_services.extend(
match ecs_client.describe_services(desc_service_req).sync() {
Err(e) => {
println!("Error: {}", e);
process::exit(1);
}
Ok(services) => services.services.unwrap(),
},
)
}
describe_services
}
fn find_active_services(services: Vec<Service>) -> Vec<String> {
let mut active_services: Vec<String> = Vec::new();
for service in services {
if service.running_count.unwrap() > 0 {
println!(
"Running service: {}, count: {}",
service.service_name.clone().unwrap(),
service.running_count.unwrap()
);
active_services.push(service.service_name.unwrap());
} else {
println!(
"Not running service: {}, count: {}",
service.service_name.unwrap(),
service.running_count.unwrap()
);
}
}
active_services
}
fn map_tasks_to_services(
ecs_client: &EcsClient,
cluster: &String,
services: Vec<String>,
) -> HashMap<String, Vec<String>> {
let mut services_and_tasks: HashMap<String, Vec<String>> = HashMap::new();
for service in services {
let active_tasks_req = ListTasksRequest {
cluster: Some(cluster.clone()),
container_instance: None,
desired_status: None,
family: None,
launch_type: None,
max_results: Some(100),
next_token: None,
service_name: Some(String::from(&service)),
started_by: None,
};
let tasks: Vec<String> = match ecs_client.list_tasks(active_tasks_req).sync() {
Err(e) => {
println!("Error: {}", e);
process::exit(1);
}
Ok(tasks) => tasks.task_arns.unwrap(),
};
//task_arns.append(&mut tasks);
services_and_tasks.insert(service, tasks);
}
services_and_tasks
}
fn get_services_with_tasks(ecs_client: &EcsClient) -> HashMap<String, Vec<String>> {
//let cluster_name = String::from("PLATENG-TESTLAB");
let cluster_name = String::from("TCE-ECS-CLUSTER-INTERNAL-02");
let start = Instant::now();
let all_service_names = get_all_services(ecs_client, &cluster_name);
println!(
"Finished all_service_names in {:?}",
Instant::now().duration_since(start)
);
//println!("all service_names: {:?}, count: {}", all_service_names, all_service_names.len());
/* Just an example of how to transform a string
let service_names = service_arns
.iter()
.map(|arn| format!("{}test", arn))
.collect::<Vec<std::string::String>>();
println!("service_names: {:?}", service_names);
*/
let start = Instant::now();
let describe_services: Vec<Service> =
describe_services(ecs_client, &cluster_name, all_service_names);
println!(
"Finished describe_services in {:?}",
Instant::now().duration_since(start)
);
let start = Instant::now();
let active_services = find_active_services(describe_services);
println!(
"Finished for service in describe_services in {:?}",
Instant::now().duration_since(start)
);
println!("number of active services: {}", active_services.len());
//println!("active services: {:?}", active_services);
let start = Instant::now();
let services_and_tasks = map_tasks_to_services(ecs_client, &cluster_name, active_services);
println!(
"Finished for service in active_services in {:?}",
Instant::now().duration_since(start)
);
println!("services_and_tasks: {:?}", services_and_tasks);
/*
{
# container id: {task id, service name}
47djw92kej39: {
task_id: f749ej3983-38o56kf9
service_name: my_cool_stuff
},
g84832i2i3i7: {
task_id: f749ej3983-38o56kf9
service_name: my_crap_stuff
}
}
*/
HashMap::new()
}
| true |
90d0daffea7b3c0791c833036b0c51fe695944bc
|
Rust
|
gilbertw1/mpwc
|
/src/conf.rs
|
UTF-8
| 825 | 2.8125 | 3 |
[
"Unlicense"
] |
permissive
|
use clap::ArgMatches;
pub fn create_config(matches: &ArgMatches) -> MpwcConfig {
MpwcConfig {
stdin: matches.is_present("stdin"),
quiet: matches.is_present("quiet"),
name: get_string_value(matches, "name").unwrap(),
site: get_string_value(matches, "site").unwrap(),
counter: get_int_value(matches, "counter").unwrap(),
pass_type: get_string_value(matches, "type").unwrap()
}
}
fn get_string_value(matches: &ArgMatches, key: &str) -> Option<String> {
matches.value_of(key).map(|m| m.to_string())
}
fn get_int_value(matches: &ArgMatches, key: &str) -> Option<u32> {
matches.value_of(key).map(|m| m.parse::<u32>().unwrap())
}
#[derive(Debug)]
pub struct MpwcConfig {
pub quiet: bool,
pub stdin: bool,
pub name: String,
pub site: String,
pub counter: u32,
pub pass_type: String,
}
| true |
b93282dc1c21148eaa0bd5d6f851aeccfee8c64b
|
Rust
|
codeworm96/hikari
|
/src/bvh_node.rs
|
UTF-8
| 1,931 | 2.71875 | 3 |
[] |
no_license
|
use rand::prelude::*;
use crate::aabb::{surrounding_box, AABB};
use crate::hitable::{HitRecord, Hitable};
use crate::ray::Ray;
pub struct BvhNode {
left: Box<dyn Hitable + Sync>,
right: Box<dyn Hitable + Sync>,
aabb: AABB,
}
pub fn build(
mut list: Vec<Box<dyn Hitable + Sync>>,
time0: f64,
time1: f64,
rng: &mut ThreadRng,
) -> Box<dyn Hitable + Sync> {
let len = list.len();
if len == 0 {
panic!("no hitables");
} else if len == 1 {
list.remove(0)
} else {
let axis = rng.gen_range(0, 3);
/* TODO perf */
list.sort_by(|a, b| {
a.bounding_box(time0, time1).unwrap().min[axis]
.partial_cmp(&b.bounding_box(time0, time1).unwrap().min[axis])
.unwrap()
});
let list2 = list.split_off(len / 2);
let left = build(list, time0, time1, rng);
let right = build(list2, time0, time1, rng);
let aabb = surrounding_box(
&left.bounding_box(time0, time1).unwrap(),
&right.bounding_box(time0, time1).unwrap(),
);
Box::new(BvhNode { left, right, aabb })
}
}
impl Hitable for BvhNode {
fn hit(&self, r: &Ray, t_min: f64, t_max: f64) -> Option<HitRecord> {
if self.aabb.hit(r, t_min, t_max) {
match (
self.left.hit(r, t_min, t_max),
self.right.hit(r, t_min, t_max),
) {
(Some(l), Some(r)) => {
if l.t < r.t {
Some(l)
} else {
Some(r)
}
}
(Some(l), None) => Some(l),
(None, Some(r)) => Some(r),
(None, None) => None,
}
} else {
None
}
}
fn bounding_box(&self, _t0: f64, _t1: f64) -> Option<AABB> {
Some(self.aabb)
}
}
| true |
fc87997b413547696f342f7412dfb1d080952a13
|
Rust
|
timsuchanek/prisma-engines
|
/libs/datamodel/core/src/ast/enum.rs
|
UTF-8
| 1,674 | 3.21875 | 3 |
[
"Apache-2.0"
] |
permissive
|
use super::*;
/// An enum declaration.
#[derive(Debug, Clone, PartialEq)]
pub struct Enum {
/// The name of the enum.
pub name: Identifier,
/// The values of the enum.
pub values: Vec<EnumValue>,
/// The directives of this enum.
pub directives: Vec<Directive>,
/// The comments for this enum.
pub documentation: Option<Comment>,
/// The location of this enum in the text representation.
pub span: Span,
}
impl WithIdentifier for Enum {
fn identifier(&self) -> &Identifier {
&self.name
}
}
impl WithSpan for Enum {
fn span(&self) -> &Span {
&self.span
}
}
impl WithDirectives for Enum {
fn directives(&self) -> &Vec<Directive> {
&self.directives
}
}
impl WithDocumentation for Enum {
fn documentation(&self) -> &Option<Comment> {
&self.documentation
}
fn is_commented_out(&self) -> bool {
false
}
}
/// An enum value definition.
#[derive(Debug, Clone, PartialEq)]
pub struct EnumValue {
/// The name of the enum value as it will be exposed by the api.
pub name: Identifier,
/// The enum value as it will be stored in the database.
pub directives: Vec<Directive>,
/// The location of this enum value in the text representation.
pub documentation: Option<Comment>,
pub span: Span,
pub commented_out: bool,
}
impl WithIdentifier for EnumValue {
fn identifier(&self) -> &Identifier {
&self.name
}
}
impl WithDirectives for EnumValue {
fn directives(&self) -> &Vec<Directive> {
&self.directives
}
}
impl WithSpan for EnumValue {
fn span(&self) -> &Span {
&self.span
}
}
| true |
22875a923e6c208132b896ce1095c622c179329d
|
Rust
|
elpiel/serde-hex
|
/src/macros/hex.rs
|
UTF-8
| 7,080 | 2.796875 | 3 |
[
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
//! Various helpful macros related to implementing `SerHex`.
/// implement `SerHexSeq` for a specified type.
#[macro_export]
macro_rules! impl_serhex_seq {
($type: ty, $bytes: expr) => {
impl $crate::SerHexSeq<$crate::Strict> for $type {
fn size() -> usize {
$bytes
}
}
impl $crate::SerHexSeq<$crate::StrictPfx> for $type {
fn size() -> usize {
$bytes
}
}
impl $crate::SerHexSeq<$crate::StrictCap> for $type {
fn size() -> usize {
$bytes
}
}
impl $crate::SerHexSeq<$crate::StrictCapPfx> for $type {
fn size() -> usize {
$bytes
}
}
};
}
/// helper macro for implementing the `into_hex_raw` function for
/// bytearray-style types.
#[doc(hidden)]
#[macro_export]
macro_rules! into_hex_bytearray {
($src: ident, $dst: ident, $len: expr) => {{
let src: &[u8] = $src.as_ref();
debug_assert!(src.len() == $len);
// add prefix if we are doing such things.
if <C as $crate::HexConf>::withpfx() {
$dst.write_all("0x".as_bytes())?;
}
// if
if <C as $crate::HexConf>::compact() {
// find index and location of first non-zero byte.
if let Some((idx, val)) = src.iter().enumerate().find(|&(_, v)| *v > 0u8) {
// if first non-zero byte is less than `0x10`, repr w/ one hex char.
if *val < 0x10 {
if <C as $crate::HexConf>::withcap() {
$dst.write_all(&[$crate::utils::fromvalcaps(*val)])?;
$crate::utils::writehexcaps(&src[(idx + 1)..], $dst)
} else {
$dst.write_all(&[$crate::utils::fromval(*val)])?;
$crate::utils::writehex(&src[(idx + 1)..], $dst)
}
} else {
if <C as $crate::HexConf>::withcap() {
$crate::utils::writehexcaps(&src[idx..], $dst)
} else {
$crate::utils::writehex(&src[idx..], $dst)
}
}
// if no non-zero byte was found, just write in a zero.
} else {
$dst.write_all(&[b'0'])?;
Ok(())
}
} else {
if <C as $crate::HexConf>::withcap() {
$crate::utils::writehexcaps(src, $dst)
} else {
$crate::utils::writehex(src, $dst)
}
}
}};
}
/// helper macro for implementing the `into_hex_raw` function for
/// bytearray-style types.
#[doc(hidden)]
#[macro_export]
macro_rules! from_hex_bytearray {
($src: ident, $len: expr) => {{
let raw: &[u8] = $src.as_ref();
let hex = if <C as $crate::HexConf>::withpfx() {
let pfx = "0x".as_bytes();
if raw.starts_with(pfx) {
&raw[2..]
} else {
raw
}
} else {
raw
};
let mut buf = [0u8; $len];
if <C as $crate::HexConf>::compact() {
let min = 1;
let max = $len * 2;
let got = hex.len();
if got < min || got > max {
let inner = $crate::types::ParseHexError::Range { min, max, got };
let error = $crate::types::Error::from(inner);
return Err(error.into());
}
let body = $len - (got / 2);
let head = got % 2;
if head > 0 {
buf[body - head] = $crate::utils::intobyte(b'0', hex[0])?;
}
$crate::utils::fromhex(&mut buf[body..], &hex[head..])?;
} else {
$crate::utils::fromhex(&mut buf[..], hex)?;
}
Ok(buf)
}};
}
/// macro for implementing `SerHex` for a type which implements
/// `From<[u8;n]>` and `AsRef<[u8]>`.
#[macro_export]
macro_rules! impl_serhex_bytearray {
($type: ty, $len: expr) => {
impl_serhex_seq!($type, $len);
impl<C> $crate::SerHex<C> for $type
where
C: $crate::HexConf,
{
type Error = $crate::types::Error;
fn into_hex_raw<D>(&self, mut dst: D) -> ::std::result::Result<(), Self::Error>
where
D: ::std::io::Write,
{
into_hex_bytearray!(self, dst, $len)?;
Ok(())
}
fn from_hex_raw<S>(src: S) -> ::std::result::Result<Self, Self::Error>
where
S: AsRef<[u8]>,
{
let rslt: ::std::result::Result<[u8; $len], Self::Error> =
from_hex_bytearray!(src, $len);
match rslt {
Ok(buf) => Ok(buf.into()),
Err(e) => Err(e),
}
}
}
};
}
#[cfg(test)]
mod tests {
use {
Compact, CompactCap, CompactCapPfx, CompactPfx, SerHex, Strict, StrictCap, StrictCapPfx,
StrictPfx,
};
#[derive(Debug, PartialEq, Eq)]
struct Foo([u8; 4]);
impl_newtype_bytearray!(Foo, 4);
impl_serhex_bytearray!(Foo, 4);
#[test]
fn hex_strict_ok() {
let f1 = Foo([0, 1, 2, 3]);
let hs = <Foo as SerHex<Strict>>::into_hex(&f1).unwrap();
let f2 = <Foo as SerHex<Strict>>::from_hex(&hs).unwrap();
assert_eq!(f1, f2);
}
#[test]
#[should_panic]
fn hex_strict_err() {
let _ = <Foo as SerHex<Strict>>::from_hex("faaffaa").unwrap();
}
#[test]
fn hex_compact() {
let f1 = Foo([0, 0, 0x0a, 0xff]);
let hs = <Foo as SerHex<Compact>>::into_hex(&f1).unwrap();
assert_eq!(&hs, "aff");
let f2 = <Foo as SerHex<Compact>>::from_hex(&hs).unwrap();
assert_eq!(f1, f2);
}
#[test]
fn hex_variants() {
let f = Foo([0x00, 0x0f, 0xff, 0x11]);
assert_eq!(
"0x000fff11",
<Foo as SerHex<StrictPfx>>::into_hex(&f).unwrap()
);
assert_eq!(
"000FFF11",
<Foo as SerHex<StrictCap>>::into_hex(&f).unwrap()
);
assert_eq!(
"0x000FFF11",
<Foo as SerHex<StrictCapPfx>>::into_hex(&f).unwrap()
);
assert_eq!(
"0xfff11",
<Foo as SerHex<CompactPfx>>::into_hex(&f).unwrap()
);
assert_eq!("FFF11", <Foo as SerHex<CompactCap>>::into_hex(&f).unwrap());
assert_eq!(
"0xFFF11",
<Foo as SerHex<CompactCapPfx>>::into_hex(&f).unwrap()
);
}
#[test]
fn blanket_array() {
let v: [Foo; 2] = <[Foo; 2] as SerHex<StrictPfx>>::from_hex("0xffaaffaa11221122").unwrap();
assert_eq!(v[0], Foo([0xff, 0xaa, 0xff, 0xaa]));
assert_eq!(v[1], Foo([0x11, 0x22, 0x11, 0x22]));
let hs = <[Foo; 2] as SerHex<StrictPfx>>::into_hex(&v).unwrap();
assert_eq!(hs, "0xffaaffaa11221122");
}
}
| true |
faff9e1bac8435170dbb6694ab0a3996564da6ef
|
Rust
|
davidsm/aoc-2020
|
/parser/src/lib.rs
|
UTF-8
| 12,113 | 3.28125 | 3 |
[] |
no_license
|
// Stolen from Nom, more or less
// TODO: Figure out how to make this with &str instead of generic I...
pub trait Parser<O, I> {
fn parse(&self, input: I) -> Option<(O, I)>;
}
impl<'a, I, O, F> Parser<O, I> for F
where
F: Fn(I) -> Option<(O, I)> + 'a,
{
fn parse(&self, i: I) -> Option<(O, I)> {
self(i)
}
}
pub fn take_while(pred: impl Fn(char) -> bool, input: &str) -> (&str, &str) {
let mut i = 0;
for (ci, c) in input.char_indices() {
i = ci;
if !pred(c) {
break;
}
i += 1
}
(&input[..i], &input[i..])
}
pub fn take_while1(pred: impl Fn(char) -> bool, input: &str) -> Option<(&str, &str)> {
let (matching, input) = take_while(pred, input);
if !matching.is_empty() {
Some((matching, input))
} else {
None
}
}
pub fn take(length: usize, input: &str) -> Option<(&str, &str)> {
let mut char_ind_iter = input.char_indices();
let (ci, _) = char_ind_iter.nth(length - 1)?;
let ci = char_ind_iter.next().map(|(ci, _)| ci).unwrap_or(ci + 1);
Some((&input[..ci], &input[ci..]))
}
pub fn fixed<'a>(s: &str, input: &'a str) -> Option<(&'a str, &'a str)> {
if let Some(rest) = input.strip_prefix(s) {
Some((&input[..s.len()], rest))
} else {
None
}
}
pub fn unsigned_number(input: &str) -> Option<(u64, &str)> {
let (num_str, input) = take_while(|c| c.is_ascii_digit(), input);
let num = num_str.parse::<u64>().ok()?;
Some((num, input))
}
pub fn signed_number(input: &str) -> Option<(i64, &str)> {
let parser = |inp| {
let (_, inp) = optional(
|inp_| either(|i| fixed("+", i), |i| fixed("-", i), inp_),
inp,
);
let (_, inp) = unsigned_number(inp)?;
Some(((), inp))
};
let (num_str, input) = recognize(parser, input)?;
let num = num_str.parse::<i64>().ok()?;
Some((num, input))
}
pub fn match_n(pred: impl Fn(char) -> bool, length: usize, input: &str) -> Option<(&str, &str)> {
let (part, input) = take(length, input)?;
if part.chars().all(pred) {
Some((part, input))
} else {
None
}
}
pub fn endline(input: &str) -> Option<(&str, &str)> {
match_n(|c| c == '\n', 1, input)
}
pub fn words(number: usize, input: &str) -> Option<(&str, &str)> {
assert!(number > 0);
let mut rest = input;
let mut pos_words_end = 0;
for _ in 0..(number - 1) {
let pos_word_end = rest.find(' ')?;
if pos_word_end == input.len() - 1 {
return None;
}
let start_next_word = pos_word_end + 1;
rest = &rest[start_next_word..];
pos_words_end += start_next_word;
}
let pos_word_end = rest.find(' ').unwrap_or_else(|| rest.len());
pos_words_end += pos_word_end;
Some((&input[..pos_words_end], &input[pos_words_end..]))
}
pub fn optional<'a, O>(parser: impl Parser<O, &'a str>, input: &'a str) -> (Option<O>, &'a str) {
if let Some((res, rest)) = parser.parse(input) {
(Some(res), rest)
} else {
(None, input)
}
}
pub fn many1<'a, O>(parser: impl Parser<O, &'a str>, mut input: &'a str) -> Option<(Vec<O>, &str)> {
let mut collected = Vec::new();
while let Some((res, rest)) = parser.parse(input) {
collected.push(res);
input = rest;
}
if !collected.is_empty() {
Some((collected, input))
} else {
None
}
}
pub fn either<'a, O>(
parser1: impl Parser<O, &'a str>,
parser2: impl Parser<O, &'a str>,
input: &'a str,
) -> Option<(O, &str)> {
parser1.parse(input).or_else(|| parser2.parse(input))
}
pub fn recognize<'a, O>(parser: impl Parser<O, &'a str>, input: &'a str) -> Option<(&str, &str)> {
let (_, rest) = parser.parse(input)?;
// Feels a little weird, but stolen from Nom, so probably fine, maybe
let input_ptr = input.as_ptr();
let rest_ptr = rest.as_ptr();
let offset = rest_ptr as usize - input_ptr as usize;
Some((&input[..offset], rest))
}
pub fn eof(input: &str) -> Option<(&str, &str)> {
if input.is_empty() {
Some(("", input))
} else {
None
}
}
pub fn endline_terminated<'a, O>(
parser: impl Parser<O, &'a str>,
input: &'a str,
) -> Option<(O, &str)> {
let (res, input) = parser.parse(input)?;
let (_, input) = either(endline, eof, input)?;
Some((res, input))
}
#[macro_export]
macro_rules! make_parser {
($parser:path, $($arg:expr),*) => {
move |inp| $parser($($arg,)* inp)
}
}
#[macro_export]
macro_rules! any {
($parser_1:expr, $parser_2:expr, $($parser_n:expr),*) => {
{
let parser = $crate::make_parser!($crate::either, $parser_1, $parser_2);
$(let parser = $crate::make_parser!($crate::either, parser, $parser_n);)*
parser
}
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn take_while_with_matches() {
let input = "1234abc";
let res = take_while(|c| c.is_ascii_digit(), input);
assert_eq!(res, ("1234", "abc"));
}
#[test]
fn take_while_full_match() {
let input = "1234";
let res = take_while(|c| c.is_ascii_digit(), input);
assert_eq!(res, ("1234", ""));
}
#[test]
fn take_while_no_matches() {
let input = "abc";
let res = take_while(|c| c.is_ascii_digit(), input);
assert_eq!(res, ("", "abc"));
}
#[test]
fn take_while1_with_match() {
let input = "1234abc";
let res = take_while1(|c| c.is_ascii_digit(), input);
assert_eq!(res, Some(("1234", "abc")));
}
#[test]
fn take_while1_no_matches() {
let input = "abc";
let res = take_while1(|c| c.is_ascii_digit(), input);
assert!(res.is_none());
}
#[test]
fn take_within_range() {
let input = "1234";
let res = take(2, input);
assert_eq!(res, Some(("12", "34")));
}
#[test]
fn take_beyond_range() {
let input = "1234";
let res = take(5, input);
assert!(res.is_none());
}
#[test]
fn take_complete() {
let input = "1234";
let res = take(4, input);
assert_eq!(res, Some(("1234", "")));
}
#[test]
fn fixed_matches() {
let input = "1234abc";
let res = fixed("1234", input);
assert_eq!(res, Some(("1234", "abc")));
}
#[test]
fn fixed_no_match() {
let input = "1234abc";
let res = fixed("12345", input);
assert!(res.is_none());
}
#[test]
fn unsigned_number_matches() {
let input = "1234abc";
let res = unsigned_number(input);
assert_eq!(res, Some((1234, "abc")));
}
#[test]
fn unsigned_number_no_match() {
let input = "abc1234";
let res = unsigned_number(input);
assert!(res.is_none());
}
#[test]
fn signed_number_matches_positive() {
let input = "+10";
let res = signed_number(input);
assert_eq!(res, Some((10, "")));
}
#[test]
fn signed_number_matches_negative() {
let input = "-9";
let res = signed_number(input);
assert_eq!(res, Some((-9, "")));
}
#[test]
fn signed_number_matches_no_sign() {
let input = "10";
let res = signed_number(input);
assert_eq!(res, Some((10, "")));
}
#[test]
fn signed_number_no_match() {
let input = "a10";
let res = signed_number(input);
assert!(res.is_none());
}
#[test]
fn match_n_matches() {
let input = "1234abc";
let res = match_n(|c| c.is_ascii_digit(), 2, input);
assert_eq!(res, Some(("12", "34abc")));
}
#[test]
fn match_n_no_match() {
let input = "abc1234";
let res = match_n(|c| c.is_ascii_digit(), 2, input);
assert!(res.is_none());
}
#[test]
fn match_n_beyond_range() {
let input = "12";
let res = match_n(|c| c.is_ascii_digit(), 3, input);
assert!(res.is_none());
}
fn two_space(input: &str) -> Option<(&str, &str)> {
if input.starts_with(" ") {
Some((&input[..2], &input[2..]))
} else {
None
}
}
#[test]
fn optional_matches() {
let input = " abc";
let res = optional(two_space, input);
assert_eq!(res, (Some(" "), "abc"));
}
#[test]
fn optional_no_match() {
let input = " abc";
let res = optional(two_space, input);
assert_eq!(res, (None, " abc"));
}
#[test]
fn match1_matches() {
let input = " abc";
let res = many1(two_space, input);
let expected = vec![" ", " "];
assert_eq!(res, Some((expected, "abc")));
}
#[test]
fn match1_no_match() {
let input = "abc";
let res = many1(two_space, input);
assert!(res.is_none());
}
#[test]
fn endline_match() {
let input = "\nabc";
let res = endline(input);
assert_eq!(res, Some(("\n", "abc")));
}
#[test]
fn words_one() {
let input = "dark green sky";
let res = words(1, input);
assert_eq!(res, Some(("dark", " green sky")));
}
#[test]
fn words_two() {
let input = "dark green sky";
let res = words(2, input);
assert_eq!(res, Some(("dark green", " sky")));
}
#[test]
fn words_incomplete() {
let input = "dark";
let res = words(2, input);
assert!(res.is_none());
}
#[test]
fn words_complete() {
let input = "dark";
let res = words(1, input);
assert_eq!(res, Some(("dark", "")));
let input = "dark green";
let res = words(2, input);
assert_eq!(res, Some(("dark green", "")));
}
#[test]
fn recognize_match() {
let parser = |inp| {
let (_, inp) = fixed("#", inp)?;
let (_, inp) = take_while1(|c| c.is_ascii_digit(), inp)?;
Some(((), inp))
};
let input = "#1234abc";
let res = recognize(parser, input);
assert_eq!(res, Some(("#1234", "abc")));
}
#[test]
fn either_one_matches() {
let p1 = |inp| fixed("A", inp);
let p2 = |inp| fixed("a", inp);
let input = "abcd";
let res = either(p1, p2, input);
assert_eq!(res, Some(("a", "bcd")));
let res = either(p2, p1, input);
assert_eq!(res, Some(("a", "bcd")));
let input = "Abcd";
let res = either(p1, p2, input);
assert_eq!(res, Some(("A", "bcd")));
}
#[test]
fn either_no_match() {
let p1 = |inp| fixed("A", inp);
let p2 = |inp| fixed("a", inp);
let input = "bcd";
let res = either(p1, p2, input);
assert!(res.is_none());
}
#[test]
fn endline_terminated_endline() {
let input = "abc\ndef";
let res = endline_terminated(|inp| fixed("abc", inp), input);
assert_eq!(res, Some(("abc", "def")));
}
#[test]
fn endline_terminated_eof() {
let input = "abc";
let res = endline_terminated(|inp| fixed("abc", inp), input);
assert_eq!(res, Some(("abc", "")));
}
#[test]
fn make_parser_fixed() {
let parser = make_parser!(fixed, "abc");
let res = parser("abcd");
assert_eq!(res, Some(("abc", "d")));
}
#[test]
fn make_parser_match_n() {
let parser = make_parser!(match_n, |c| c == 'a', 3);
let res = parser("aaaab");
assert_eq!(res, Some(("aaa", "ab")));
}
#[test]
fn any_fixed() {
let parser1 = make_parser!(fixed, "a");
let parser2 = make_parser!(fixed, "b");
let parser3 = make_parser!(fixed, "c");
let any_parser = any!(parser1, parser2, parser3);
assert_eq!(any_parser("a "), Some(("a", " ")));
assert_eq!(any_parser("b "), Some(("b", " ")));
assert_eq!(any_parser("c "), Some(("c", " ")));
assert!(any_parser("d ").is_none());
}
}
| true |
35344d40195bd9ea6bec78aff27026d3523761a6
|
Rust
|
indragiek/advent-of-code-2020
|
/day1part1/src/main.rs
|
UTF-8
| 874 | 3.21875 | 3 |
[
"MIT"
] |
permissive
|
use std::env;
use std::fs::File;
use std::io::{self, BufRead};
use std::process;
fn main() {
let args: Vec<String> = env::args().collect();
if args.len() < 2 {
println!("usage: day1part1 <path to input text file>");
process::exit(1);
}
let filename = &args[1];
let file = File::open(filename).expect("failed to open file");
let mut values: Vec<u32> = io::BufReader::new(file)
.lines()
.map(|line| line.unwrap())
.map(|line| line.parse::<u32>().unwrap())
.collect();
values.sort();
for i in 0..values.len() {
let value = values[i];
if let Ok(index) = values.binary_search(&(2020 - value)) {
println!("{}", value * values[index]);
process::exit(0);
}
}
println!("did not find a pair of numbers that sum to 2020");
process::exit(1);
}
| true |
49c1cccfbb28db73d7674e6a11a00ae8d8eec494
|
Rust
|
rnleach/sounding-analysis
|
/src/precip_type/nssl.rs
|
UTF-8
| 8,568 | 3.125 | 3 |
[
"MIT"
] |
permissive
|
//! This module implements the NSSL Precip Type algorithm.
use crate::{
error::{AnalysisError, Result},
precip_type::{is_drizzler, PrecipType},
sounding::Sounding,
};
use itertools::izip;
use metfor::{Celsius, Meters};
/// Analyze a sounding using the NSSL algorithm for precipitation type.
///
/// This algorithm also analyzes wet snow vs snow, but the precip codes we have in this module
/// do not allow that distinction, so wet snow will be analyzed as snow. It also may analyze mixed
/// freezing rain and ice pellets, for which we have no code. In that case we will analyze freezing
/// rain since that is generally considered the more severe weather type.
///
/// In addition to the NSSL algorithm if the type of the sounding is type 1 - 4 (i.e. the surface
/// wet bulb temperature is below 3C) and the RH is below 80% in the dendritic layer, then an
/// appropriate drizzle type is selected. If the surface wet bulb is warm enough, there is nothing
/// to prevent warm rain processes from generating rain so it is impossible to tell the difference
/// between drizzle and rain.
///
/// Since the sounding generally doesn't come with information convective or stratiform and the
/// amount of precipitation, this function can only determine the phase (ice or liquid) and whether
/// it is likely to freeze once it reaches the surface (eg freezing rain). So all returned weather
/// codes will assume stratiform conditions and a light intensity.
pub fn nssl_precip_type(snd: &Sounding) -> Result<PrecipType> {
let n_type = analyze_nssl_type(snd)?;
let mut p_type = match n_type {
NsslType::WarmSfcRain => PrecipType::LightRain,
NsslType::One => PrecipType::LightSnow,
NsslType::Two { h0 } => analyze_nssl_type_2(h0),
NsslType::Three { tw_max, tw_min } => analyze_nssl_type_3(tw_max, tw_min),
NsslType::Four { tw_max, tw_min } => analyze_nssl_type_4(tw_max, tw_min),
};
if is_drizzler(snd) {
match n_type {
NsslType::WarmSfcRain => {}
NsslType::One => p_type = PrecipType::LightFreezingDrizzle,
NsslType::Two { .. } => {}
NsslType::Three { .. } => {
if p_type == PrecipType::LightRain {
p_type = PrecipType::LightDrizzle;
} else {
p_type = PrecipType::LightFreezingDrizzle;
}
}
NsslType::Four { .. } => p_type = PrecipType::LightFreezingDrizzle,
}
}
Ok(p_type)
}
#[derive(Debug)]
enum NsslType {
WarmSfcRain,
One,
Two { h0: Meters },
Three { tw_max: Celsius, tw_min: Celsius },
Four { tw_max: Celsius, tw_min: Celsius },
}
fn analyze_nssl_type(snd: &Sounding) -> Result<NsslType> {
let sfc_wet_bulb = snd
.wet_bulb_profile()
.iter()
.cloned()
.filter_map(|opt_val| opt_val.into_option())
.next()
.ok_or(AnalysisError::MissingValue)?;
if sfc_wet_bulb >= Celsius(3.0) {
return Ok(NsslType::WarmSfcRain);
}
let wbzs = crate::wet_bulb_zero_levels(snd)?;
let n_type = if sfc_wet_bulb > Celsius(0.0) {
// Handle type 2 and type 3
// There should only be 1 or 3 WBZ levels, but weird stuff happens, so lets handle an above
// freezing sfc wet bulb and 2 crossings the same as 1 crossing.
if wbzs.len() <= 2 {
// Type 2
let h0: Meters = wbzs[0]
.height
.into_option()
.ok_or(AnalysisError::MissingValue)?;
let h_surface = snd
.station_info()
.elevation()
.into_option()
.ok_or(AnalysisError::MissingValue)?;
let h0 = h0 - h_surface;
NsslType::Two { h0 }
} else {
assert!(wbzs.len() >= 3);
// Type 3
let h2: Meters = wbzs[0]
.height
.into_option()
.ok_or(AnalysisError::MissingValue)?;
let h1: Meters = wbzs[1]
.height
.into_option()
.ok_or(AnalysisError::MissingValue)?;
let h0: Meters = wbzs[2]
.height
.into_option()
.ok_or(AnalysisError::MissingValue)?;
let (tw_max, tw_min) = izip!(snd.wet_bulb_profile(), snd.height_profile())
.filter(|(wb, h)| wb.is_some() && h.is_some())
.map(|(wb, h)| (wb.unpack(), h.unpack()))
.skip_while(|(_, h)| *h <= h2)
.take_while(|(_, h)| *h <= h0)
.fold((None, None), |acc, (wb, h)| {
let (mut tw_max, mut tw_min) = acc;
if h < h1 {
if let Some(min_val) = tw_min {
if wb < min_val {
tw_min = Some(wb);
}
} else {
tw_min = Some(wb);
}
} else {
if let Some(max_val) = tw_max {
if wb > max_val {
tw_max = Some(wb);
}
} else {
tw_max = Some(wb);
}
}
(tw_max, tw_min)
});
let tw_max = tw_max.ok_or(AnalysisError::MissingValue)?;
let tw_min = tw_min.ok_or(AnalysisError::MissingValue)?;
NsslType::Three { tw_max, tw_min }
}
} else {
// Handle type 1 and type 4
if wbzs.len() <= 1 {
// I suppose the WB could start below freezing and jump above it with the
// wet_bulb_zero_levels function above, but that would mean it was above freezing at
// 500 hPa and below freezing somewhere below it. Which would be REALLY weird, but
// that's why I look at the only 1 WBZ level case.
NsslType::One
} else {
assert!(wbzs.len() >= 2);
let h1: Meters = wbzs[0]
.height
.into_option()
.ok_or(AnalysisError::MissingValue)?;
let h0: Meters = wbzs[1]
.height
.into_option()
.ok_or(AnalysisError::MissingValue)?;
let (tw_max, tw_min) = izip!(snd.wet_bulb_profile(), snd.height_profile())
.filter(|(wb, h)| wb.is_some() && h.is_some())
.map(|(wb, h)| (wb.unpack(), h.unpack()))
.take_while(|(_, h)| *h <= h0)
.fold((None, None), |acc, (wb, h)| {
let (mut tw_max, mut tw_min) = acc;
if h < h1 {
if let Some(min_val) = tw_min {
if wb < min_val {
tw_min = Some(wb);
}
} else {
tw_min = Some(wb);
}
} else {
if let Some(max_val) = tw_max {
if wb > max_val {
tw_max = Some(wb);
}
} else {
tw_max = Some(wb);
}
}
(tw_max, tw_min)
});
let tw_max = tw_max.ok_or(AnalysisError::MissingValue)?;
let tw_min = tw_min.ok_or(AnalysisError::MissingValue)?;
NsslType::Four { tw_max, tw_min }
}
};
Ok(n_type)
}
fn analyze_nssl_type_2(h0: Meters) -> PrecipType {
if h0 < Meters(1000.0) {
PrecipType::LightSnow
} else {
PrecipType::LightRain
}
}
fn analyze_nssl_type_3(tw_max: Celsius, tw_min: Celsius) -> PrecipType {
if tw_max >= Celsius(0.0) && tw_max < Celsius(2.0) && tw_min < Celsius(-5.0) {
PrecipType::LightIcePellets
} else {
PrecipType::LightRain
}
}
fn analyze_nssl_type_4(tw_max: Celsius, tw_min: Celsius) -> PrecipType {
if tw_max > Celsius(2.0) && tw_min >= Celsius(-5.0) {
PrecipType::LightFreezingRain
} else if tw_max < Celsius(2.0) && tw_min < Celsius(-5.0) {
PrecipType::LightIcePellets
} else {
// This should be FZRA mixed with IP, but we don't have that option.
PrecipType::LightFreezingRain
}
}
| true |
6aa8a2b23894c8439b541cdb18941a1b5a0d5c02
|
Rust
|
achanda/rust-ndarray
|
/src/iterators.rs
|
UTF-8
| 10,212 | 3.15625 | 3 |
[
"MIT",
"Apache-2.0"
] |
permissive
|
use std::marker;
use super::{Dimension, Ix, Ixs};
use super::{Elements, ElementsRepr, ElementsBase, ElementsBaseMut, ElementsMut, Indexed, IndexedMut};
use super::{
ArrayView,
ArrayViewMut,
};
/// Base for array iterators
///
/// Iterator element type is `&'a A`.
pub struct Baseiter<'a, A: 'a, D> {
// Can have pub fields because it is not itself pub.
pub ptr: *mut A,
pub dim: D,
pub strides: D,
pub index: Option<D>,
pub life: marker::PhantomData<&'a A>,
}
impl<'a, A, D: Dimension> Baseiter<'a, A, D>
{
/// Creating a Baseiter is unsafe, because it can
/// have any lifetime, be immut or mut, and the
/// boundary and stride parameters need to be correct to
/// avoid memory unsafety.
///
/// It must be placed in the correct mother iterator to be safe.
///
/// NOTE: Mind the lifetime, it's arbitrary
#[inline]
pub unsafe fn new(ptr: *mut A, len: D, stride: D) -> Baseiter<'a, A, D>
{
Baseiter {
ptr: ptr,
index: len.first_index(),
dim: len,
strides: stride,
life: marker::PhantomData,
}
}
}
impl<'a, A, D: Dimension> Baseiter<'a, A, D>
{
#[inline]
pub fn next(&mut self) -> Option<*mut A>
{
let index = match self.index {
None => return None,
Some(ref ix) => ix.clone(),
};
let offset = Dimension::stride_offset(&index, &self.strides);
self.index = self.dim.next_for(index);
unsafe {
Some(self.ptr.offset(offset))
}
}
#[inline]
fn next_ref(&mut self) -> Option<&'a A>
{
unsafe { self.next().map(|p| &*p) }
}
#[inline]
fn next_ref_mut(&mut self) -> Option<&'a mut A>
{
unsafe { self.next().map(|p| &mut *p) }
}
fn size_hint(&self) -> usize
{
match self.index {
None => 0,
Some(ref ix) => {
let gone = self.dim.default_strides().slice().iter()
.zip(ix.slice().iter())
.fold(0, |s, (&a, &b)| s + a as usize * b as usize);
self.dim.size() - gone
}
}
}
}
impl<'a, A> Baseiter<'a, A, Ix>
{
#[inline]
fn next_back(&mut self) -> Option<*mut A>
{
let index = match self.index {
None => return None,
Some(ref ix) => ix.clone(),
};
self.dim -= 1;
let offset = Dimension::stride_offset(&self.dim, &self.strides);
if index == self.dim {
self.index = None;
}
unsafe {
Some(self.ptr.offset(offset))
}
}
#[inline]
fn next_back_ref(&mut self) -> Option<&'a A>
{
unsafe { self.next_back().map(|p| &*p) }
}
#[inline]
fn next_back_ref_mut(&mut self) -> Option<&'a mut A>
{
unsafe { self.next_back().map(|p| &mut *p) }
}
}
impl<'a, A, D: Clone> Clone for Baseiter<'a, A, D>
{
fn clone(&self) -> Baseiter<'a, A, D>
{
Baseiter {
ptr: self.ptr,
dim: self.dim.clone(),
strides: self.strides.clone(),
index: self.index.clone(),
life: self.life,
}
}
}
impl<'a, A, D: Clone> Clone for ElementsBase<'a, A, D>
{
fn clone(&self) -> ElementsBase<'a, A, D> { ElementsBase{inner: self.inner.clone()} }
}
impl<'a, A, D: Dimension> Iterator for ElementsBase<'a, A, D>
{
type Item = &'a A;
#[inline]
fn next(&mut self) -> Option<&'a A>
{
self.inner.next_ref()
}
fn size_hint(&self) -> (usize, Option<usize>)
{
let len = self.inner.size_hint();
(len, Some(len))
}
}
impl<'a, A> DoubleEndedIterator for ElementsBase<'a, A, Ix>
{
#[inline]
fn next_back(&mut self) -> Option<&'a A>
{
self.inner.next_back_ref()
}
}
impl<'a, A> ExactSizeIterator for ElementsBase<'a, A, Ix> { }
macro_rules! either {
($value:expr, $inner:ident => $result:expr) => (
match $value {
ElementsRepr::Slice(ref $inner) => $result,
ElementsRepr::Counted(ref $inner) => $result,
}
)
}
macro_rules! either_mut {
($value:expr, $inner:ident => $result:expr) => (
match $value {
ElementsRepr::Slice(ref mut $inner) => $result,
ElementsRepr::Counted(ref mut $inner) => $result,
}
)
}
impl<'a, A, D: Clone> Clone for Elements<'a, A, D>
{
fn clone(&self) -> Elements<'a, A, D> {
Elements {
inner: match self.inner {
ElementsRepr::Slice(ref iter) => ElementsRepr::Slice(iter.clone()),
ElementsRepr::Counted(ref iter) => ElementsRepr::Counted(iter.clone()),
}
}
}
}
impl<'a, A, D: Dimension> Iterator for Elements<'a, A, D>
{
type Item = &'a A;
#[inline]
fn next(&mut self) -> Option<&'a A> {
either_mut!(self.inner, iter => iter.next())
}
fn size_hint(&self) -> (usize, Option<usize>)
{
either!(self.inner, iter => iter.size_hint())
}
}
impl<'a, A> DoubleEndedIterator for Elements<'a, A, Ix>
{
#[inline]
fn next_back(&mut self) -> Option<&'a A> {
either_mut!(self.inner, iter => iter.next_back())
}
}
impl<'a, A> ExactSizeIterator for Elements<'a, A, Ix> { }
impl<'a, A, D: Dimension> Iterator for Indexed<'a, A, D>
{
type Item = (D, &'a A);
#[inline]
fn next(&mut self) -> Option<(D, &'a A)>
{
let index = match self.0.inner.index {
None => return None,
Some(ref ix) => ix.clone()
};
match self.0.inner.next_ref() {
None => None,
Some(p) => Some((index, p))
}
}
fn size_hint(&self) -> (usize, Option<usize>)
{
let len = self.0.inner.size_hint();
(len, Some(len))
}
}
impl<'a, A, D: Dimension> Iterator for ElementsMut<'a, A, D>
{
type Item = &'a mut A;
#[inline]
fn next(&mut self) -> Option<&'a mut A> {
either_mut!(self.inner, iter => iter.next())
}
fn size_hint(&self) -> (usize, Option<usize>) {
either!(self.inner, iter => iter.size_hint())
}
}
impl<'a, A> DoubleEndedIterator for ElementsMut<'a, A, Ix>
{
#[inline]
fn next_back(&mut self) -> Option<&'a mut A> {
either_mut!(self.inner, iter => iter.next_back())
}
}
impl<'a, A, D: Dimension> Iterator for ElementsBaseMut<'a, A, D>
{
type Item = &'a mut A;
#[inline]
fn next(&mut self) -> Option<&'a mut A>
{
self.inner.next_ref_mut()
}
fn size_hint(&self) -> (usize, Option<usize>)
{
let len = self.inner.size_hint();
(len, Some(len))
}
}
impl<'a, A> DoubleEndedIterator for ElementsBaseMut<'a, A, Ix>
{
#[inline]
fn next_back(&mut self) -> Option<&'a mut A>
{
self.inner.next_back_ref_mut()
}
}
impl<'a, A, D: Dimension> Iterator for IndexedMut<'a, A, D>
{
type Item = (D, &'a mut A);
#[inline]
fn next(&mut self) -> Option<(D, &'a mut A)>
{
let index = match self.0.inner.index {
None => return None,
Some(ref ix) => ix.clone()
};
match self.0.inner.next_ref_mut() {
None => None,
Some(p) => Some((index, p))
}
}
fn size_hint(&self) -> (usize, Option<usize>)
{
let len = self.0.inner.size_hint();
(len, Some(len))
}
}
/// An iterator that traverses over all dimensions but the innermost,
/// and yields each inner row.
pub struct InnerIter<'a, A: 'a, D> {
inner_len: Ix,
inner_stride: Ixs,
iter: Baseiter<'a, A, D>,
}
pub fn new_outer<A, D>(mut v: ArrayView<A, D>) -> InnerIter<A, D>
where D: Dimension,
{
if v.shape().len() == 0 {
InnerIter {
inner_len: 1,
inner_stride: 1,
iter: v.into_base_iter(),
}
} else {
// Set length of innerest dimension to 1, start iteration
let ndim = v.shape().len();
let len = v.shape()[ndim - 1];
let stride = v.strides()[ndim - 1];
v.dim.slice_mut()[ndim - 1] = 1;
InnerIter {
inner_len: len,
inner_stride: stride,
iter: v.into_base_iter(),
}
}
}
impl<'a, A, D> Iterator for InnerIter<'a, A, D>
where D: Dimension,
{
type Item = ArrayView<'a, A, Ix>;
fn next(&mut self) -> Option<Self::Item> {
self.iter.next().map(|ptr| {
let view = ArrayView {
data: &[],
ptr: ptr,
dim: self.inner_len,
strides: self.inner_stride as Ix,
};
view
})
}
}
// NOTE: InnerIterMut is a mutable iterator and must not expose aliasing
// pointers. Due to this we use an empty slice for the raw data (it's unused
// anyway).
/// An iterator that traverses over all dimensions but the innermost,
/// and yields each inner row (mutable).
pub struct InnerIterMut<'a, A: 'a, D> {
inner_len: Ix,
inner_stride: Ixs,
iter: Baseiter<'a, A, D>,
}
pub fn new_outer_mut<A, D>(mut v: ArrayViewMut<A, D>) -> InnerIterMut<A, D>
where D: Dimension,
{
if v.shape().len() == 0 {
InnerIterMut {
inner_len: 1,
inner_stride: 1,
iter: v.into_base_iter(),
}
} else {
// Set length of innerest dimension to 1, start iteration
let ndim = v.shape().len();
let len = v.shape()[ndim - 1];
let stride = v.strides()[ndim - 1];
v.dim.slice_mut()[ndim - 1] = 1;
InnerIterMut {
inner_len: len,
inner_stride: stride,
iter: v.into_base_iter(),
}
}
}
impl<'a, A, D> Iterator for InnerIterMut<'a, A, D>
where D: Dimension,
{
type Item = ArrayViewMut<'a, A, Ix>;
fn next(&mut self) -> Option<Self::Item> {
self.iter.next().map(|ptr| {
let view = ArrayViewMut {
data: &mut [],
ptr: ptr,
dim: self.inner_len,
strides: self.inner_stride as Ix,
};
view
})
}
}
| true |
7554409905283fd4013ab7e341fbd8c5225f9434
|
Rust
|
libcala/cargo-cala
|
/cargo-gsp/src/file.rs
|
UTF-8
| 3,994 | 2.5625 | 3 |
[
"MIT"
] |
permissive
|
// bin/file.rs
// Graphical Software Packager
// Copyright 2017 (c) Aldaron's Tech
// Copyright 2017 (c) Jeron Lau
// Licensed under the MIT LICENSE
use file;
use std::fs;
use std::io::prelude::*;
use std::path::Path;
pub enum PathType {
Folder,
File,
}
pub fn save<P: AsRef<Path>, B: AsRef<[u8]>>(name: P, data: B) -> () {
let path = name.as_ref();
let parent = path.parent().unwrap();
if parent.exists() == false {
file::mkdir(parent);
}
fs::File::create(path)
.unwrap()
.write_all(data.as_ref())
.unwrap();
}
pub fn load<P: AsRef<Path>>(name: P) -> Vec<u8> {
let mut file = fs::File::open(name).unwrap();
let mut contents = Vec::new();
file.read_to_end(&mut contents).unwrap();
contents
}
pub fn rm<P: AsRef<Path>>(path: P) {
fs::remove_file(path).unwrap();
}
pub fn rmdir<P: AsRef<Path>>(path: P) {
fs::remove_dir_all(path).unwrap();
}
pub fn mkdir<P: AsRef<Path>>(path: P) {
fs::create_dir_all(path).unwrap();
}
// Because: https://doc.rust-lang.org/std/fs/fn.rename.html Platform-Specifc...
#[cfg(target_os = "linux")]
fn mvto_ll<P: AsRef<Path>>(old: P, new: P) {
file::rmdir(&new);
file::mkdir(&new);
fs::rename(old, new).unwrap();
}
/// Move or rename a file ( change it's path ).
pub fn mvto<P: AsRef<Path>>(old: P, new: P) {
mvto_ll(old, new);
}
///
pub fn get_permissions<P: AsRef<Path>>(name: P) -> fs::Permissions {
let file = fs::File::open(name).unwrap();
file.metadata().unwrap().permissions()
}
///
pub fn set_permissions<P: AsRef<Path>>(name: P, permissions: fs::Permissions) -> () {
let file = fs::File::open(name).unwrap();
file.set_permissions(permissions).unwrap()
}
// Remove first folder in relative path
fn fnrm_first<P: AsRef<Path>>(input: P) -> String {
let input = input.as_ref().to_str().unwrap();
let index = input.find('/').unwrap();
let mut input = input.to_string();
let t: String = input.drain(index + 1..).collect();
t
}
pub fn copy<P: AsRef<Path>>(src: P, dst: P) -> Result<(), String> {
let src = src.as_ref();
let dst = dst.as_ref();
if let Some(pt) = path_type(src) {
match pt {
PathType::File => {
let permissions = get_permissions(src);
let data = load(src);
save(dst, data.as_slice());
set_permissions(dst, permissions);
Ok(())
}
PathType::Folder => {
if let Ok(dir_iter) = fs::read_dir(src) {
for entry in dir_iter {
if let Ok(entry) = entry {
let path = entry.path();
let apnd = fnrm_first(&path);
let dest = dst.join(&apnd);
file::copy(path, dest).unwrap();
} else {
return Err("intermitten\
t io"
.to_string());
}
}
Ok(())
} else {
Err(format!(
"Couldn't copy folder {:?} \
because it lacks read \
permission",
src
))
}
}
}
} else {
Err(format!("Couldn't copy {:?} because it doesn't exist.", src))
}
}
pub fn get_exists(name: &str) -> bool {
Path::new(name).exists()
}
pub fn path_type<P: AsRef<Path>>(path: P) -> Option<PathType> {
let path = path.as_ref();
if path.exists() == false {
None
} else if path.is_file() == true {
Some(PathType::File)
} else if path.is_dir() == true {
Some(PathType::Folder)
} else {
panic!(
"Filesystem contains mysterious entity (Not a file or a \
folder)!"
);
}
}
| true |
98d5b4cba2d439dad21487018078b7b8ba1ad0c6
|
Rust
|
mislav-markovic/advent-of-code
|
/aoc-22/src/days/day11.rs
|
UTF-8
| 9,575 | 2.6875 | 3 |
[] |
no_license
|
use crate::day_exec::DayExecutor;
use std::{
collections::{HashMap, VecDeque},
fmt::Display,
str::FromStr,
};
pub struct Day11;
impl DayExecutor for Day11 {
fn exec_part1(&self, input: String) -> Box<dyn Display> {
Box::new(format!("Monkey business score: {}", solve_part1(&input)))
}
fn exec_part2(&self, input: String) -> Box<dyn Display> {
Box::new(format!("Monkey business score: {}", solve_part2(&input)))
}
}
fn solve_part1(input: &str) -> u128 {
let mut group = get_monkey_group_from_input(input);
group.relief_adujstment = Box::new(|i| i / 3);
for _ in 0..20 {
group.play_round();
}
let mut num_of_inspects = group.inspect_counter.values().collect::<Vec<_>>();
num_of_inspects.sort();
let last = num_of_inspects.pop().unwrap();
let second_to_last = num_of_inspects.pop().unwrap();
last * second_to_last
}
fn solve_part2(input: &str) -> u128 {
let mut group = get_monkey_group_from_input(input);
let monkey_divisors = group
.monkey_items
.values()
.map(|(m, _)| m.tests_by)
.collect::<Vec<_>>();
let adjustment_val = lcmm(&monkey_divisors);
group.relief_adujstment = Box::new(move |i| i % adjustment_val);
for _ in 0..10000 {
group.play_round();
}
let mut num_of_inspects = group.inspect_counter.values().collect::<Vec<_>>();
num_of_inspects.sort();
let last = num_of_inspects.pop().unwrap();
let second_to_last = num_of_inspects.pop().unwrap();
last * second_to_last
}
fn lcmm(args: &[u128]) -> u128 {
args.iter().cloned().reduce(|a, b| lcm(a, b)).unwrap()
}
fn lcm(a: u128, b: u128) -> u128 {
a / gcd(a, b) * b
}
fn gcd(mut a: u128, mut b: u128) -> u128 {
while b > 0 {
let t = b;
b = a % b;
a = t;
}
a
}
fn get_monkey_group_from_input(input: &str) -> MonkeyGroup {
input
.parse::<MonkeyGroup>()
.expect("Failed to parse monkey group")
}
type MonkeyId = u128;
#[derive(Debug)]
struct Item(u128);
struct Monkey {
operation: Box<dyn Fn(u128) -> u128>,
test: Box<dyn Fn(u128) -> bool>,
test_success_target: MonkeyId,
test_failure_target: MonkeyId,
tests_by: u128,
}
impl Monkey {
fn new<OpF, TestF>(
op: OpF,
test: TestF,
test_success_target: MonkeyId,
test_failure_target: MonkeyId,
tests_by: u128,
) -> Self
where
OpF: Fn(u128) -> u128 + 'static,
TestF: Fn(u128) -> bool + 'static,
{
let operation = Box::new(op);
let test = Box::new(test);
Self {
operation,
test,
test_success_target,
test_failure_target,
tests_by,
}
}
fn inspect(
&self,
mut item: Item,
relief_adjustment: impl Fn(u128) -> u128,
) -> (Item, MonkeyId) {
item.0 = (self.operation)(item.0);
item.0 = (relief_adjustment)(item.0);
let target = if (self.test)(item.0) {
self.test_success_target
} else {
self.test_failure_target
};
(item, target)
}
}
struct MonkeyTriplet(MonkeyId, Monkey, VecDeque<Item>);
#[derive(Debug)]
struct MonkeyParseError;
impl FromStr for MonkeyTriplet {
type Err = MonkeyParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut lines = s.lines();
let monkey_id_str = lines.next().ok_or(MonkeyParseError)?;
let starting_items_str = lines.next().ok_or(MonkeyParseError)?;
let operation_str = lines.next().ok_or(MonkeyParseError)?;
let test_str = lines.next().ok_or(MonkeyParseError)?;
let success_target_str = lines.next().ok_or(MonkeyParseError)?;
let failure_target_str = lines.next().ok_or(MonkeyParseError)?;
let monkey_id = monkey_id_str
.trim()
.trim_start_matches("Monkey")
.trim_end_matches(":")
.trim()
.parse::<MonkeyId>()
.map_err(|_| MonkeyParseError {})?;
let starting_items = starting_items_str
.trim()
.trim_start_matches("Starting items:")
.split(',')
.map(|s| s.trim().parse::<u128>().map(|v| Item(v)))
.collect::<Result<VecDeque<_>, _>>()
.map_err(|_| MonkeyParseError {})?;
let (_, formula) = operation_str.split_once('=').ok_or(MonkeyParseError)?;
let mut parts = formula.split_ascii_whitespace();
let lhs = parts.next().ok_or(MonkeyParseError)?;
let op = parts.next().ok_or(MonkeyParseError)?;
let rhs = parts.next().ok_or(MonkeyParseError)?;
let lhs = lhs.parse::<Variable>().map_err(|_| MonkeyParseError)?;
let op = op.parse::<Operand>().map_err(|_| MonkeyParseError)?;
let rhs = rhs.parse::<Variable>().map_err(|_| MonkeyParseError)?;
let operation = move |item: u128| op.calc(lhs.get_val(item), rhs.get_val(item));
let test_divisible_by =
test_str
.split_once("by")
.ok_or(MonkeyParseError)
.and_then(|(_, divider)| {
divider
.trim()
.parse::<u128>()
.map_err(|_| MonkeyParseError {})
})?;
let test = move |item: u128| (item % test_divisible_by) == 0;
let success_target_id = success_target_str
.trim()
.split_ascii_whitespace()
.last()
.ok_or(MonkeyParseError)
.and_then(|id_str| id_str.parse::<MonkeyId>().map_err(|_| MonkeyParseError {}))?;
let failure_target_id = failure_target_str
.trim()
.split_ascii_whitespace()
.last()
.ok_or(MonkeyParseError)
.and_then(|id_str| id_str.parse::<MonkeyId>().map_err(|_| MonkeyParseError {}))?;
let monkey = Monkey::new(
operation,
test,
success_target_id,
failure_target_id,
test_divisible_by,
);
Ok(MonkeyTriplet(monkey_id, monkey, starting_items))
}
}
#[derive(Debug)]
enum Operand {
Add,
Mul,
}
impl Operand {
fn calc(&self, lhs: u128, rhs: u128) -> u128 {
match self {
Operand::Add => lhs + rhs,
Operand::Mul => lhs * rhs,
}
}
}
struct OperandParseError;
impl FromStr for Operand {
type Err = OperandParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.trim() {
"*" => Ok(Self::Mul),
"+" => Ok(Self::Add),
_ => Err(OperandParseError),
}
}
}
#[derive(Debug)]
enum Variable {
Constant(u128),
Old,
}
impl Variable {
fn get_val(&self, current_val: u128) -> u128 {
match self {
Variable::Constant(constant_val) => *constant_val,
Variable::Old => current_val,
}
}
}
struct VariableParseError;
impl FromStr for Variable {
type Err = VariableParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let trimmed = s.trim();
if trimmed == "old" {
Ok(Self::Old)
} else {
trimmed
.parse::<u128>()
.map(|v| Self::Constant(v))
.map_err(|_| VariableParseError {})
}
}
}
struct MonkeyGroup {
monkey_items: HashMap<MonkeyId, (Monkey, VecDeque<Item>)>,
inspect_counter: HashMap<MonkeyId, u128>,
relief_adujstment: Box<dyn Fn(u128) -> u128>,
}
impl MonkeyGroup {
fn new(relief_adujstment: impl Fn(u128) -> u128 + 'static) -> Self {
Self {
monkey_items: HashMap::new(),
inspect_counter: HashMap::new(),
relief_adujstment: Box::new(relief_adujstment),
}
}
fn add_monkey(&mut self, to_add: MonkeyTriplet) {
self.monkey_items.insert(to_add.0, (to_add.1, to_add.2));
self.inspect_counter.insert(to_add.0, 0);
}
fn play_round(&mut self) {
let mut turn_order = self.monkey_items.keys().cloned().collect::<Vec<_>>();
turn_order.sort();
for monkey_id in turn_order {
self.play_turn(&monkey_id);
}
}
fn play_turn(&mut self, for_monkey: &MonkeyId) {
let (monkey, items) = self.monkey_items.get_mut(for_monkey).unwrap();
let mut thrown_items: Vec<(Item, MonkeyId)> = Vec::with_capacity(items.len());
while let Some(item) = items.pop_front() {
thrown_items.push(monkey.inspect(item, &self.relief_adujstment));
self.inspect_counter
.entry(*for_monkey)
.and_modify(|e| *e += 1)
.or_insert(1);
}
for (item, target) in thrown_items {
self.monkey_items
.entry(target)
.and_modify(|(_, items)| items.push_back(item));
}
}
}
#[derive(Debug)]
struct MonkeyGroupParseError;
impl FromStr for MonkeyGroup {
type Err = MonkeyGroupParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut group = Self::new(|i| i);
s.split("\n\n")
.map(|m| {
m.parse::<MonkeyTriplet>()
.map_err(|_| MonkeyGroupParseError)
})
.try_for_each(|m| -> Result<(), MonkeyGroupParseError> {
let inner = m?;
group.add_monkey(inner);
Ok(())
})?;
Ok(group)
}
}
| true |
50f84d11fdcb104c70b282ab89f2d8dcae02d97d
|
Rust
|
shyba/tcp-forwarding-a-language-battle
|
/rust/server.rs
|
UTF-8
| 2,540 | 2.921875 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
use std::io::{Listener, Acceptor,IoError, IoErrorKind};
use std::io::net::tcp::{TcpListener, TcpStream};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
static EXT_PORT: u16 = 8443;
static SSH_PORT: u16 = 22;
static SSL_PORT: u16 = 9443;
fn keep_copying(mut a: TcpStream, mut b: TcpStream, timedOut: Arc<AtomicBool>) {
a.set_read_timeout(Some(15*60*1000));
let mut buf = [0u8,..1024];
loop {
let read = match a.read(&mut buf) {
Err(ref err) => {
let other = timedOut.swap(true, Ordering::AcqRel);
if other {
// the other side also timed-out / errored, so lets go
drop(a);
drop(b);
return;
}
if err.kind == IoErrorKind::TimedOut {
continue;
}
// normal errors, just stop
drop(a);
drop(b);
return; // normal errors, stop
},
Ok(r) => r
};
timedOut.store(false, Ordering::Release);
match b.write(buf.slice_to(read)) {
Err(..) => {
timedOut.store(true, Ordering::Release);
drop(a);
drop(b);
return;
},
Ok(..) => ()
};
}
}
fn start_pipe(front: TcpStream, port: u16, header: Option<u8>) {
let mut back = match TcpStream::connect(("127.0.0.1", port)) {
Err(e) => {
println!("Error connecting: {}", e);
drop(front);
return;
},
Ok(b) => b
};
if header.is_some() {
match back.write_u8(header.unwrap()) {
Err(e) => {
println!("Error writing first byte: {}", e);
drop(back);
drop(front);
return;
},
Ok(..) => ()
}
}
let front_copy = front.clone();
let back_copy = back.clone();
let timedOut = Arc::new(AtomicBool::new(false));
let timedOut_copy = timedOut.clone();
spawn(move|| {
keep_copying(front, back, timedOut);
});
spawn(move|| {
keep_copying(back_copy, front_copy, timedOut_copy);
});
}
fn handle_new_connection(mut stream: TcpStream) {
stream.set_read_timeout(Some(3000));
let header: Option<u8> = match stream.read_byte() {
Err(..) => None,
Ok(b) => Some(b)
};
if header.is_some() && (header.unwrap() == 22 || header.unwrap() == 128) {
start_pipe(stream, SSL_PORT, header);
}
else {
start_pipe(stream, SSH_PORT, header);
}
}
fn main() {
let mut acceptor = TcpListener::bind(("127.0.0.1", EXT_PORT)).listen().unwrap();
println!("listening started, ready to accept");
for stream in acceptor.incoming() {
match stream {
Err(e) => println!("Strange connection broken: {}", e),
Ok(stream) => spawn(move|| {
// connection succeeded
handle_new_connection(stream);
})
}
}
drop(acceptor);
}
| true |
99780720dbf167f660e85125facd0c8a4204e557
|
Rust
|
bnicholson/rust-learning
|
/src/print.rs
|
UTF-8
| 474 | 3.5625 | 4 |
[] |
no_license
|
pub fn run() {
// Print to console
println!("Hello from the print.rs file");
println!("{2} {1} {0}",1,2,3);
// named arguments
println!("{name} like to play {activity}", name = "John", activity = "baseball");
// Placeholder traits
println!("Binary: {:b} Hex: {:x} Octal: {:o}",10,10,10);
// Debug trait
println!(" {:?} ", (12, true, "hello") );
// basic math
println!("10 + 10 = {}", 10 + 10 );
}
| true |
369567183b49a115dc371a452c39353722f79101
|
Rust
|
ysoftman/test_code
|
/rust/raw_string_literal/raw_string_literal.rs
|
UTF-8
| 675 | 3.65625 | 4 |
[
"MIT"
] |
permissive
|
// ysoftman
// raw string literal test
fn main() {
// 일반적인 스트링 사용시 double quotation 을 escape 해줘야 한다.
let s = "I'm ysoftman, ## __ \"hello\"".to_string();
println!("{}", s);
// r#""# 형식의 raw 스트링으로 사용할 수 있다.
let raw_s = r#"I'm ysoftman, ## __ "hello""#;
println!("{}", raw_s);
println!("{}", raw_s.to_string());
// json 등의 데이터를 raw 스트링을 처리하기에 좋다.
let json_s = r#"{
"name": "ysoftman",
"age": 30,
"fruits": [
"lemon",
"orange",
"apple"
]
}"#;
println!("{}", json_s);
}
| true |
ad2fe0104c3f1ade9bd5d30dd52a68c924acc656
|
Rust
|
kofmatsugen/aabb
|
/src/debug/system/collision_view.rs
|
UTF-8
| 4,358 | 2.546875 | 3 |
[] |
no_license
|
use crate::{
debug::traits::CollisionColor,
event::{ContactEvent, ContactEventChannel},
types::{Aabb, Vector},
Collision, Collisions,
};
use amethyst::{
core::{
math::{Point2, Point3, Vector3},
Transform,
},
ecs::{
Builder, Entity, Join, Read, ReadStorage, ReaderId, System, World, WorldExt, Write,
WriteStorage,
},
renderer::{debug_drawing::DebugLinesComponent, palette::rgb::Srgba, ActiveCamera},
};
use std::marker::PhantomData;
pub(crate) struct CollisionViewSystem<T>
where
T: 'static + Send + Sync,
{
debug_collisions: Entity,
contact_collisions: Entity,
reader: Option<ReaderId<ContactEvent<T>>>,
paramater: PhantomData<T>,
}
impl<T> CollisionViewSystem<T>
where
T: 'static + Send + Sync,
{
pub(crate) fn new(world: &mut World) -> Self {
CollisionViewSystem {
debug_collisions: world.create_entity().build(),
contact_collisions: world.create_entity().build(),
reader: None,
paramater: PhantomData,
}
}
}
impl<'s, T> System<'s> for CollisionViewSystem<T>
where
T: 'static + Send + Sync + CollisionColor,
{
type SystemData = (
WriteStorage<'s, DebugLinesComponent>,
ReadStorage<'s, Transform>,
ReadStorage<'s, Collisions<T>>,
Read<'s, ActiveCamera>,
Write<'s, ContactEventChannel<T>>,
);
fn run(
&mut self,
(mut debug_lines, transforms, collisions, camera, mut channel): Self::SystemData,
) {
if self.reader.is_none() == true {
self.reader = channel.register_reader().into();
}
let camera_z = camera
.entity
.and_then(|entity| transforms.get(entity))
.map(|transform| transform.translation().z - 1.);
if camera_z.is_none() == true {
return;
}
let position_z = camera_z.unwrap();
// 既存コリジョン
if let Ok(entry) = debug_lines.entry(self.debug_collisions) {
let debug = entry.or_insert(DebugLinesComponent::with_capacity(2048));
debug.clear();
for (c,) in (&collisions,).join() {
for Collision {
aabb,
position,
paramater,
..
} in c.collisions.iter()
{
let (r, g, b, a) = paramater.collision_color();
draw_aabb(debug, aabb, position, position_z, Srgba::new(r, g, b, a));
}
}
}
// 衝突判定検出点
let reader = self.reader.as_mut().unwrap();
if let Ok(entry) = debug_lines.entry(self.contact_collisions) {
let debug = entry.or_insert(DebugLinesComponent::with_capacity(2048));
debug.clear();
let color = Srgba::new(0., 1., 1., 1.);
for ContactEvent {
hit_center, delta, ..
} in channel.read(reader)
{
let radius = 30.;
// entity1
let position = Point3::new(hit_center.x, hit_center.y, position_z);
debug.add_circle_2d(position, radius, 100, color);
let delta = Vector3::new(delta.x, delta.y, position_z);
debug.add_direction(position, delta, color);
}
}
}
}
fn draw_aabb(
debug: &mut DebugLinesComponent,
aabb: &Aabb,
position: &Vector,
position_z: f32,
color: Srgba,
) {
let left_top = Point2::new(
position.x - aabb.half_extents().x,
position.y + aabb.half_extents().y,
);
let right_down = Point2::new(
position.x + aabb.half_extents().x,
position.y - aabb.half_extents().y,
);
debug.add_line(
Point3::new(position.x, position.y - 5., position_z),
Point3::new(position.x, position.y + 5., position_z),
color,
);
debug.add_line(
Point3::new(position.x - 5., position.y, position_z),
Point3::new(position.x + 5., position.y, position_z),
color,
);
debug.add_rectangle_2d(left_top, right_down, position_z, color);
}
| true |
072f8910ea58c7b31f7764407bd82e9201834d32
|
Rust
|
IThawk/rust-project
|
/rust-master/src/test/ui/consts/rfc-2203-const-array-repeat-exprs/migrate-fail.rs
|
UTF-8
| 721 | 2.640625 | 3 |
[
"MIT",
"LicenseRef-scancode-other-permissive",
"Apache-2.0",
"BSD-3-Clause",
"BSD-2-Clause",
"NCSA"
] |
permissive
|
// ignore-tidy-linelength
// ignore-compare-mode-nll
// compile-flags: -Z borrowck=migrate
#![feature(const_in_array_repeat_expressions)]
#![allow(warnings)]
// Some type that is not copyable.
struct Bar;
mod non_constants {
use Bar;
fn no_impl_copy_empty_value_multiple_elements() {
let x = None;
let arr: [Option<Bar>; 2] = [x; 2];
//~^ ERROR the trait bound `std::option::Option<Bar>: std::marker::Copy` is not satisfied [E0277]
}
fn no_impl_copy_value_multiple_elements() {
let x = Some(Bar);
let arr: [Option<Bar>; 2] = [x; 2];
//~^ ERROR the trait bound `std::option::Option<Bar>: std::marker::Copy` is not satisfied [E0277]
}
}
fn main() {}
| true |
8a1b574e72ec340e089f3dfcb260eb652e094b40
|
Rust
|
tigranmt/rust_presentation
|
/errorhandling/errorhandling.rs
|
UTF-8
| 1,073 | 3.609375 | 4 |
[] |
no_license
|
use std::path::Path;
use std::fs::File;
/*
enum Result<T,E>
{
Ok(T), //wrap workable instance, in case of a success
Err(E), //wrap error instance,message, ..etc , in case of a failure
}
pub enum Option<T>
{
None, //nothing to report
Some(T), //wrap some value
}
*/
fn main()
{
let file_path = Path::new("intro1.rs"); // construct Path instance
let mut file = match File::open(&file_path) // invoke Open(..) file and match returning Result<T> in-place
{
Ok(file) => file, //return file object
Err(err) => { //handle and report error
println!("Error while opening file: {}", err);
panic!(); //raise unhandled exception
}
};
}
/*fn main()
{
let file_path = Path::new("intro1.rs");
let mut file = File::open(&file_path).
expect(&format!("Error while opening file: {:?}", file_path));
}*/
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.