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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
1923441caf41ebc9cc15552893798631484f4d56
|
Rust
|
j-browne/advent-of-code
|
/2021/src/seven_segment_display.rs
|
UTF-8
| 4,434
| 3.21875
| 3
|
[] |
no_license
|
use std::collections::HashMap;
#[derive(Debug)]
pub struct Display {
signals: Vec<Signals>,
output: Vec<Signals>,
}
impl Display {
#[must_use]
pub fn new(s: &str) -> Self {
let mut it = s.split(" | ");
let signals = it
.next()
.unwrap()
.split_whitespace()
.map(Signals::new)
.collect();
let output = it
.next()
.unwrap()
.split_whitespace()
.map(Signals::new)
.collect();
Self { signals, output }
}
#[must_use]
pub fn output_uniques(&self) -> usize {
self.output
.iter()
.filter(|x| x.len() == 2 || x.len() == 4 || x.len() == 3 || x.len() == 7)
.count()
}
#[must_use]
pub fn output_value(&self) -> u32 {
let mut signal_to_num = HashMap::new();
let mut num_to_signal = HashMap::new();
// 1 is the only signal with 2 segments
let sig = self.signals.iter().find(|s| s.len() == 2).unwrap();
signal_to_num.insert(sig, 1);
num_to_signal.insert(1, sig);
// 4 is the only signal with 4 segments
let sig = self.signals.iter().find(|s| s.len() == 4).unwrap();
signal_to_num.insert(sig, 4);
num_to_signal.insert(4, sig);
// 7 is the only signal with 3 segments
let sig = self.signals.iter().find(|s| s.len() == 3).unwrap();
signal_to_num.insert(sig, 7);
num_to_signal.insert(7, sig);
// 8 is the only signal with 7 segments
let sig = self.signals.iter().find(|s| s.len() == 7).unwrap();
signal_to_num.insert(sig, 8);
num_to_signal.insert(8, sig);
// 6 is the only len 6 that doesn't contain all of 1
let sig = self
.signals
.iter()
.find(|s| s.len() == 6 && num_to_signal[&1].iter().any(|x| !s.contains(x)))
.unwrap();
signal_to_num.insert(sig, 6);
num_to_signal.insert(6, sig);
// 9 is the only len 6 that contains all of 4
let sig = self
.signals
.iter()
.find(|s| s.len() == 6 && num_to_signal[&4].iter().all(|x| s.contains(x)))
.unwrap();
signal_to_num.insert(sig, 9);
num_to_signal.insert(9, sig);
// 0 is the remaining len 6
let sig = self
.signals
.iter()
.find(|s| s.len() == 6 && s != &num_to_signal[&6] && s != &num_to_signal[&9])
.unwrap();
signal_to_num.insert(sig, 0);
num_to_signal.insert(0, sig);
// 3 is the only len 5 that contains all of 1
let sig = self
.signals
.iter()
.find(|s| s.len() == 5 && num_to_signal[&1].iter().all(|x| s.contains(x)))
.unwrap();
signal_to_num.insert(sig, 3);
num_to_signal.insert(3, sig);
// 5 is the only len 5 that 6 contains all of
let sig = self
.signals
.iter()
.find(|s| s.len() == 5 && s.iter().all(|x| num_to_signal[&6].contains(x)))
.unwrap();
signal_to_num.insert(sig, 5);
num_to_signal.insert(5, sig);
// 2 is the remaining len 5
let sig = self
.signals
.iter()
.find(|s| s.len() == 5 && s != &num_to_signal[&3] && s != &num_to_signal[&5])
.unwrap();
signal_to_num.insert(sig, 2);
num_to_signal.insert(2, sig);
self.output.iter().fold(0, |x, s| 10 * x + signal_to_num[s])
}
}
#[derive(Debug, PartialEq, Eq, Hash)]
#[allow(clippy::len_without_is_empty)]
pub struct Signals(pub [bool; 7]);
impl Signals {
#[must_use]
pub fn new(s: &str) -> Self {
let mut signals = [false; 7];
for c in s.chars() {
let idx = c as usize - 'a' as usize;
signals[idx] = true;
}
Self(signals)
}
#[must_use]
pub fn len(&self) -> usize {
self.0.iter().filter(|x| **x).count()
}
#[must_use]
pub const fn contains(&self, c: char) -> bool {
let idx = c as usize - 'a' as usize;
self.0[idx]
}
pub fn iter(&self) -> impl Iterator<Item = char> + '_ {
self.0
.iter()
.enumerate()
.filter_map(|(n, x)| x.then(|| (b'a' + u8::try_from(n).unwrap()) as char))
}
}
| true
|
68ad540da2d121eb0edcc5ab9de078f8bce8fe31
|
Rust
|
placrosse/drogue-device
|
/src/supervisor/interrupt_dispatcher.rs
|
UTF-8
| 1,687
| 2.734375
| 3
|
[
"Apache-2.0"
] |
permissive
|
use heapless::{consts::*, Vec};
use crate::actor::Actor;
use crate::interrupt::{Interrupt, InterruptContext};
use core::sync::atomic::Ordering;
pub(crate) trait ActiveInterrupt {
fn on_interrupt(&self);
}
impl<I: Actor + Interrupt> ActiveInterrupt for InterruptContext<I> {
fn on_interrupt(&self) {
// Mask this interrupt handler (not the entire IRQ) if this
// actor currently has an in-flight async block.
//
// This does indeed mean that this interrupt will never be
// processed. Perhaps we should just queue it up and deliver
// after the async block has completed?
if !self.actor_context.in_flight.load(Ordering::Acquire) {
self.actor_context.interrupt();
}
}
}
struct Interruptable {
irq: u8,
interrupt: &'static dyn ActiveInterrupt,
}
impl Interruptable {
pub fn new(interrupt: &'static dyn ActiveInterrupt, irq: u8) -> Self {
Self { irq, interrupt }
}
}
pub struct InterruptDispatcher {
interrupts: Vec<Interruptable, U16>,
}
impl InterruptDispatcher {
pub(crate) fn new() -> Self {
Self {
interrupts: Vec::new(),
}
}
pub(crate) fn activate_interrupt<I: ActiveInterrupt>(
&mut self,
interrupt: &'static I,
irq: u8,
) {
self.interrupts
.push(Interruptable::new(interrupt, irq))
.unwrap_or_else(|_| panic!("too many interrupts"));
}
#[doc(hidden)]
pub(crate) fn on_interrupt(&self, irqn: i16) {
for interrupt in self.interrupts.iter().filter(|e| e.irq == irqn as u8) {
interrupt.interrupt.on_interrupt();
}
}
}
| true
|
9295e3277951d89415fa18d28b249828160072f4
|
Rust
|
xayon40-12/wgpu_ray
|
/src/window.rs
|
UTF-8
| 3,837
| 2.640625
| 3
|
[] |
no_license
|
pub mod canvas;
use winit::{
event_loop::{ControlFlow, EventLoop},
event::{self,Event,WindowEvent},
};
pub trait Window {
fn new(sc_desc: &wgpu::SwapChainDescriptor, device: &wgpu::Device) -> Self;
fn update(&mut self, event: Event<()>, device: &wgpu::Device) -> Vec<wgpu::CommandBuffer>;
fn resize(&mut self, sc_desc: &wgpu::SwapChainDescriptor, device: &wgpu::Device) -> Option<wgpu::CommandBuffer>;
fn render(&mut self, frame: &wgpu::SwapChainOutput, device: &wgpu::Device) -> wgpu::CommandBuffer;
}
pub fn run<T: 'static + Window>() {
let events_loop = EventLoop::new();
let (window, size, surface) = {
let window = winit::window::Window::new(&events_loop).unwrap();
window.set_cursor_grab(true).expect("Could not grab cursor");
window.set_cursor_visible(false);
//window.set_fullscreen(Some(winit::window::Fullscreen::Borderless(window.current_monitor())));
let size = window.inner_size().to_physical(window.hidpi_factor());
let surface = wgpu::Surface::create(&window);
(window, size, surface)
};
let adapter = wgpu::Adapter::request(&wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::Default,
backends: wgpu::BackendBit::PRIMARY
}).unwrap();
let (device, mut queue) = adapter.request_device(&wgpu::DeviceDescriptor {
extensions: wgpu::Extensions {
anisotropic_filtering: false
},
limits: wgpu::Limits::default()
});
let mut sc_desc = wgpu::SwapChainDescriptor {
usage: wgpu::TextureUsage::OUTPUT_ATTACHMENT,
format: wgpu::TextureFormat::Bgra8UnormSrgb,
width: size.width.round() as u32,
height: size.height.round() as u32,
present_mode: wgpu::PresentMode::Vsync,
};
let mut swap_chain = device.create_swap_chain(&surface, &sc_desc);
let mut win = T::new(&sc_desc, &device);
events_loop.run(move |events, _, control_flow| {
*control_flow = if cfg!(feature = "metal-auto-capture") {
ControlFlow::Exit
} else {
ControlFlow::Poll
};
match &events {
Event::WindowEvent { event, .. } => match event {
WindowEvent::Resized(size) => {
let physical = size.to_physical(window.hidpi_factor());
sc_desc.width = physical.width.round() as u32;
sc_desc.height = physical.height.round() as u32;
swap_chain = device.create_swap_chain(&surface, &sc_desc);
let command_buf = win.resize(&sc_desc, &device);
if let Some(command_buf) = command_buf {
queue.submit(&[command_buf]);
window.request_redraw();
}
},
WindowEvent::KeyboardInput {
input:
event::KeyboardInput {
virtual_keycode: Some(event::VirtualKeyCode::Escape),
state: event::ElementState::Pressed,
..
},
..
}
| WindowEvent::CloseRequested => {
*control_flow = ControlFlow::Exit;
},
WindowEvent::RedrawRequested => {
let frame = swap_chain.get_next_texture();
let command_buf = win.render(&frame, &device);
queue.submit(&[command_buf]);
},
_ => {}
},
_ => {}
}
let command_bufs = win.update(events, &device);
if command_bufs.len() > 0 {
queue.submit(&command_bufs);
window.request_redraw();
}
});
}
| true
|
333add9265842385519d779800a29651c56a10a5
|
Rust
|
larntz/mft_muncher
|
/src/ntfs_attributes/standard_information.rs
|
UTF-8
| 2,618
| 2.828125
| 3
|
[] |
no_license
|
use crate::utils::*;
/**
reference: [https://flatcap.org/linux-ntfs/ntfs/attributes/standard_information.html](https://flatcap.org/linux-ntfs/ntfs/attributes/standard_information.html)
_NOTE:_ this attribute is always resident.
```
Offset Size OS Description
~ ~ Standard Attribute Header
0x00 8 C Time - File Creation
0x08 8 A Time - File Altered
0x10 8 M Time - MFT Changed
0x18 8 R Time - File Read
0x20 4 DOS File Permissions
0x24 4 Maximum Number of Versions
0x28 4 Version Number
0x2C 4 Class Id
0x30 4 2K Owner Id
0x34 4 2K Security Id
0x38 8 2K Quota Charged
0x40 8 2K Update Sequence Number (USN)
```
dos attributes
```
Flag Description
0x0001 Read-Only
0x0002 Hidden
0x0004 System
0x0020 Archive
0x0040 Device
0x0080 Normal
0x0100 Temporary
0x0200 Sparse File
0x0400 Reparse Point
0x0800 Compressed
0x1000 Offline
0x2000 Not Content Indexed
0x4000 Encrypted
```
**/
#[derive(Debug)]
#[repr(C)]
pub struct NtfsStandardInformationAttribute {
pub file_creation: u64, // 0x00
pub file_altered: u64, // 0x08
pub mft_altered: u64, // 0x10
pub file_read: u64, // 0x18
pub dos_attributes: u32, // 0x20
pub max_versions: u32, // 0x24
pub version: u32, // 0x28
pub class_id: u32, // 0x2c
pub owner_id: u32, // 0x30
pub security_id: u32, // 0x34
pub quota_charged: u64, // 0x38
pub usn: u64, // 0x40
}
impl NtfsStandardInformationAttribute {
pub fn new(bytes: &[u8]) -> Result<NtfsStandardInformationAttribute, std::io::Error> {
Ok(NtfsStandardInformationAttribute {
file_creation: u64::from_le_bytes(get_bytes_8(&bytes[0x00..])?),
file_altered: u64::from_le_bytes(get_bytes_8(&bytes[0x08..])?),
mft_altered: u64::from_le_bytes(get_bytes_8(&bytes[0x10..])?),
file_read: u64::from_le_bytes(get_bytes_8(&bytes[0x18..])?),
dos_attributes: u32::from_le_bytes(get_bytes_4(&bytes[0x20..])?),
max_versions: u32::from_le_bytes(get_bytes_4(&bytes[0x24..])?),
version: u32::from_le_bytes(get_bytes_4(&bytes[0x28..])?),
class_id: u32::from_le_bytes(get_bytes_4(&bytes[0x2c..])?),
owner_id: u32::from_le_bytes(get_bytes_4(&bytes[0x30..])?),
security_id: u32::from_le_bytes(get_bytes_4(&bytes[0x34..])?),
quota_charged: u64::from_le_bytes(get_bytes_8(&bytes[0x38..])?),
usn: u64::from_le_bytes(get_bytes_8(&bytes[0x40..])?),
})
}
}
| true
|
390f1c96fb21e0a2ba747f7d3f43111fd2c3822c
|
Rust
|
jdwile/advent-of-code
|
/2022/advent-of-code-2022/src/bin/09.rs
|
UTF-8
| 2,379
| 3.421875
| 3
|
[] |
no_license
|
use std::collections::HashSet;
#[aoc::main(09)]
pub fn main(input: &str) -> (usize, usize) {
solve(input)
}
#[aoc::test(09)]
pub fn test(input: &str) -> (String, String) {
let res = solve(input);
(res.0.to_string(), res.1.to_string())
}
fn solve(input: &str) -> (usize, usize) {
let p1 = part1(input);
let p2 = part2(input);
(p1, p2)
}
#[derive(Eq, PartialEq, Hash, Debug, Clone, Copy)]
struct Position {
x: i32,
y: i32,
}
impl Position {
fn is_touching(&self, other: Position) -> bool {
self.x.abs_diff(other.x) <= 1 && self.y.abs_diff(other.y) <= 1
}
fn is_covering(&self, other: Position) -> bool {
self.x == other.x && self.y == other.y
}
fn move_toward(&mut self, other: Position) {
if self.x.abs_diff(other.x) >= 1 && self.y.abs_diff(other.y) >= 1 {
self.x += (other.x - self.x).signum();
self.y += (other.y - self.y).signum();
} else if self.x.abs_diff(other.x) >= 1 {
self.x += (other.x - self.x).signum();
} else {
self.y += (other.y - self.y).signum();
}
}
}
fn generate_tail_history(rope_length: usize, input: &str) -> HashSet<Position> {
let mut rope: Vec<Position> = vec![Position { x: 0, y: 0 }; rope_length];
let mut tail_history = HashSet::<Position>::new();
tail_history.insert(rope[rope.len() - 1]);
input.lines().for_each(|line| {
let (dir, mag_str) = line.split_once(' ').unwrap();
let mag = mag_str.parse::<i32>().unwrap();
let mut dest = rope[0];
match dir {
_ if dir == "U" => dest.x += mag,
_ if dir == "D" => dest.x -= mag,
_ if dir == "L" => dest.y -= mag,
_ if dir == "R" => dest.y += mag,
_ => panic!("Shouldn't happen"),
};
while !rope[0].is_covering(dest) {
rope[0].move_toward(dest);
for i in 1..rope.len() {
let dest = rope[i - 1];
while !rope[i].is_touching(dest) {
rope[i].move_toward(dest);
tail_history.insert(rope[rope.len() - 1]);
}
}
}
});
tail_history
}
fn part1(input: &str) -> usize {
generate_tail_history(2, input).len()
}
fn part2(input: &str) -> usize {
generate_tail_history(10, input).len()
}
| true
|
9cfed41b28c9f28df26008ed1507e8e8634e2736
|
Rust
|
jaredly/veoluz
|
/src/state.rs
|
UTF-8
| 11,218
| 2.640625
| 3
|
[] |
no_license
|
use std::sync::Mutex;
use wasm_bindgen::prelude::*;
use web_sys::CanvasRenderingContext2d;
#[wasm_bindgen]
extern "C" {
pub type TimeoutId;
#[wasm_bindgen(js_name = "setTimeout")]
pub fn set_timeout_inner(cb: &JsValue, timeout: f64) -> TimeoutId;
#[wasm_bindgen(js_name = "clearTimeout")]
pub fn clear_timeout(id: &TimeoutId);
}
pub fn set_timeout<T: FnOnce() + 'static>(cb: T, timeout: f64) -> TimeoutId {
set_timeout_inner(&Closure::once_into_js(cb), timeout)
}
pub struct State {
pub hide_timeout: Option<TimeoutId>,
pub render_id: usize,
pub last_rendered: usize,
pub ctx: CanvasRenderingContext2d,
pub image_data: web_sys::ImageData,
pub config: shared::Config,
pub history: Vec<shared::Config>,
pub history_index: usize,
pub last_rendered_config: Option<shared::Config>,
pub buffer: Vec<u32>,
pub ui: crate::ui::UiState,
pub hist_canvas: Option<web_sys::HtmlCanvasElement>,
pub on_change: js_sys::Function,
pub workers: Vec<(web_sys::Worker, bool, Option<shared::messaging::Message>)>,
}
// umm I dunno if this is cheating or something
// I mean bad things could happen if I accessed the ctx
// from different threads
// but given that wasm doesn't yet have threads, it's probably fine.
unsafe impl Send for State {}
impl State {
pub fn new(config: shared::Config, on_change: js_sys::Function) -> Self {
State {
hide_timeout: None,
render_id: 0,
hist_canvas: None,
last_rendered: 0,
ctx: crate::ui::init(&config).expect("Unable to setup canvas"),
image_data: web_sys::ImageData::new_with_sw(
config.rendering.width as u32,
config.rendering.height as u32,
)
.expect("Can't make an imagedata"),
buffer: vec![0_u32; config.rendering.width * config.rendering.height],
workers: vec![],
ui: Default::default(),
history: vec![config.clone()],
history_index: 0,
last_rendered_config: None,
on_change,
config,
}
}
}
pub fn make_image_data(
config: &shared::Config,
bright: &[u32],
) -> Result<web_sys::ImageData, JsValue> {
let colored = shared::colorize(config, bright);
let mut clamped = wasm_bindgen::Clamped(colored.clone());
// let mut clamped = Clamped(state.buffer.clone());
let data = web_sys::ImageData::new_with_u8_clamped_array_and_sh(
wasm_bindgen::Clamped(clamped.as_mut_slice()),
config.rendering.width as u32,
config.rendering.height as u32,
)?;
Ok(data)
}
impl State {
pub fn reset_buffer(&mut self) {
self.buffer = vec![0_u32; self.config.rendering.width * self.config.rendering.height];
self.invalidate_past_renders();
}
pub fn add_worker(&mut self, worker: web_sys::Worker) {
self.workers.push((worker, false, None))
}
pub fn invalidate_past_renders(&mut self) {
self.render_id += 1;
self.last_rendered = self.render_id;
}
pub fn undo(&mut self) -> Result<(), JsValue> {
log!("Undo {} {}", self.history.len(), self.history_index);
if self.history_index == 0 {
if Some(&self.config) != self.history.last() {
self.history.push(self.config.clone());
}
}
self.history_index = (self.history_index + 1).min(self.history.len() - 1);
if let Some(config) = self
.history
.get(self.history.len() - self.history_index - 1)
{
self.config = config.clone();
self.async_render(false)?;
}
Ok(())
}
pub fn redo(&mut self) -> Result<(), JsValue> {
if self.history_index == 0 {
log!("nothing to redo");
return Ok(());
}
log!("redo");
self.history_index = (self.history_index - 1).max(0);
if let Some(config) = self
.history
.get(self.history.len() - self.history_index - 1)
{
self.config = config.clone();
self.async_render(false)?;
}
Ok(())
}
pub fn maybe_save_history(&mut self) {
log!("saving history");
// If the lastest is the same
if self.history_index == 0
&& self
.history
.last()
.map_or(false, |last| *last == self.config)
{
return;
}
if self.history_index != 0
&& self
.history
.get(self.history.len() - self.history_index - 1)
.map_or(false, |last| *last == self.config)
{
return;
}
// snip undone stuff
if self.history_index != 0 {
self.history = self.history[0..self.history.len() - self.history_index].to_vec();
self.history_index = 0;
}
// if self.history.last().map_or(true, |last| *last != self.config) {
self.history.push(self.config.clone());
if self.history.len() > 500 {
// trim to 500 len
self.history = self.history[self.history.len() - 500..].to_vec();
}
// }
}
pub fn handle_render(
&mut self,
worker: usize,
id: usize,
array: js_sys::Uint32Array,
) -> Result<(), JsValue> {
if id < self.last_rendered {
let (worker, busy, queued) = &mut self.workers[worker];
match queued {
None => {
// log!("Finished a thread");
*busy = false
}
Some(message) => {
// log!("Sending a new config to render");
worker.post_message(&JsValue::from_serde(message).unwrap())?;
*queued = None
}
}
// this is old data, disregard
return Ok(());
}
if id > self.last_rendered {
self.reset_buffer();
self.last_rendered = id;
}
let mut bright = vec![0_u32; self.config.rendering.width * self.config.rendering.height];
array.copy_to(&mut bright);
for i in 0..bright.len() {
self.buffer[i] += bright[i];
}
self.image_data = make_image_data(&self.config, &self.buffer)?;
// crate::ui::use_ui(|ui| {
// crate::ui::draw(ui, &self)
// });
// self.ctx.put_image_data(&self.image_data, 0.0, 0.0)?;
let (worker, busy, queued) = &mut self.workers[worker];
match queued {
None => {
// log!("Finished a thread");
*busy = false
}
Some(message) => {
// log!("Sending a new config to render");
worker.post_message(&JsValue::from_serde(message).unwrap())?;
*queued = None
}
}
Ok(())
}
pub fn debug_render(&mut self) -> Result<(), JsValue> {
let brightness = shared::calculate::deterministic_calc(&self.config);
self.image_data = make_image_data(&self.config, &brightness)?;
self.ctx.put_image_data(&self.image_data, 0.0, 0.0)?;
Ok(())
}
pub fn clear(&mut self) {
self.ctx.clear_rect(
0.0,
0.0,
self.config.rendering.width as f64,
self.config.rendering.height as f64,
)
}
pub fn reexpose(&mut self) -> Result<(), JsValue> {
self.image_data = make_image_data(&self.config, &self.buffer)?;
// self.ctx.put_image_data(&self.image_data, 0.0, 0.0)?;
// crate::ui::use_ui(|ui| {
crate::ui::draw(&self);
// });
Ok(())
}
pub fn send_on_change(&self) {
let _res = self.on_change.call2(
&JsValue::null(),
&JsValue::from_serde(&self.config).unwrap(),
&JsValue::from_serde(&self.ui).unwrap(),
);
}
pub fn async_render(&mut self, small: bool) -> Result<(), JsValue> {
// log!("Async nreder folks");
match &self.last_rendered_config {
Some(config) => {
if *config == self.config {
return Ok(());
}
let mut old_config_with_new_exposure = config.clone();
old_config_with_new_exposure.rendering.exposure =
self.config.rendering.exposure.clone();
old_config_with_new_exposure.rendering.coloration =
self.config.rendering.coloration.clone();
// We've only changed settings that don't require recalculation
if old_config_with_new_exposure == self.config {
self.last_rendered_config = Some(self.config.clone());
self.send_on_change();
self.reexpose();
return Ok(());
} else {
log!("Not the same")
// log!("Not the same! {} vs {}", old_json, json)
}
}
_ => (),
}
// log!("Render new config");
// web_sys::console::log_1(&JsValue::from_serde(&self.config).unwrap());
self.send_on_change();
self.last_rendered_config = Some(self.config.clone());
self.render_id += 1;
let message = shared::messaging::Message {
config: self.config.clone(),
id: self.render_id,
// count: if small { 10_000 } else { 500_000 },
count: 200_000,
};
if self.workers.is_empty() {
return self.debug_render();
}
for (worker, busy, queued) in self.workers.iter_mut() {
if *busy {
// log!("Queueing up for a worker");
*queued = Some(message.clone())
} else {
*busy = true;
// log!("Sending a new config to render");
worker.post_message(&JsValue::from_serde(&message).unwrap())?;
}
}
Ok(())
}
}
lazy_static! {
static ref STATE: Mutex<Option<State>> = Mutex::new(None);
}
pub fn with_opt_state<F: FnOnce(&mut Option<State>)>(f: F) {
f(&mut STATE.lock().unwrap())
}
pub fn set_state(state: State) {
with_opt_state(|wrapper| *wrapper = Some(state))
}
pub fn has_state() -> bool {
match STATE.lock().unwrap().as_mut() {
Some(_) => true,
None => false,
}
}
pub fn with<R, F: FnOnce(&mut State) -> R>(f: F) -> R {
match STATE.lock().unwrap().as_mut() {
Some(mut state) => f(&mut state),
None => {
log!("!!! Error: tried to handle state, but no state found");
panic!("No state found, must set state first")
}
}
}
pub fn maybe_with<F: FnOnce(&mut State)>(f: F) {
match STATE.lock().unwrap().as_mut() {
Some(mut state) => f(&mut state),
None => (),
}
}
pub fn try_with<F: FnOnce(&mut State) -> Result<(), wasm_bindgen::prelude::JsValue>>(f: F) {
with(|state| crate::utils::try_log(|| f(state)))
}
| true
|
303409b79f66b1c21f72a86538af7a256c3a1776
|
Rust
|
denjalonso/sdk-node
|
/packages/worker/native/src/errors.rs
|
UTF-8
| 3,577
| 2.921875
| 3
|
[
"MIT"
] |
permissive
|
use neon::prelude::*;
use once_cell::sync::OnceCell;
/// An unhandled error while communicating with the server, considered fatal
pub static TRANSPORT_ERROR: OnceCell<Root<JsFunction>> = OnceCell::new();
/// Thrown after shutdown was requested as a response to a poll function, JS should stop polling
/// once this error is encountered
pub static SHUTDOWN_ERROR: OnceCell<Root<JsFunction>> = OnceCell::new();
/// Workflow did something Core did not expect, it should be immediately deleted from the cache
pub static WORKFLOW_ERROR: OnceCell<Root<JsFunction>> = OnceCell::new();
/// Something unexpected happened, considered fatal
pub static UNEXPECTED_ERROR: OnceCell<Root<JsFunction>> = OnceCell::new();
/// This is one of the ways to implement custom errors in neon.
/// Taken from the answer in GitHub issues: https://github.com/neon-bindings/neon/issues/714
pub trait CustomError {
fn construct<'a, C>(&self, cx: &mut C, args: Vec<Handle<JsValue>>) -> JsResult<'a, JsObject>
where
C: Context<'a>;
fn from_string<'a, C>(&self, cx: &mut C, message: String) -> JsResult<'a, JsObject>
where
C: Context<'a>;
fn from_error<'a, C, E>(&self, cx: &mut C, err: E) -> JsResult<'a, JsObject>
where
C: Context<'a>,
E: std::fmt::Display;
}
// Implement `CustomError` for ALL errors in a `OnceCell`. This only needs to be
// done _once_ even if other errors are added.
impl CustomError for OnceCell<Root<JsFunction>> {
fn construct<'a, C>(&self, cx: &mut C, args: Vec<Handle<JsValue>>) -> JsResult<'a, JsObject>
where
C: Context<'a>,
{
let error = self
.get()
.expect("Expected module to be initialized")
.to_inner(cx);
// Use `.construct` to call this as a constructor instead of a normal function
error.construct(cx, args)
}
fn from_string<'a, C>(&self, cx: &mut C, message: String) -> JsResult<'a, JsObject>
where
C: Context<'a>,
{
let args = vec![cx.string(message).upcast()];
self.construct(cx, args)
}
fn from_error<'a, C, E>(&self, cx: &mut C, err: E) -> JsResult<'a, JsObject>
where
C: Context<'a>,
E: std::fmt::Display,
{
self.from_string(cx, format!("{}", err))
}
}
/// This method should be manually called _once_ from JavaScript to initialize the module
/// It expects a single argument, an object with the various Error constructors.
/// This is a very common pattern in Neon modules.
pub fn register_errors(mut cx: FunctionContext) -> JsResult<JsUndefined> {
let mapping = cx.argument::<JsObject>(0)?;
let shutdown_error = mapping
.get(&mut cx, "ShutdownError")?
.downcast_or_throw::<JsFunction, FunctionContext>(&mut cx)?
.root(&mut cx);
let transport_error = mapping
.get(&mut cx, "TransportError")?
.downcast_or_throw::<JsFunction, FunctionContext>(&mut cx)?
.root(&mut cx);
let workflow_error = mapping
.get(&mut cx, "WorkflowError")?
.downcast_or_throw::<JsFunction, FunctionContext>(&mut cx)?
.root(&mut cx);
let unexpected_error = mapping
.get(&mut cx, "UnexpectedError")?
.downcast_or_throw::<JsFunction, FunctionContext>(&mut cx)?
.root(&mut cx);
TRANSPORT_ERROR.get_or_try_init(|| Ok(transport_error))?;
SHUTDOWN_ERROR.get_or_try_init(|| Ok(shutdown_error))?;
WORKFLOW_ERROR.get_or_try_init(|| Ok(workflow_error))?;
UNEXPECTED_ERROR.get_or_try_init(|| Ok(unexpected_error))?;
Ok(cx.undefined())
}
| true
|
7c976b8f3d3d1545df643bc091e9a81422347a3c
|
Rust
|
l1h3r/did_doc
|
/src/verification/method_query.rs
|
UTF-8
| 1,594
| 2.921875
| 3
|
[
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
use crate::verification::MethodIndex;
use crate::verification::MethodScope;
/// Specifies the conditions of a DID document method resolution query.
///
/// See `Document::resolve`.
#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct MethodQuery<'a> {
pub(crate) ident: MethodIndex<'a>,
pub(crate) scope: MethodScope,
}
impl<'a> MethodQuery<'a> {
/// Creates a new `MethodQuery`.
pub fn new<T>(ident: T) -> Self
where
T: Into<MethodIndex<'a>>,
{
Self::with_scope(ident, MethodScope::default())
}
/// Creates a new `MethodQuery` with the given `MethodScope`.
pub fn with_scope<T>(ident: T, scope: MethodScope) -> Self
where
T: Into<MethodIndex<'a>>,
{
Self {
ident: ident.into(),
scope,
}
}
}
impl<'a> From<&'a str> for MethodQuery<'a> {
fn from(other: &'a str) -> Self {
Self::new(other)
}
}
impl From<usize> for MethodQuery<'_> {
fn from(other: usize) -> Self {
Self::new(other)
}
}
impl<'a> From<(&'a str, MethodScope)> for MethodQuery<'a> {
fn from(other: (&'a str, MethodScope)) -> Self {
Self::with_scope(other.0, other.1)
}
}
impl From<(usize, MethodScope)> for MethodQuery<'_> {
fn from(other: (usize, MethodScope)) -> Self {
Self::with_scope(other.0, other.1)
}
}
impl<'a> From<(MethodIndex<'a>, MethodScope)> for MethodQuery<'a> {
fn from(other: (MethodIndex<'a>, MethodScope)) -> Self {
Self::with_scope(other.0, other.1)
}
}
impl<'a> From<MethodScope> for MethodQuery<'a> {
fn from(other: MethodScope) -> Self {
Self::with_scope(0, other)
}
}
| true
|
6804ece78377aa1fe381e7e0b66008829cda31a4
|
Rust
|
distil/diffus
|
/diffus/src/diffable_impls/string.rs
|
UTF-8
| 2,713
| 3.375
| 3
|
[
"Apache-2.0"
] |
permissive
|
use crate::{
edit::{self, string},
lcs, Diffable,
};
impl<'a> Diffable<'a> for str {
type Diff = Vec<string::Edit>;
fn diff(&'a self, other: &'a Self) -> edit::Edit<Self> {
let s = lcs::lcs(
|| self.chars(),
|| other.chars(),
self.chars().count(),
other.chars().count(),
)
.map(Into::into)
.collect::<Vec<_>>();
if s.iter().all(string::Edit::is_copy) {
edit::Edit::Copy(self)
} else {
edit::Edit::Change(s)
}
}
}
impl<'a> Diffable<'a> for String {
type Diff = <str as Diffable<'a>>::Diff;
fn diff(&'a self, other: &'a Self) -> edit::Edit<Self> {
match self.as_str().diff(other.as_str()) {
edit::Edit::Change(diff) => edit::Edit::Change(diff),
edit::Edit::Copy(_) => edit::Edit::Copy(self),
}
}
}
#[cfg(test)]
mod tests {
use crate::edit::{self, string};
#[test]
fn string() {
use super::Diffable;
let left = "XMJYAUZ".to_owned();
let right = "MZJAWXU".to_owned();
let diff = left.diff(&right);
if let edit::Edit::Change(diff) = diff {
assert_eq!(
diff.into_iter().collect::<Vec<_>>(),
vec![
string::Edit::Remove('X'),
string::Edit::Copy('M'),
string::Edit::Insert('Z'),
string::Edit::Copy('J'),
string::Edit::Remove('Y'),
string::Edit::Copy('A'),
string::Edit::Insert('W'),
string::Edit::Insert('X'),
string::Edit::Copy('U'),
string::Edit::Remove('Z')
]
);
} else {
unreachable!()
}
}
#[test]
fn str() {
use super::Diffable;
let left = "XMJYAUZ";
let right = "MZJAWXU";
let diff = left.diff(&right);
if let edit::Edit::Change(diff) = diff {
assert_eq!(
diff.into_iter().collect::<Vec<_>>(),
vec![
string::Edit::Remove('X'),
string::Edit::Copy('M'),
string::Edit::Insert('Z'),
string::Edit::Copy('J'),
string::Edit::Remove('Y'),
string::Edit::Copy('A'),
string::Edit::Insert('W'),
string::Edit::Insert('X'),
string::Edit::Copy('U'),
string::Edit::Remove('Z')
]
);
} else {
unreachable!()
}
}
}
| true
|
b1ce2b380c4de3a1a57fef8fadfac811baf8265a
|
Rust
|
joseluiscd/wpng
|
/src/lib.rs
|
UTF-8
| 3,655
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
pub mod raw;
pub mod transform;
use raw::{
RawPng, Header, Chunk, Palette, RawChunk
};
use std::borrow::Cow;
use flate2::bufread::{
ZlibDecoder,
ZlibEncoder,
};
use std::convert::TryFrom;
use std::path::Path;
pub type Scanline<'a> = Cow<'a, [u8]>;
#[derive(Debug)]
pub struct Png {
pub header: Header,
pub palette: Option<Vec<[u8; 3]>>,
pub data: Vec<u8>,
}
impl Png {
pub fn open(p: impl AsRef<Path>) -> Result<Self, std::io::Error> {
use std::io::Read;
use std::fs::File;
use std::convert::TryInto;
let mut buffer = Vec::new();
let f = File::open(p.as_ref())?.read_to_end(&mut buffer);
let (i, png) = RawPng::parse(&buffer).map_err(|_| std::io::Error::from(std::io::ErrorKind::Other))?;
let png: Png = png.try_into()?;
Ok(png)
}
pub fn iterate_rows<F>(&self, mut f: F)
where F: (FnMut(usize, &[u8])->())
{
let bitdepth = self.header.colour.bit_depth as usize;
let samples_per16 = 16 / bitdepth as usize; // Samples per 2bytes
let in_width = (self.header.width as usize / samples_per16 / 2) + 1; // +1 for filter type
for row in 0..self.header.height as usize {
let input = &self.data[in_width * row + 1 .. in_width * (row + 1)];
f(row, input)
}
}
pub fn iterate_rows_mut<F>(&mut self, mut f: F)
where F: (FnMut(usize, &mut [u8])->())
{
let bitdepth = self.header.colour.bit_depth as usize;
let samples_per16 = 16 / bitdepth as usize; // Samples per 2bytes
let in_width = (self.header.width as usize / samples_per16 / 2) + 1; // +1 for filter type
for row in 0..self.header.height as usize {
let buffer = &mut self.data[in_width * row + 1 .. in_width * (row + 1)];
f(row, buffer)
}
}
pub fn extract_pixels(&self) -> Vec<u8> {
let mut ret = Vec::<u8>::new();
self.iterate_rows(|row, buffer|{
ret.extend(buffer);
});
ret
}
}
impl <'a> TryFrom<RawPng<'a>> for Png {
type Error = std::io::Error;
fn try_from(raw: RawPng<'a>) -> Result<Self, Self::Error> {
use std::io::Read;
let RawPng(header, chunks) = raw;
let mut raw_data = Vec::new();
let mut data = Vec::new();
let mut palette = None;
for chunk in chunks {
match chunk {
Chunk::Palette(p) => {
palette.replace(p.into_owned());
},
Chunk::Data(d) => {
raw_data.extend(&*d);
},
_ => {}
}
}
let mut d = ZlibDecoder::new(&*raw_data);
d.read_to_end(&mut data)?;
Ok(Png{
header: header.into_owned(),
palette,
data
})
}
}
impl <'a> TryFrom<&'a Png> for RawPng<'a> {
type Error = std::io::Error;
fn try_from(p: &'a Png) -> Result<Self, Self::Error> {
use std::io::Read;
let Png{ header, palette, data } = p;
let mut chunks = Vec::<Chunk>::new();
if let Some(palette) = palette {
chunks.push(Chunk::Palette(Cow::from(palette)));
}
let mut r = ZlibEncoder::new(&**data, flate2::Compression::default());
let mut buf = vec![0; 4096];
loop {
let b = r.read(&mut buf)?;
if b == 0 {
break
}
chunks.push(Chunk::Data(Cow::Owned(buf[0..b].to_owned())));
}
Ok(RawPng(Cow::Borrowed(header), chunks))
}
}
| true
|
95713be297ba7c8b9a746a4ad96f07d8229b24b1
|
Rust
|
mesainner/easy-file
|
/src/protocols/smb.rs
|
UTF-8
| 1,141
| 2.71875
| 3
|
[] |
no_license
|
use std::io::Result;
use crate::file_opt::{FileOpt, FileAttr};
use crate::cache::disk::CacheFlag;
#[derive(Debug, Default)]
pub struct SmbClient {
field: u8,
read_offset: i64,
}
impl FileOpt for SmbClient {
fn open(path: &str, flag: Option<CacheFlag>) -> Self {
SmbClient{
field:1,
read_offset: 0,
}
}
fn get_attr(&self) -> Option<FileAttr>{
None
}
fn seek(&mut self, offset: i64) -> Result<()>{
self.read_offset = offset;
Ok(())
}
fn read(&mut self, len: i64) -> Option<Vec<u8>>{
None
}
fn read_to_file(&mut self, len: i64, path: &str) -> Result<()>{
Ok(())
}
fn is_exist(path: &str) -> bool{
true
}
fn write_from_file(&self, path: &str, progress: &mut f32) -> Result<()>{
Ok(())
}
fn write(&self, buffer: &[u8]) -> Result<()>{
Ok(())
}
fn close(&self) {
}
fn enumerate(path: &str) -> Result<Vec<String>> {
let ret: Vec<String> = Vec::new();
Ok(ret)
}
fn delete(path: &str) -> Result<()>{
Ok(())
}
}
| true
|
f65b4d21c84bf3c563c0bd2f3fcf0d3ab6847ad4
|
Rust
|
pseudobabble/rust_practice
|
/src/main.rs
|
UTF-8
| 709
| 3.875
| 4
|
[] |
no_license
|
fn reverse_string(phrase: &str) -> String {
phrase.chars().rev().collect()
}
fn bool_to_word(value: bool) -> &'static str {
match value {
true => {
"Yes"
}
false => {
"No"
}
}
}
fn main() {
let reversed = reverse_string("Hello World");
println!("{}", reversed);
let word_from_bool = bool_to_word(true);
println!("{}", word_from_bool)
}
#[cfg(test)]
pub mod tests {
#[test]
pub fn test_reverse_string() {
assert_eq!(reverse_string("world"), "dlrow");
}
#[test]
fn test_bool_to_word() {
assert_eq!(bool_to_word(true), "Yes");
assert_eq!(bool_to_word(false), "No");
}
}
| true
|
a7ad00545926b6277dab7d0cbaf9b963c133ccbf
|
Rust
|
tock/libtock-rs
|
/platform/src/termination.rs
|
UTF-8
| 587
| 3.03125
| 3
|
[
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
//! Definition of the Termination trait. The main() function (set using set_main!())
//! must return a type that implements Termination.
use crate::{ErrorCode, Syscalls};
pub trait Termination {
fn complete<S: Syscalls>(self) -> !;
}
impl Termination for () {
fn complete<S: Syscalls>(self) -> ! {
S::exit_terminate(0)
}
}
impl Termination for Result<(), ErrorCode> {
fn complete<S: Syscalls>(self) -> ! {
let exit_code = match self {
Ok(()) => 0,
Err(ec) => ec as u32,
};
S::exit_terminate(exit_code);
}
}
| true
|
c9b0ec89901a179bfe319411213ae6af7cd974bc
|
Rust
|
tahnok/advent2017
|
/rust/src/bin/day18_1.rs
|
UTF-8
| 2,586
| 2.96875
| 3
|
[] |
no_license
|
use std::collections::HashMap;
use std::io;
use std::io::Read;
fn main() {
let mut input = String::new();
let _ = io::stdin().read_to_string(&mut input);
println!("{}", solve(input.trim()));
}
fn val_or_reg(val: &str, register: &HashMap<&str, isize>) -> isize {
let maybe_val = val.parse();
match maybe_val {
Ok(number) => number,
Err(_) => *register.get(val).unwrap_or(&0)
}
}
fn solve(input: &str) -> isize {
let mut registers = HashMap::new();
let mut last_sound = 0;
let instructions: Vec<&str> = input.lines().collect();
let mut pc = 0;
loop {
let assembly = instructions[pc];
let mut step_size = 1;
let mut parts = assembly.split_whitespace();
let instruction = parts.next().unwrap();
let reg = parts.next().unwrap();
match instruction {
"set" => {
let val = val_or_reg(parts.next().unwrap(), ®isters);
registers.insert(reg, val);
},
"add" => {
let reg_val = *registers.get(reg).unwrap_or(&0);
let val = val_or_reg(parts.next().unwrap(), ®isters);
registers.insert(reg, reg_val + val);
},
"mul" => {
let reg_val = *registers.get(reg).unwrap_or(&0);
let val = val_or_reg(parts.next().unwrap(), ®isters);
registers.insert(reg, reg_val * val);
},
"mod" => {
let reg_val = *registers.get(reg).unwrap_or(&0);
let val = val_or_reg(parts.next().unwrap(), ®isters);
registers.insert(reg, reg_val % val);
},
"snd" => {
last_sound = *registers.get(reg).unwrap_or(&0);
},
"rcv" => {
let val = *registers.get(reg).unwrap_or(&0);
if val != 0 {
return last_sound;
}
},
"jgz" => {
let reg_val = *registers.get(reg).unwrap_or(&0);
if reg_val > 0 {
let val = val_or_reg(parts.next().unwrap(), ®isters);
step_size = val;
}
},
_ => panic!("unknown line {}", assembly)
}
let new_pc = (pc as isize) + step_size;
if new_pc > (instructions.len() as isize) {
break;
} else if new_pc < 0 {
break;
} else {
pc = new_pc as usize;
}
}
panic!("not found");
}
| true
|
5051c9cd67e8892ee5c9c649fedf425366373172
|
Rust
|
coriolinus/adventofcode-2015
|
/day21/src/loadout_generator.rs
|
UTF-8
| 2,305
| 3.359375
| 3
|
[] |
no_license
|
use crate::{
items::{Item, ItemType},
loadout::Loadout,
};
use itertools::Itertools;
/// Produce `None`, followed by `Some(t)` for each item in `ts`.
fn optional_iter<T: Clone>(
ts: impl Iterator<Item = T> + Clone,
) -> impl Iterator<Item = Option<T>> + Clone {
std::iter::once(None).chain(ts.map(Some))
}
/// Produce an iterator over sets of 0, 1, 2 distinct rings.
fn rings_iter<T: Ord + Copy>(
rings: impl Iterator<Item = T> + Clone,
) -> impl Iterator<Item = (Option<T>, Option<T>)> + Clone {
optional_iter(rings.clone())
.cartesian_product(optional_iter(rings))
.filter(|rings| match rings {
// given two rings, they must be distinct, and the more powerful must be on the right
// (for efficiency)
(Some(left), Some(right)) => left < right,
// discard left-hand-only cases for efficiency (redundant with right-hand-only)
(Some(_), None) => false,
// consider all the other cases
_ => true,
})
}
pub fn loadout_generator(items: &[Item]) -> impl '_ + Iterator<Item = Loadout> {
let filter_items =
|item_type: ItemType| items.iter().filter(move |item| item.itype == item_type);
let weapons = filter_items(ItemType::Weapon);
let armors = filter_items(ItemType::Armor);
let rings = filter_items(ItemType::Ring);
weapons
.into_iter()
.cartesian_product(optional_iter(armors))
.cartesian_product(rings_iter(rings.copied()))
.map(|((weapon, armor), (left_ring, right_ring))| Loadout {
weapon: *weapon,
armor: armor.copied(),
ring_l: left_ring,
ring_r: right_ring,
})
}
#[cfg(test)]
mod test {
use super::*;
use maplit::hashset;
use std::collections::HashSet;
#[test]
fn rings_iter_produces_correct_items() {
let rings: HashSet<_> = rings_iter(0..3).collect();
println!("{:#?}", rings);
assert_eq!(
rings,
hashset! {
(None, None),
(None, Some(0)),
(None, Some(1)),
(None, Some(2)),
(Some(0), Some(1)),
(Some(0), Some(2)),
(Some(1), Some(2)),
}
);
}
}
| true
|
ea01a259d651beddc65aa5e047661cd219e9cc29
|
Rust
|
snicmakino/practice-aoj
|
/src/3_2.rs
|
UTF-8
| 818
| 3.03125
| 3
|
[] |
no_license
|
use std::io::Read;
fn main() {
let mut buf = String::new();
std::io::stdin().read_to_string(&mut buf).unwrap();
let mut iter = buf.split_whitespace();
let n: i32 = iter.next().unwrap().parse().unwrap();
let mut a: Vec<i32> = (0..n)
.map(|_| iter.next().unwrap().parse().unwrap())
.collect();
// 処理
for i in 1..n {
println_array(&a);
let v = a[i as usize];
let mut j = i - 1;
while j >= 0 && a[j as usize] > v {
a[(j + 1) as usize] = a[j as usize];
j -= 1;
}
a[(j + 1) as usize] = v;
}
println_array(&a);
}
fn println_array(a: &Vec<i32>) {
println!(
"{}",
a.iter()
.map(|i| i.to_string())
.collect::<Vec<_>>()
.join(" ")
);
}
| true
|
186f7951737dd26e2f2bcd32af5e423d4b66ce31
|
Rust
|
obsc/rustlam
|
/src/scanner/standard.rs
|
UTF-8
| 711
| 3.265625
| 3
|
[] |
no_license
|
use std::io;
use std::collections::VecDeque;
pub struct StdScanner {
std: io::Stdin,
buf: VecDeque<String>,
}
impl StdScanner {
pub fn new() -> Self {
StdScanner{
std: io::stdin(),
buf: VecDeque::new(),
}
}
pub fn next_line(&mut self) -> Option<&String> {
let mut line = String::new();
match self.std.read_line(&mut line) {
Ok(bytes) if bytes > 0 => {
self.buf.push_back(line);
self.buf.back()
},
_ => None,
}
}
}
impl Iterator for StdScanner {
type Item = String;
fn next(&mut self) -> Option<String> {
self.buf.pop_front()
}
}
| true
|
5eb127a84dba08224929e11b0f69dd01601ab493
|
Rust
|
Rohesie/wallmount-slicer
|
/src/config.rs
|
UTF-8
| 2,386
| 2.8125
| 3
|
[] |
no_license
|
use anyhow::bail;
use yaml_rust::YamlLoader;
use std::path::Path;
use std::io::prelude::*;
use std::fs::File;
use anyhow::Result;
#[derive(Clone, PartialEq, Debug, Default)]
pub struct PrefHolder {
pub x_step: u32,
pub y_step: u32,
pub north_start_x: u32,
pub north_start_y: u32,
pub east_start_x: u32,
pub east_start_y: u32,
pub south_start_x: u32,
pub south_start_y: u32,
pub west_start_x: u32,
pub west_start_y: u32,
}
pub fn load_configs(caller_path: String) -> Result<PrefHolder> {
let config_path;
let last_slash = caller_path.rfind(|c| c == '/' || c == '\\');
if last_slash != None {
config_path = caller_path[..last_slash.unwrap()].to_string();
} else {
config_path = ".".to_string();
};
let path = Path::new(&config_path).join("config.yaml");
let mut file = File::open(path)?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
let docs = YamlLoader::load_from_str(&contents).unwrap();
let doc = &docs[0];
let x_step = read_necessary_u32_config(&doc, "x_step")?;
let y_step = read_necessary_u32_config(&doc, "y_step")?;
let north_start_x = read_necessary_u32_config(&doc, "north_start_x")?;
let north_start_y = read_necessary_u32_config(&doc, "north_start_y")?;
let east_start_x = read_necessary_u32_config(&doc, "east_start_x")?;
let east_start_y = read_necessary_u32_config(&doc, "east_start_y")?;
let south_start_x = read_necessary_u32_config(&doc, "south_start_x")?;
let south_start_y = read_necessary_u32_config(&doc, "south_start_y")?;
let west_start_x = read_necessary_u32_config(&doc, "west_start_x")?;
let west_start_y = read_necessary_u32_config(&doc, "west_start_y")?;
return Ok(PrefHolder {
x_step,
y_step,
north_start_x,
north_start_y,
east_start_x,
east_start_y,
south_start_x,
south_start_y,
west_start_x,
west_start_y,
})
}
pub fn read_necessary_u32_config(source: &yaml_rust::yaml::Yaml, index: &str) -> Result<u32> {
let config = &source[index];
if config.is_badvalue() {
bail!("Undefined value for {}. This is a necessary config. Please check config.yaml in the examples folder for documentation.", index);
};
return match source[index].as_i64() {
Some(thing) => Ok(thing as u32),
None => bail!(
"Unlawful value for {}, not a proper number: ({:?})",
index,
source[index]
),
};
}
| true
|
cf7f79020b77d9a654d7f1de7ebbe5ffbc73c99e
|
Rust
|
mikialex/soa-derive
|
/soa-derive-internal/src/vec.rs
|
UTF-8
| 12,273
| 2.703125
| 3
|
[
"Apache-2.0",
"MIT"
] |
permissive
|
use proc_macro2::{Span, TokenStream};
use syn::Ident;
use quote::TokenStreamExt;
use quote::quote;
use crate::input::Input;
pub fn derive(input: &Input) -> TokenStream {
let name = &input.name;
let vec_name_str = format!("Vec<{}>", name);
let other_derive = &input.derive();
let visibility = &input.visibility;
let vec_name = &input.vec_name();
let slice_name = &input.slice_name();
let slice_mut_name = &input.slice_mut_name();
let ref_name = &input.ref_name();
let ptr_name = &input.ptr_name();
let ptr_mut_name = &input.ptr_mut_name();
let fields_names = input.fields.iter()
.map(|field| field.ident.clone().unwrap())
.collect::<Vec<_>>();
let fields_names_1 = &fields_names;
let fields_names_2 = &fields_names;
let first_field = &fields_names[0];
let fields_doc = fields_names.iter()
.map(|field| format!("A vector of `{0}` from a [`{1}`](struct.{1}.html)", field, name))
.collect::<Vec<_>>();
let fields_types = &input.fields.iter()
.map(|field| &field.ty)
.collect::<Vec<_>>();
let mut generated = quote! {
/// An analog to `
#[doc = #vec_name_str]
/// ` with Struct of Array (SoA) layout
#[allow(dead_code)]
#other_derive
#visibility struct #vec_name {
#(
#[doc = #fields_doc]
pub #fields_names_1: Vec<#fields_types>,
)*
}
#[allow(dead_code)]
impl #vec_name {
/// Similar to [`
#[doc = #vec_name_str]
/// ::new()`](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.new)
pub fn new() -> #vec_name {
#vec_name {
#(#fields_names_1 : Vec::new(),)*
}
}
/// Similar to [`
#[doc = #vec_name_str]
/// ::with_capacity()`](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.with_capacity),
/// initializing all fields with the given `capacity`.
pub fn with_capacity(capacity: usize) -> #vec_name {
#vec_name {
#(#fields_names_1 : Vec::with_capacity(capacity),)*
}
}
/// Similar to [`
#[doc = #vec_name_str]
/// ::capacity()`](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.capacity),
/// the capacity of all fields should be the same.
pub fn capacity(&self) -> usize {
let capacity = self.#first_field.capacity();
#(debug_assert_eq!(self.#fields_names_1.capacity(), capacity);)*
capacity
}
/// Similar to [`
#[doc = #vec_name_str]
/// ::reserve()`](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.reserve),
/// reserving the same `additional` space for all fields.
pub fn reserve(&mut self, additional: usize) {
#(self.#fields_names_1.reserve(additional);)*
}
/// Similar to [`
#[doc = #vec_name_str]
/// ::reserve_exact()`](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.reserve_exact)
/// reserving the same `additional` space for all fields.
pub fn reserve_exact(&mut self, additional: usize) {
#(self.#fields_names_1.reserve_exact(additional);)*
}
/// Similar to [`
#[doc = #vec_name_str]
/// ::shrink_to_fit()`](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.shrink_to_fit)
/// shrinking all fields.
pub fn shrink_to_fit(&mut self) {
#(self.#fields_names_1.shrink_to_fit();)*
}
/// Similar to [`
#[doc = #vec_name_str]
/// ::truncate()`](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.truncate)
/// truncating all fields.
pub fn truncate(&mut self, len: usize) {
#(self.#fields_names_1.truncate(len);)*
}
/// Similar to [`
#[doc = #vec_name_str]
/// ::push()`](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.push).
pub fn push(&mut self, value: #name) {
let #name{#(#fields_names_1),*} = value;
#(self.#fields_names_1.push(#fields_names_2);)*
}
/// Similar to [`
#[doc = #vec_name_str]
/// ::len()`](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.len),
/// all the fields should have the same length.
pub fn len(&self) -> usize {
let len = self.#first_field.len();
#(debug_assert_eq!(self.#fields_names_1.len(), len);)*
len
}
/// Similar to [`
#[doc = #vec_name_str]
/// ::is_empty()`](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.is_empty),
/// all the fields should have the same length.
pub fn is_empty(&self) -> bool {
let empty = self.#first_field.is_empty();
#(debug_assert_eq!(self.#fields_names_1.is_empty(), empty);)*
empty
}
/// Similar to [`
#[doc = #vec_name_str]
/// ::swap_remove()`](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.swap_remove).
pub fn swap_remove(&mut self, index: usize) -> #name {
#(
let #fields_names_1 = self.#fields_names_2.swap_remove(index);
)*
#name{#(#fields_names_1: #fields_names_2),*}
}
/// Similar to [`
#[doc = #vec_name_str]
/// ::insert()`](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.insert).
pub fn insert(&mut self, index: usize, element: #name) {
let #name{#(#fields_names_1),*} = element;
#(self.#fields_names_1.insert(index, #fields_names_2);)*
}
/// Similar to [`
#[doc = #vec_name_str]
/// ::remove()`](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.remove).
pub fn remove(&mut self, index: usize) -> #name {
#(
let #fields_names_1 = self.#fields_names_2.remove(index);
)*
#name{#(#fields_names_1: #fields_names_2),*}
}
/// Similar to [`
#[doc = #vec_name_str]
/// ::pop()`](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.pop).
pub fn pop(&mut self) -> Option<#name> {
if self.is_empty() {
None
} else {
#(
let #fields_names_1 = self.#fields_names_2.pop().unwrap();
)*
Some(#name{#(#fields_names_1: #fields_names_2),*})
}
}
/// Similar to [`
#[doc = #vec_name_str]
/// ::append()`](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.append).
pub fn append(&mut self, other: &mut #vec_name) {
#(
self.#fields_names_1.append(&mut other.#fields_names_2);
)*
}
/// Similar to [`
#[doc = #vec_name_str]
/// ::clear()`](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.clear).
pub fn clear(&mut self) {
#(self.#fields_names_1.clear();)*
}
/// Similar to [`
#[doc = #vec_name_str]
/// ::split_off()`](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.split_off).
pub fn split_off(&mut self, at: usize) -> #vec_name {
#vec_name {
#(#fields_names_1 : self.#fields_names_2.split_off(at), )*
}
}
/// Similar to [`
#[doc = #vec_name_str]
/// ::as_slice()`](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.as_slice).
pub fn as_slice(&self) -> #slice_name {
#slice_name {
#(#fields_names_1 : &self.#fields_names_2, )*
}
}
/// Similar to [`
#[doc = #vec_name_str]
/// ::as_mut_slice()`](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.as_mut_slice).
pub fn as_mut_slice(&mut self) -> #slice_mut_name {
#slice_mut_name {
#(#fields_names_1 : &mut self.#fields_names_2, )*
}
}
/// Create a slice of this vector matching the given `range`. This
/// is analogous to `Index<Range<usize>>`.
pub fn slice(&self, range: ::std::ops::Range<usize>) -> #slice_name {
#slice_name {
#(#fields_names_1 : &self.#fields_names_2[range.clone()], )*
}
}
/// Create a mutable slice of this vector matching the given
/// `range`. This is analogous to `IndexMut<Range<usize>>`.
pub fn slice_mut(&mut self, range: ::std::ops::Range<usize>) -> #slice_mut_name {
#slice_mut_name {
#(#fields_names_1 : &mut self.#fields_names_2[range.clone()], )*
}
}
/// Similar to [`
#[doc = #vec_name_str]
/// ::retain()`](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.retain).
pub fn retain<F>(&mut self, mut f: F) where F: FnMut(#ref_name) -> bool {
let len = self.len();
let mut del = 0;
{
let mut slice = self.as_mut_slice();
for i in 0..len {
if !f(slice.get(i).unwrap()) {
del += 1;
} else if del > 0 {
slice.swap(i - del, i);
}
}
}
if del > 0 {
self.truncate(len - del);
}
}
/// Similar to [`
#[doc = #vec_name_str]
/// ::as_ptr()`](https://doc.rust-lang.org/std/struct.Vec.html#method.as_ptr).
pub fn as_ptr(&self) -> #ptr_name {
#ptr_name {
#(#fields_names_1: self.#fields_names_2.as_ptr(),)*
}
}
/// Similar to [`
#[doc = #vec_name_str]
/// ::as_mut_ptr()`](https://doc.rust-lang.org/std/struct.Vec.html#method.as_mut_ptr).
pub fn as_mut_ptr(&mut self) -> #ptr_mut_name {
#ptr_mut_name {
#(#fields_names_1: self.#fields_names_2.as_mut_ptr(),)*
}
}
/// Similar to [`
#[doc = #vec_name_str]
/// ::from_raw_parts()`](https://doc.rust-lang.org/std/struct.Vec.html#method.from_raw_parts).
pub unsafe fn from_raw_parts(data: #ptr_mut_name, len: usize, capacity: usize) -> #vec_name {
#vec_name {
#(#fields_names_1: Vec::from_raw_parts(data.#fields_names_2, len, capacity),)*
}
}
}
};
if input.derives.contains(&Ident::new("Clone", Span::call_site())) {
generated.append_all(quote!{
#[allow(dead_code)]
impl #vec_name {
/// Similar to [`
#[doc = #vec_name_str]
/// ::resize()`](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.resize).
pub fn resize<T>(&mut self, new_len: usize, value: #name) {
#(
self.#fields_names_1.resize(new_len, value.#fields_names_2);
)*
}
}
});
}
return generated;
}
| true
|
d4ce5a3f55bdae0d2f013276af64788797929e30
|
Rust
|
jbradberry/advent-of-code
|
/2022/day09-2/src/main.rs
|
UTF-8
| 2,775
| 3.296875
| 3
|
[] |
no_license
|
use std::collections::{HashSet, HashMap};
use std::io;
use std::io::prelude::*;
#[derive(Debug)]
enum Move {
Up,
Down,
Left,
Right,
}
fn read() -> Vec<(Move, u8)> {
let stdin = io::stdin();
stdin.lock().lines()
.map(|x| {
let line = x.unwrap();
let split = line.split(" ").collect::<Vec<_>>();
match split[0] {
"U" => (Move::Up, split[1].parse().unwrap()),
"D" => (Move::Down, split[1].parse().unwrap()),
"L" => (Move::Left, split[1].parse().unwrap()),
"R" => (Move::Right, split[1].parse().unwrap()),
_ => unreachable!()
}
})
.collect()
}
fn display(rope: &[(i16, i16); 10]) {
let grid = rope.iter().enumerate().map(|(i, x)| (x, i)).collect::<HashMap<_, _>>();
let min_x = rope.iter().map(|(x, _)| *x).min().unwrap();
let max_x = rope.iter().map(|(x, _)| *x).max().unwrap();
let min_y = rope.iter().map(|(_, y)| *y).min().unwrap();
let max_y = rope.iter().map(|(_, y)| *y).max().unwrap();
for y in (min_y..=max_y).rev() {
let row: String = (min_x..=max_x)
.map(|x| match grid.get(&(x, y)) {
Some(v) => v.to_string().chars().next().unwrap(),
None if (x == 0 && y == 0) => 's',
None => '.',
})
.collect();
println!("{}", row);
}
println!("");
}
fn main() {
let moves = read();
let mut rope = [(0, 0); 10];
let mut visited = HashSet::new();
visited.insert((0, 0));
for (mv, inc) in moves {
for _ in 0..inc {
rope[0] = match mv {
Move::Up => (rope[0].0, rope[0].1 + 1),
Move::Down => (rope[0].0, rope[0].1 - 1),
Move::Left => (rope[0].0 - 1, rope[0].1),
Move::Right => (rope[0].0 + 1, rope[0].1),
};
for i in 1..10 {
let (mut x1, mut y1): (i16, i16) = rope[i];
let (x0, y0): (i16, i16) = rope[i - 1];
if (x0 - x1).abs() > 1 {
x1 += (x0 - x1) >> 1;
if y1 != y0 { y1 += (y0 - y1).signum(); }
// println!("x1: {:?}", rope[i]);
}
else if (y0 - y1).abs() > 1 {
y1 += (y0 - y1) >> 1;
if x1 != x0 { x1 += (x0 - x1).signum(); }
// println!("x1: {:?}", rope[i]);
}
rope[i] = (x1, y1);
}
visited.insert(rope[9]);
// display(&rope);
// println!("rope: {:?}", rope);
}
display(&rope);
}
println!("visited: {}", visited.len());
}
| true
|
0e5d33ece0070c0adb892a2957e9ec02f3e6f1bc
|
Rust
|
elracional/Games-FoxHell
|
/src/bitmap.rs
|
UTF-8
| 3,615
| 3.203125
| 3
|
[] |
no_license
|
/*
* Este módulo contiene la clase BitMap en la cual se define el mapa de bits que conforma un sprite.
* El mapa de bits consiste en una matriz 8x8 (para un sprite 8bits) en la cual cada posición indica un index
* que posteriormente se usará para saber qué color se debe insertar en cada una de las posiciones de la
* matriz, debido a la estructura de datos que se utiliza se pueden usar 8 opciones (3bits) de color, donde
* el 0 indica vacío o sin color, y los números del 1 al 7 indican el index del color que se debe usar para
* ese campo de la matriz.
*
* Esta clase se encarga de la compresión de una matriz 8x8 a la asiganción de los valores en variables de tipo
* u64. Esto se diseñó así porque en una matriz 8x8 se tienen 64 valores, por lo que si queremos guardar
* valores que sólo necesiten 3 bits tenemos 8 posibilidades. Cada uno de los bits que reprsentan un sólo valor
* de la matriz se van almacenando en las variables u64 que tienen 64 bits de almacenamiento disponibles, esto
* nos permite guardar los bits más significativos de cada uno de las celdas de la matriz en la primer variable
* u64, el siguiente bit de cada número en la segunda variable u64 y el bit menos significativo en el otro u64.
* Para leerlo se construye la matriz llenando cada celda con los bits que se van leyendo de las variables u64.
*
* Esta clase permite tanto comprimir una matriz como descomprimirla.
*
* Aquí también se definen métodos para invertir el lado del mapa de bits y así invertir un sprite de dirección
* y también para hacer un giro hacia la derecha, estas operaciones se aplican sobre la matriz 8x8.
*/
use std::fmt;
#[derive(Debug, Copy, Clone)]
pub struct BitMap( pub [[u8; 8]; 8] );
impl fmt::Display for BitMap {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
writeln!(f, "___")?;
for line in self.0.iter() {
for bit in line.iter() {
write!(f, "{}, ", bit)?;
}
writeln!(f, "")?;
}
writeln!(f, "---")
}
}
impl BitMap {
pub fn new() -> BitMap {
BitMap([[0; 8]; 8])
}
pub fn compress_map(self) -> (u64, u64, u64) {
let mut a:u64=0;
let mut b:u64=0;
let mut c:u64=0;
let mut i=0;
for line in self.0.iter() {
for color in line.iter() {
a |= ((*color as u64&4)>>2)<<i;
b |= ((*color as u64&2)>>1)<<i;
c |= (*color as u64&1)<<i;
i+=1;
}
}
(a, b, c)
}
pub fn from_compress(compressed: (u64, u64, u64)) -> BitMap {
let (a, b, c) = compressed;
let mut map: [[u8; 8]; 8] = [[0; 8]; 8];
let mut i=0;
for line in 0..8 {
for bit in 0..8 {
let temp:u8 = ((((a&(1<<i))>>i)<<2) | (((b&(1<<i))>>i)<<1) | (c&(1<<i))>>i) as u8;
map[line][bit] = temp;
i+=1;
}
}
BitMap(map)
}
pub fn invert_side(&mut self) {
for i in 0..8 {
for j in 0..4 {
let temp = self.0[i][j];
self.0[i][j] = self.0[i][(7-j) as usize];
self.0[i][(7-j) as usize] = temp;
}
}
}
pub fn right_rotate(&mut self) {
let mut temp = BitMap::new();
for i in 0..8 {
for j in 0..8 {
temp.0[i][j] = self.0[7-j][i];
}
}
for i in 0..8 {
for j in 0..8 {
self.0[i][j] = temp.0[i][j];
}
}
}
}
| true
|
6a40aef7ef1c2478d2dce5f58fe4ad986801f71f
|
Rust
|
polapl/coreutils
|
/src/sleep/sleep.rs
|
UTF-8
| 2,410
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
#![crate_name = "sleep"]
#![feature(collections, core, old_io, rustc_private, std_misc)]
/*
* This file is part of the uutils coreutils package.
*
* (c) Arcterus <arcterus@mail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
extern crate getopts;
extern crate libc;
use std::f64;
use std::old_io::{print, timer};
use std::time::duration::{self, Duration};
#[path = "../common/util.rs"]
#[macro_use]
mod util;
#[path = "../common/time.rs"]
mod time;
static NAME: &'static str = "sleep";
pub fn uumain(args: Vec<String>) -> i32 {
let program = args[0].clone();
let opts = [
getopts::optflag("h", "help", "display this help and exit"),
getopts::optflag("V", "version", "output version information and exit")
];
let matches = match getopts::getopts(args.tail(), &opts) {
Ok(m) => m,
Err(f) => {
show_error!("{}", f);
return 1;
}
};
if matches.opt_present("help") {
println!("sleep 1.0.0");
println!("");
println!("Usage:");
println!(" {0} NUMBER[SUFFIX]", program);
println!("or");
println!(" {0} OPTION", program);
println!("");
print(getopts::usage("Pause for NUMBER seconds. SUFFIX may be 's' for seconds (the default),
'm' for minutes, 'h' for hours or 'd' for days. Unlike most implementations
that require NUMBER be an integer, here NUMBER may be an arbitrary floating
point number. Given two or more arguments, pause for the amount of time
specified by the sum of their values.", &opts).as_slice());
} else if matches.opt_present("version") {
println!("sleep 1.0.0");
} else if matches.free.is_empty() {
show_error!("missing an argument");
show_error!("for help, try '{0} --help'", program);
return 1;
} else {
sleep(matches.free);
}
0
}
fn sleep(args: Vec<String>) {
let sleep_time = args.iter().fold(0.0, |result, arg| {
let num = match time::from_str(arg.as_slice()) {
Ok(m) => m,
Err(f) => {
crash!(1, "{}", f)
}
};
result + num
});
let sleep_dur = if sleep_time == f64::INFINITY {
duration::MAX
} else {
Duration::seconds(sleep_time as i64)
};
timer::sleep(sleep_dur);
}
| true
|
92c65adb6c0b83931ef35a64b65f89acb76dd11c
|
Rust
|
aleb/rofld
|
/src/lib/caption/engine/config.rs
|
UTF-8
| 1,342
| 3.359375
| 3
|
[] |
no_license
|
//! Module with captioning engine configuration.
use std::error;
use std::fmt;
/// Structure holding configuration for the `Engine`.
///
/// This is shared with `CaptionTask`s.
#[derive(Clone, Copy, Debug)]
pub struct Config {
/// Quality of the generated JPEG images (in %).
pub jpeg_quality: u8,
/// Quality of the generated GIF animations (in %).
pub gif_quality: u8,
}
impl Default for Config {
/// Initialize Config with default values.
fn default() -> Self {
Config {
jpeg_quality: 85,
gif_quality: 60,
}
}
}
/// Error signifying an invalid value for one of the configuration options.
#[derive(Clone, Debug)]
pub enum Error {
/// Invalid value for the GIF animation quality percentage.
GifQuality(u8),
/// Invalid value for the JPEG image quality percentage.
JpegQuality(u8),
}
impl error::Error for Error {
fn description(&self) -> &str { "invalid Engine configuration value" }
fn cause(&self) -> Option<&error::Error> { None }
}
impl fmt::Display for Error {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::GifQuality(q) => write!(fmt, "invalid GIF quality value: {}%", q),
Error::JpegQuality(q) => write!(fmt, "invalid JPEG quality value: {}%", q),
}
}
}
| true
|
2d36e2105560c2194d61c17ea7123670bdacf6d3
|
Rust
|
Rexagon/crypto-labs
|
/primes/src/modulo_generator.rs
|
UTF-8
| 416
| 2.53125
| 3
|
[
"Apache-2.0"
] |
permissive
|
use {
num_bigint::BigUint,
rand::{distributions::uniform::UniformSampler, prelude::Rng},
};
use crate::range::Range;
pub trait ModuloGenerator {
fn generate_mod<R: Rng + ?Sized>(&self, modulo: &BigUint, rng: &mut R) -> BigUint;
}
impl ModuloGenerator for Range {
fn generate_mod<R: Rng + ?Sized>(&self, modulo: &BigUint, rng: &mut R) -> BigUint {
self.uniform.sample(rng) % modulo
}
}
| true
|
c93e43dfc86cfa192663632bcee1fc257a5d8201
|
Rust
|
mvertescher/psoc6-pac
|
/src/pdm0/rx_fifo_status.rs
|
UTF-8
| 1,155
| 2.53125
| 3
|
[
"BSD-3-Clause",
"0BSD",
"Apache-2.0"
] |
permissive
|
#[doc = "Reader of register RX_FIFO_STATUS"]
pub type R = crate::R<u32, super::RX_FIFO_STATUS>;
#[doc = "Reader of field `USED`"]
pub type USED_R = crate::R<u8, u8>;
#[doc = "Reader of field `RD_PTR`"]
pub type RD_PTR_R = crate::R<u8, u8>;
#[doc = "Reader of field `WR_PTR`"]
pub type WR_PTR_R = crate::R<u8, u8>;
impl R {
#[doc = "Bits 0:7 - Number of entries in the RX FIFO. The field value is in the range \\[0, 255\\]. When this is zero, the RX FIFO is empty."]
#[inline(always)]
pub fn used(&self) -> USED_R {
USED_R::new((self.bits & 0xff) as u8)
}
#[doc = "Bits 16:23 - RX FIFO read pointer: RX FIFO location from which a data frame is read by the host.This field is used only for debugging purposes."]
#[inline(always)]
pub fn rd_ptr(&self) -> RD_PTR_R {
RD_PTR_R::new(((self.bits >> 16) & 0xff) as u8)
}
#[doc = "Bits 24:31 - RX FIFO write pointer: RX FIFO location at which a new data frame is written by the hardware.This field is used only for debugging purposes."]
#[inline(always)]
pub fn wr_ptr(&self) -> WR_PTR_R {
WR_PTR_R::new(((self.bits >> 24) & 0xff) as u8)
}
}
| true
|
c2a8278281404c434d84800133e76da667fb2180
|
Rust
|
frankmcsherry/timely-dataflow
|
/timely/src/dataflow/operators/generic/handles.rs
|
UTF-8
| 8,953
| 2.8125
| 3
|
[
"MIT"
] |
permissive
|
//! Handles to an operator's input and output streams.
//!
//! These handles are used by the generic operator interfaces to allow user closures to interact as
//! the operator would with its input and output streams.
use std::rc::Rc;
use std::cell::RefCell;
use crate::Data;
use crate::progress::Timestamp;
use crate::progress::ChangeBatch;
use crate::progress::frontier::MutableAntichain;
use crate::dataflow::channels::pullers::Counter as PullCounter;
use crate::dataflow::channels::pushers::Counter as PushCounter;
use crate::dataflow::channels::pushers::buffer::{Buffer, Session};
use crate::dataflow::channels::Bundle;
use crate::communication::{Push, Pull, message::RefOrMut};
use crate::logging::TimelyLogger as Logger;
use crate::dataflow::operators::CapabilityRef;
use crate::dataflow::operators::capability::mint_ref as mint_capability_ref;
use crate::dataflow::operators::capability::CapabilityTrait;
/// Handle to an operator's input stream.
pub struct InputHandle<T: Timestamp, D, P: Pull<Bundle<T, D>>> {
pull_counter: PullCounter<T, D, P>,
internal: Rc<RefCell<Vec<Rc<RefCell<ChangeBatch<T>>>>>>,
logging: Option<Logger>,
}
/// Handle to an operator's input stream and frontier.
pub struct FrontieredInputHandle<'a, T: Timestamp, D: 'a, P: Pull<Bundle<T, D>>+'a> {
/// The underlying input handle.
pub handle: &'a mut InputHandle<T, D, P>,
/// The frontier as reported by timely progress tracking.
pub frontier: &'a MutableAntichain<T>,
}
impl<'a, T: Timestamp, D: Data, P: Pull<Bundle<T, D>>> InputHandle<T, D, P> {
/// Reads the next input buffer (at some timestamp `t`) and a corresponding capability for `t`.
/// The timestamp `t` of the input buffer can be retrieved by invoking `.time()` on the capability.
/// Returns `None` when there's no more data available.
#[inline]
pub fn next(&mut self) -> Option<(CapabilityRef<T>, RefOrMut<Vec<D>>)> {
let internal = &self.internal;
self.pull_counter.next().map(|bundle| {
match bundle.as_ref_or_mut() {
RefOrMut::Ref(bundle) => {
(mint_capability_ref(&bundle.time, internal.clone()), RefOrMut::Ref(&bundle.data))
},
RefOrMut::Mut(bundle) => {
(mint_capability_ref(&bundle.time, internal.clone()), RefOrMut::Mut(&mut bundle.data))
},
}
})
}
/// Repeatedly calls `logic` till exhaustion of the available input data.
/// `logic` receives a capability and an input buffer.
///
/// # Examples
/// ```
/// use timely::dataflow::operators::ToStream;
/// use timely::dataflow::operators::generic::Operator;
/// use timely::dataflow::channels::pact::Pipeline;
///
/// timely::example(|scope| {
/// (0..10).to_stream(scope)
/// .unary(Pipeline, "example", |_cap, _info| |input, output| {
/// input.for_each(|cap, data| {
/// output.session(&cap).give_vec(&mut data.replace(Vec::new()));
/// });
/// });
/// });
/// ```
#[inline]
pub fn for_each<F: FnMut(CapabilityRef<T>, RefOrMut<Vec<D>>)>(&mut self, mut logic: F) {
let mut logging = self.logging.clone();
while let Some((cap, data)) = self.next() {
logging.as_mut().map(|l| l.log(crate::logging::GuardedMessageEvent { is_start: true }));
logic(cap, data);
logging.as_mut().map(|l| l.log(crate::logging::GuardedMessageEvent { is_start: false }));
}
}
}
impl<'a, T: Timestamp, D: Data, P: Pull<Bundle<T, D>>+'a> FrontieredInputHandle<'a, T, D, P> {
/// Allocate a new frontiered input handle.
pub fn new(handle: &'a mut InputHandle<T, D, P>, frontier: &'a MutableAntichain<T>) -> Self {
FrontieredInputHandle {
handle,
frontier,
}
}
/// Reads the next input buffer (at some timestamp `t`) and a corresponding capability for `t`.
/// The timestamp `t` of the input buffer can be retrieved by invoking `.time()` on the capability.
/// Returns `None` when there's no more data available.
#[inline]
pub fn next(&mut self) -> Option<(CapabilityRef<T>, RefOrMut<Vec<D>>)> {
self.handle.next()
}
/// Repeatedly calls `logic` till exhaustion of the available input data.
/// `logic` receives a capability and an input buffer.
///
/// # Examples
/// ```
/// use timely::dataflow::operators::ToStream;
/// use timely::dataflow::operators::generic::Operator;
/// use timely::dataflow::channels::pact::Pipeline;
///
/// timely::example(|scope| {
/// (0..10).to_stream(scope)
/// .unary(Pipeline, "example", |_cap,_info| |input, output| {
/// input.for_each(|cap, data| {
/// output.session(&cap).give_vec(&mut data.replace(Vec::new()));
/// });
/// });
/// });
/// ```
#[inline]
pub fn for_each<F: FnMut(CapabilityRef<T>, RefOrMut<Vec<D>>)>(&mut self, logic: F) {
self.handle.for_each(logic)
}
/// Inspect the frontier associated with this input.
#[inline]
pub fn frontier(&self) -> &'a MutableAntichain<T> {
self.frontier
}
}
pub fn _access_pull_counter<T: Timestamp, D, P: Pull<Bundle<T, D>>>(input: &mut InputHandle<T, D, P>) -> &mut PullCounter<T, D, P> {
&mut input.pull_counter
}
/// Constructs an input handle.
/// Declared separately so that it can be kept private when `InputHandle` is re-exported.
pub fn new_input_handle<T: Timestamp, D, P: Pull<Bundle<T, D>>>(pull_counter: PullCounter<T, D, P>, internal: Rc<RefCell<Vec<Rc<RefCell<ChangeBatch<T>>>>>>, logging: Option<Logger>) -> InputHandle<T, D, P> {
InputHandle {
pull_counter,
internal,
logging,
}
}
/// An owned instance of an output buffer which ensures certain API use.
///
/// An `OutputWrapper` exists to prevent anyone from using the wrapped buffer in any way other
/// than with an `OutputHandle`, whose methods ensure that capabilities are used and that the
/// pusher is flushed (via the `cease` method) once it is no longer used.
pub struct OutputWrapper<T: Timestamp, D, P: Push<Bundle<T, D>>> {
push_buffer: Buffer<T, D, PushCounter<T, D, P>>,
internal_buffer: Rc<RefCell<ChangeBatch<T>>>,
}
impl<T: Timestamp, D, P: Push<Bundle<T, D>>> OutputWrapper<T, D, P> {
/// Creates a new output wrapper from a push buffer.
pub fn new(push_buffer: Buffer<T, D, PushCounter<T, D, P>>, internal_buffer: Rc<RefCell<ChangeBatch<T>>>) -> Self {
OutputWrapper {
push_buffer,
internal_buffer,
}
}
/// Borrows the push buffer into a handle, which can be used to send records.
///
/// This method ensures that the only access to the push buffer is through the `OutputHandle`
/// type which ensures the use of capabilities, and which calls `cease` when it is dropped.
pub fn activate(&mut self) -> OutputHandle<T, D, P> {
OutputHandle {
push_buffer: &mut self.push_buffer,
internal_buffer: &self.internal_buffer,
}
}
}
/// Handle to an operator's output stream.
pub struct OutputHandle<'a, T: Timestamp, D: 'a, P: Push<Bundle<T, D>>+'a> {
push_buffer: &'a mut Buffer<T, D, PushCounter<T, D, P>>,
internal_buffer: &'a Rc<RefCell<ChangeBatch<T>>>,
}
impl<'a, T: Timestamp, D, P: Push<Bundle<T, D>>> OutputHandle<'a, T, D, P> {
/// Obtains a session that can send data at the timestamp associated with capability `cap`.
///
/// In order to send data at a future timestamp, obtain a capability for the new timestamp
/// first, as show in the example.
///
/// # Examples
/// ```
/// use timely::dataflow::operators::ToStream;
/// use timely::dataflow::operators::generic::Operator;
/// use timely::dataflow::channels::pact::Pipeline;
///
/// timely::example(|scope| {
/// (0..10).to_stream(scope)
/// .unary(Pipeline, "example", |_cap, _info| |input, output| {
/// input.for_each(|cap, data| {
/// let time = cap.time().clone() + 1;
/// output.session(&cap.delayed(&time))
/// .give_vec(&mut data.replace(Vec::new()));
/// });
/// });
/// });
/// ```
pub fn session<'b, C: CapabilityTrait<T>>(&'b mut self, cap: &'b C) -> Session<'b, T, D, PushCounter<T, D, P>> where 'a: 'b {
assert!(cap.valid_for_output(&self.internal_buffer), "Attempted to open output session with invalid capability");
self.push_buffer.session(cap.time())
}
}
impl<'a, T: Timestamp, D, P: Push<Bundle<T, D>>> Drop for OutputHandle<'a, T, D, P> {
fn drop(&mut self) {
self.push_buffer.cease();
}
}
| true
|
3341eb1cc71fc09ae6cc4ae66224545c712644fb
|
Rust
|
monsieurbadia/qoeur-and-qoeur-lab-and-qompo
|
/src/qoeurc/src/utils/iters.rs
|
UTF-8
| 1,231
| 3.046875
| 3
|
[
"MIT"
] |
permissive
|
use crate::analyzer::interpreter::{Interpreter, ValueResult};
use crate::transformer::transpiler::Transpiler;
use crate::value::instruction::IKind;
use crate::value::{Value, Values};
use crate::void;
pub fn eval_expressions(
interpreter: &mut Interpreter,
exprs: Vec<Box<dyn Value>>,
) -> ValueResult<Values> {
let values = exprs
.to_owned()
.iter()
.map(|expr| -> ValueResult<Box<dyn Value>> {
Ok(expr.to_owned().eval(interpreter)?)
})
.collect::<ValueResult<Values>>()?;
Ok(values)
}
pub fn eval_statements(
interpreter: &mut Interpreter,
stmts: Vec<Box<dyn Value>>,
) -> ValueResult<Box<dyn Value>> {
let mut value = void!().boxed();
for stmt in &stmts {
value = stmt.to_owned().eval(interpreter)?;
if let IKind::Return = value.ikind() {
return Ok(value);
}
}
Ok(value)
}
pub fn strip_exprs(expr: &Values, delimiter: &str) -> String {
expr
.iter()
.map(|a| a.text())
.collect::<Vec<String>>()
.join(delimiter)
}
pub fn transpile_exprs(
transpiler: &mut Transpiler,
data: &Values,
delimiter: &str,
) -> String {
data
.iter()
.map(|d| d.to_owned().transpile(transpiler))
.collect::<Vec<String>>()
.join(delimiter)
}
| true
|
cc0a7ad7e29ea5aaa859fa466907b804359dd175
|
Rust
|
jbyte/chip8
|
/src/main.rs
|
UTF-8
| 1,358
| 2.625
| 3
|
[
"MIT"
] |
permissive
|
#[macro_use]
extern crate nom;
extern crate rand;
use std::env;
use std::io::Read;
use std::fs::File;
use std::path::Path;
mod cpu;
mod debugger;
use debugger::Debugger;
fn main() {
let rom_name: String;
let debug: String;
let file = env::args().nth(2);
let flag = env::args().nth(1);
match file {
None => {
match flag {
Some(_) => {
rom_name = flag.unwrap();
debug = String::new();
},
None => panic!("Where the args at? Do need a file atleast.")
}
},
Some(_) => {
rom_name = file.unwrap();
debug = flag.unwrap();
}
}
let rom = read_rom(rom_name);
//TODO: setup graphics
//TODO: setup input
let mut cpu = cpu::cpu::init();
cpu.load_rom(rom);
match debug.as_ref() {
"-d" | "--debug" => {
// TODO: run with debugger
let mut debug = Debugger::new(cpu);
debug.run();
}
_ => {
loop {
cpu.emulate_cycle();
}
}
}
}
fn read_rom<P: AsRef<Path>>(path: P) -> Box<[u8]> {
let mut file = File::open(path).unwrap();
let mut file_buf = Vec::new();
file.read_to_end(&mut file_buf).unwrap();
file_buf.into_boxed_slice()
}
| true
|
f933874a79b19114af81e21b10344e62132949bb
|
Rust
|
mewbak/Lancelot
|
/core/src/loader.rs
|
UTF-8
| 5,332
| 2.953125
| 3
|
[
"Apache-2.0"
] |
permissive
|
use bitflags::bitflags;
use failure::{Error, Fail};
use log::info;
use strum_macros::Display;
use super::{
analysis::Analyzer,
arch::{Arch, RVA, VA},
config::Config,
loaders::{pe::PELoader, sc::ShellcodeLoader},
pagemap::PageMap,
};
#[derive(Debug, Fail)]
pub enum LoaderError {
#[fail(display = "The given buffer is not supported (arch/plat/file format)")]
NotSupported,
#[fail(display = "The given buffer uses a bitness incompatible with the architecture")]
MismatchedBitness,
}
#[derive(Display, Clone, Copy)]
pub enum FileFormat {
Raw, // shellcode
PE,
}
#[derive(Display, Clone, Copy)]
pub enum Platform {
Windows,
}
bitflags! {
pub struct Permissions: u8 {
const R = 0b0000_0001;
const W = 0b0000_0010;
const X = 0b0000_0100;
const RW = Self::R.bits | Self::W.bits;
const RX = Self::R.bits | Self::X.bits;
const WX = Self::W.bits | Self::X.bits;
const RWX = Self::R.bits | Self::W.bits | Self::X.bits;
}
}
#[derive(Debug)]
pub struct Section {
pub addr: RVA,
pub size: u32,
pub perms: Permissions,
pub name: String,
}
impl Section {
pub fn contains(self: &Section, rva: RVA) -> bool {
if rva < self.addr {
return false;
}
let max = self.addr + self.size as i32; // danger
if rva >= max {
return false;
}
true
}
pub fn is_executable(&self) -> bool {
self.perms.intersects(Permissions::X)
}
pub fn end(&self) -> RVA {
self.addr + RVA::from(self.size as i64)
}
}
pub struct LoadedModule {
pub base_address: VA,
pub sections: Vec<Section>,
pub address_space: PageMap<u8>,
}
impl LoadedModule {
pub fn max_address(&self) -> RVA {
self.sections.iter().map(|sec| sec.end()).max().unwrap() // danger: assume there's at least one section.
}
}
pub trait Loader {
/// Fetch the number of bits for a pointer in this architecture.
fn get_arch(&self) -> Arch;
fn get_plat(&self) -> Platform;
fn get_file_format(&self) -> FileFormat;
fn get_name(&self) -> String {
return format!("{}/{}/{}", self.get_plat(), self.get_arch(), self.get_file_format());
}
/// Returns True if this Loader knows how to load the given bytes.
fn taste(&self, config: &Config, buf: &[u8]) -> bool;
/// Load the given bytes into a Module and suggest the appropriate
/// Analyzers.
///
/// While the loader is parsing a file, it should determine what
/// the most appropriate analyzers are, e.g. a PE loader may inspect the
/// headers to determine if there is Control Flow Guard metadata that
/// can be analyzed.
fn load(&self, config: &Config, buf: &[u8]) -> Result<(LoadedModule, Vec<Box<dyn Analyzer>>), Error>;
}
pub fn default_loaders() -> Vec<Box<dyn Loader>> {
// we might like these to come from a lazy_static global,
// however, then these have to be Sync.
// I'm not sure if that's a good idea yet.
let mut loaders: Vec<Box<dyn Loader>> = vec![];
// the order here matters!
// the default `load` routine will pick the first matching loader,
// so the earlier entries here have higher precedence.
loaders.push(Box::new(PELoader::new(Arch::X32)));
loaders.push(Box::new(PELoader::new(Arch::X64)));
loaders.push(Box::new(ShellcodeLoader::new(Platform::Windows, Arch::X32)));
loaders.push(Box::new(ShellcodeLoader::new(Platform::Windows, Arch::X64)));
loaders
}
/// Find the loaders that support loading the given sample.
///
/// The result is an iterator so that the caller can use the first
/// matching result without waiting for all Loaders to taste the bytes.
///
/// Loaders are tasted in the order defined in `default_loaders`.
///
/// Example:
///
/// ```
/// use lancelot::arch::*;
/// use lancelot::config::*;
/// use lancelot::loader::*;
///
/// match taste(&Config::default(), b"\xEB\xFE").nth(0) {
/// Some(loader) => assert_eq!(loader.get_name(), "Windows/x32/Raw"),
/// None => panic!("no matching loaders"),
/// };
/// ```
pub fn taste<'a>(config: &'a Config, buf: &'a [u8]) -> impl Iterator<Item = Box<dyn Loader>> + 'a {
default_loaders()
.into_iter()
.filter(move |loader| loader.taste(config, buf))
}
/// Load the given sample using the first matching loader from
/// `default_loaders`.
///
/// Example:
///
/// ```
/// use lancelot::arch::*;
/// use lancelot::config::*;
/// use lancelot::loader::*;
///
/// load(&Config::default(), b"\xEB\xFE")
/// .map(|(loader, module, analyzers)| {
/// assert_eq!(loader.get_name(), "Windows/x32/Raw");
/// assert_eq!(module.base_address, VA(0x0));
/// assert_eq!(module.sections[0].name, "raw");
/// })
/// .map_err(|e| panic!(e));
/// ```
#[allow(clippy::type_complexity)]
pub fn load(config: &Config, buf: &[u8]) -> Result<(Box<dyn Loader>, LoadedModule, Vec<Box<dyn Analyzer>>), Error> {
match taste(config, buf).nth(0) {
Some(loader) => {
info!("auto-detected loader: {}", loader.get_name());
loader
.load(config, buf)
.map(|(module, analyzers)| (loader, module, analyzers))
}
None => Err(LoaderError::NotSupported.into()),
}
}
| true
|
1407360ccbdb1ba8aef00d4ae81ffa35997ed06a
|
Rust
|
djc/async-imap
|
/src/imap_stream.rs
|
UTF-8
| 9,749
| 2.828125
| 3
|
[
"Apache-2.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
use std::fmt;
use std::pin::Pin;
use async_std::io::{self, Read, Write};
use async_std::prelude::*;
use async_std::stream::Stream;
use async_std::sync::Arc;
use byte_pool::{Block, BytePool};
use futures::task::{Context, Poll};
use nom::Needed;
use crate::types::{Request, ResponseData};
const INITIAL_CAPACITY: usize = 1024 * 4;
const MAX_CAPACITY: usize = 512 * 1024 * 1024; // 512 MiB
lazy_static::lazy_static! {
/// The global buffer pool we use for storing incoming data.
pub(crate) static ref POOL: Arc<BytePool> = Arc::new(BytePool::new());
}
/// Wraps a stream, and parses incoming data as imap server messages. Writes outgoing data
/// as imap client messages.
#[derive(Debug)]
pub struct ImapStream<R: Read + Write> {
// TODO: write some buffering logic
/// The underlying stream
pub(crate) inner: R,
/// Buffer for the already read, but not yet parsed data.
buffer: Block<'static>,
/// Position of valid read data into buffer.
current: Position,
/// How many bytes do we need to finishe the currrent element that is being decoded.
decode_needs: usize,
/// Whether we should attempt to decode whatever is currently inside the buffer.
/// False indicates that we know for certain that the buffer is incomplete.
initial_decode: bool,
}
/// A semantically explicit slice of a buffer.
#[derive(Eq, PartialEq, Debug, Copy, Clone)]
struct Position {
start: usize,
end: usize,
}
impl Position {
const ZERO: Position = Position { start: 0, end: 0 };
const fn new(start: usize, end: usize) -> Position {
Position { start, end }
}
}
enum DecodeResult {
Some {
/// The parsed response.
response: ResponseData,
/// Remaining data.
buffer: Block<'static>,
/// How many bytes are actually valid data in `buffer`.
used: usize,
},
None(Block<'static>),
}
impl fmt::Debug for DecodeResult {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
DecodeResult::Some {
response,
buffer,
used,
} => f
.debug_struct("DecodeResult::Some")
.field("response", response)
.field("block", &buffer.len())
.field("used", used)
.finish(),
DecodeResult::None(block) => write!(f, "DecodeResult::None({})", block.len()),
}
}
}
impl<R: Read + Write + Unpin> ImapStream<R> {
/// Creates a new `ImapStream` based on the given `Read`er.
pub fn new(inner: R) -> Self {
ImapStream {
inner,
buffer: POOL.alloc(INITIAL_CAPACITY),
current: Position::ZERO,
decode_needs: 0,
initial_decode: false, // buffer is empty initially, nothing to decode
}
}
pub async fn encode(&mut self, msg: Request) -> Result<(), io::Error> {
log::trace!("encode: input: {:?}", msg);
if let Some(tag) = msg.0 {
self.inner.write_all(tag.as_bytes()).await?;
self.inner.write(b" ").await?;
}
self.inner.write_all(&msg.1).await?;
self.inner.write_all(b"\r\n").await?;
Ok(())
}
pub fn into_inner(self) -> R {
self.inner
}
/// Flushes the underlying stream.
pub async fn flush(&mut self) -> Result<(), io::Error> {
self.inner.flush().await
}
pub fn as_mut(&mut self) -> &mut R {
&mut self.inner
}
}
impl<R: Read + Write + Unpin> ImapStream<R> {
fn decode(
&mut self,
buf: Block<'static>,
start: usize,
end: usize,
) -> io::Result<DecodeResult> {
log::trace!("decode: input: {:?}", std::str::from_utf8(&buf[start..end]));
let mut rest = None;
let mut used = 0;
let res = ResponseData::try_new(buf, |buf| {
match imap_proto::parse_response(&buf[start..end]) {
Ok((remaining, response)) => {
// TODO: figure out if we can shrink to the minimum required size.
self.decode_needs = 0;
let mut buf = POOL.alloc(std::cmp::max(remaining.len(), INITIAL_CAPACITY));
buf[..remaining.len()].copy_from_slice(remaining);
used = remaining.len();
rest = Some(buf);
Ok(response)
}
Err(nom::Err::Incomplete(Needed::Size(min))) => {
log::trace!("decode: incomplete data, need minimum {} bytes", min);
self.decode_needs = min;
Err(None)
}
Err(nom::Err::Incomplete(_)) => {
log::trace!("decode: incomplete data, need unknown number of bytes");
Err(None)
}
Err(err) => Err(Some(io::Error::new(
io::ErrorKind::Other,
format!("{:?} during parsing of {:?}", err, &buf[start..end]),
))),
}
});
match res {
Ok(response) => Ok(DecodeResult::Some {
response,
buffer: rest.unwrap(),
used,
}),
Err(rental::RentalError(err, buf)) => match err {
Some(err) => Err(err),
None => Ok(DecodeResult::None(buf)),
},
}
}
}
impl<R: Read + Write + Unpin> Stream for ImapStream<R> {
type Item = io::Result<ResponseData>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
// The `poll_next` method must strive to be as idempotent as possible if the underlying
// future/stream is not yet ready to produce results. It means that we must be careful
// to persist the state of polling between calls to `poll_next`, specifically,
// we must always restore the buffer and the current position before any `return`s.
let this = &mut *self;
let mut n = std::mem::replace(&mut this.current, Position::ZERO);
let buffer = std::mem::replace(&mut this.buffer, POOL.alloc(INITIAL_CAPACITY));
let mut buffer = if (n.end - n.start) > 0 && this.initial_decode {
match this.decode(buffer, n.start, n.end)? {
DecodeResult::Some {
response,
buffer,
used,
} => {
// initial_decode is still true
std::mem::replace(&mut this.buffer, buffer);
this.current = Position::new(0, used);
return Poll::Ready(Some(Ok(response)));
}
DecodeResult::None(buffer) => buffer,
}
} else {
buffer
};
loop {
if (n.end - n.start) + this.decode_needs >= buffer.capacity() {
if buffer.capacity() + this.decode_needs < MAX_CAPACITY {
buffer.realloc(buffer.capacity() + this.decode_needs);
} else {
std::mem::replace(&mut this.buffer, buffer);
this.current = n;
return Poll::Ready(Some(Err(io::Error::new(
io::ErrorKind::Other,
"incoming data too large",
))));
}
}
let bytes_read = match Pin::new(&mut this.inner).poll_read(cx, &mut buffer[n.end..]) {
Poll::Ready(result) => result?,
Poll::Pending => {
// if we're here, it means that we need more data but there is none yet,
// so no decoding attempts are necessary until we get more data
this.initial_decode = false;
std::mem::replace(&mut this.buffer, buffer);
this.current = n;
return Poll::Pending;
}
};
n.end += bytes_read;
match this.decode(buffer, n.start, n.end)? {
DecodeResult::Some {
response,
buffer,
used,
} => {
// current buffer might now contain more data inside, so we need to attempt
// to decode it next time
this.initial_decode = true;
std::mem::replace(&mut this.buffer, buffer);
this.current = Position::new(0, used);
return Poll::Ready(Some(Ok(response)));
}
DecodeResult::None(buf) => {
buffer = buf;
if this.buffer.is_empty() || n == Position::ZERO {
// "logical buffer" is empty, there is nothing to decode on the next step
this.initial_decode = false;
std::mem::replace(&mut this.buffer, buffer);
this.current = n;
return Poll::Ready(None);
} else if (n.end - n.start) == 0 {
// "logical buffer" is empty, there is nothing to decode on the next step
this.initial_decode = false;
std::mem::replace(&mut this.buffer, buffer);
this.current = n;
return Poll::Ready(Some(Err(io::Error::new(
io::ErrorKind::UnexpectedEof,
"bytes remaining in stream",
))));
}
}
}
}
}
}
| true
|
1ec0b1f63e0611dc696f0b566821cb4d6181994f
|
Rust
|
mattiascibien/dicenotation-rs
|
/dicenotation/src/lib.rs
|
UTF-8
| 2,923
| 3.375
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] |
permissive
|
// Copyright 2018 Mattias Cibien
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.
//! Library aimed at parsing and rolling dices
//! for Role-Playing games using [Standard Dice Notation](https://en.wikipedia.org/wiki/Dice_notation#Standard_notation)
//! that bears inspiration from the [dicenotation](https://github.com/mattiascibien/dicenotation) library.
#![forbid(unsafe_code)]
#[macro_use]
extern crate lazy_static;
use num_traits;
use rand;
use num_traits::int::PrimInt;
use rand::distributions::range::SampleRange;
use std::fmt::Debug;
use std::str::FromStr;
mod parsing;
mod rolling;
/// Struct represeting a die roll data
#[derive(Debug)]
pub struct DiceData<T>
where
T: PrimInt,
{
/// Number of die to roll
num_dice: T,
/// Number of faces of each dice
num_faces: T,
/// Modifies (true for plus, false for minus)
modifier: bool,
/// Modifier value (alters the result of the die roll)
modifier_val: T,
}
#[cfg(test)]
impl<T> PartialEq for DiceData<T>
where
T: PrimInt,
{
fn eq(&self, other: &DiceData<T>) -> bool {
self.num_dice == other.num_dice
&& self.num_faces == other.num_faces
&& self.modifier == other.modifier
&& self.modifier_val == other.modifier_val
}
}
/// Execute a dice roll based on the given notation
///
/// # Examples
///
/// Gets the result of rolling 3 die of 5 faces
///
/// ```
/// use dicenotation::roll_dice;
///
/// let result = roll_dice::<i32>("3d5");
/// ```
///
/// Executes two rolls by summing their values
///
/// ```
/// use dicenotation::roll_dice;
///
/// let result = roll_dice::<i32>("3d5").unwrap() + roll_dice::<i32>("2d3").unwrap();
/// ```
pub fn roll_dice<T>(notation: &str) -> Result<T, &str>
where
T: PrimInt + FromStr + SampleRange,
<T as FromStr>::Err: Debug,
{
let dice_data = parsing::parse(notation);
let dice_data = match dice_data {
Ok(d) => d,
Err(e) => return Err(e),
};
let result = rolling::roll(dice_data);
Ok(result)
}
pub fn roll_dice_with_fn<T,F>(notation: &str, random: F) -> Result<T, &str>
where
T: PrimInt + FromStr + SampleRange,
<T as FromStr>::Err: Debug,
F: Fn(T,T) -> T,
{
let dice_data = parsing::parse(notation);
let dice_data = match dice_data {
Ok(d) => d,
Err(e) => return Err(e),
};
let result = rolling::roll_with_fn(dice_data, &random);
Ok(result)
}
#[cfg(test)]
mod test {
#[test]
fn it_rolls_two_dices_of_three_faces_with_modifier_plus_two_correctly() {
let result = super::roll_dice::<i32>("2d3+2").unwrap();
assert!(result >= 4);
assert!(result <= 8);
}
}
| true
|
34c5c2dfa9e03f380a9764256a69437b09c4adc7
|
Rust
|
boa-dev/boa
|
/fuzz/fuzz_targets/common.rs
|
UTF-8
| 2,944
| 2.75
| 3
|
[
"MIT",
"Unlicense"
] |
permissive
|
use arbitrary::{Arbitrary, Unstructured};
use boa_ast::{
visitor::{VisitWith, VisitorMut},
Expression, StatementList,
};
use boa_interner::{Interner, Sym, ToInternedString};
use std::{
fmt::{Debug, Formatter},
ops::ControlFlow,
};
/// Context for performing fuzzing. This structure contains both the generated AST as well as the
/// context used to resolve the symbols therein.
pub struct FuzzData {
pub interner: Interner,
pub ast: StatementList,
}
impl<'a> Arbitrary<'a> for FuzzData {
fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
let mut interner = Interner::with_capacity(8);
let mut syms_available = Vec::with_capacity(8);
for c in 'a'..='h' {
syms_available.push(interner.get_or_intern(&*String::from(c)));
}
let mut ast = StatementList::arbitrary(u)?;
struct FuzzReplacer<'a, 's, 'u> {
syms: &'s [Sym],
u: &'u mut Unstructured<'a>,
}
impl<'a, 's, 'u, 'ast> VisitorMut<'ast> for FuzzReplacer<'a, 's, 'u> {
type BreakTy = arbitrary::Error;
// TODO arbitrary strings literals?
fn visit_expression_mut(
&mut self,
node: &'ast mut Expression,
) -> ControlFlow<Self::BreakTy> {
if matches!(node, Expression::FormalParameterList(_)) {
match self.u.arbitrary() {
Ok(id) => *node = Expression::Identifier(id),
Err(e) => return ControlFlow::Break(e),
}
}
node.visit_with_mut(self)
}
fn visit_sym_mut(&mut self, node: &'ast mut Sym) -> ControlFlow<Self::BreakTy> {
*node = self.syms[node.get() % self.syms.len()];
ControlFlow::Continue(())
}
}
let mut replacer = FuzzReplacer {
syms: &syms_available,
u,
};
if let ControlFlow::Break(e) = replacer.visit_statement_list_mut(&mut ast) {
Err(e)
} else {
Ok(Self { interner, ast })
}
}
}
impl Debug for FuzzData {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.debug_struct("FuzzData")
.field("ast", &self.ast)
.finish_non_exhaustive()
}
}
pub struct FuzzSource {
pub interner: Interner,
pub source: String,
}
impl<'a> Arbitrary<'a> for FuzzSource {
fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
let data = FuzzData::arbitrary(u)?;
let source = data.ast.to_interned_string(&data.interner);
Ok(Self {
interner: data.interner,
source,
})
}
}
impl Debug for FuzzSource {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.write_fmt(format_args!("Fuzzed source:\n{}", self.source))
}
}
| true
|
c5f9468e18c5ff3ff27c83f73666e0200e24ea2f
|
Rust
|
itsrainingmani/adventofcode2020
|
/day3-tobag-traj/src/main.rs
|
UTF-8
| 1,550
| 3.578125
| 4
|
[] |
no_license
|
use std::fs;
type Slope = (usize, usize);
type Pos = Slope;
fn main() {
println!("Advent of Code - Day 3 - Tobaggon Trajectory");
let input_filename = String::from("input.txt");
let contents =
fs::read_to_string(input_filename).expect("Something went wrong reading the file");
// Convert the string representation of the input into a vector of strs
let trees: Vec<_> = contents.split_ascii_whitespace().collect();
let slope: Slope = (3, 1);
part_one(&trees, slope);
let slopes: [Slope; 5] = [(3, 1), (5, 1), (1, 1), (7, 1), (1, 2)];
let mut encounter_vec: Vec<usize> = Vec::new();
for sl in slopes.iter() {
encounter_vec.push(part_one(&trees, *sl));
}
println!("{}", encounter_vec.iter().fold(1, |acc, x| acc * x));
}
fn part_one(trees: &Vec<&str>, slope: Slope) -> usize {
let mut cur_pos: Pos = (0, 0); // Current position of tobaggons
let size_of_treeline = trees.get(0).expect("Something went wrong").len();
let mut encounters: usize = 0;
for _ in 0..trees.len() {
let (mut x, y): Pos = cur_pos;
if y >= trees.len() {
break;
}
x %= size_of_treeline;
encounters += match get_at_location(&trees, x, y).unwrap() {
'#' => 1,
_ => 0,
};
cur_pos = (x + slope.0, y + slope.1);
}
println!("Number of tree encounters: {}", encounters);
encounters
}
fn get_at_location(trees: &Vec<&str>, x: usize, y: usize) -> Option<char> {
trees.get(y)?.chars().nth(x)
}
| true
|
a8ac2b7a998eb793eb69af04da23409399048fcc
|
Rust
|
tdejager/winner
|
/winner_server/src/messages.rs
|
UTF-8
| 2,013
| 2.96875
| 3
|
[] |
no_license
|
use crate::types::{Story, StoryPoints, Winner};
use serde_derive::{Deserialize, Serialize};
use std::collections::HashMap;
#[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)]
pub enum StateChange {
Enter,
Leave,
Leader,
}
#[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)]
pub enum RoomStateChange {
Voting,
Idle,
}
#[derive(Serialize, Deserialize, Clone, Debug, Eq, PartialEq)]
pub struct RoomInitialState {
pub winners: Vec<Winner>,
pub leader: Option<Winner>,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
/// Messages that are sent by the server
pub enum ServerMessages {
/// Sent when something in a room changes
RoomParticipantsChange((Winner, StateChange)),
/// Sent when the state of the room changes
RoomStateChange(RoomStateChange),
/// Sent when two people should debate story points
Fight((Winner, Winner)),
/// Sent when the fight has been resolved
FightResolved,
/// Sent when a vote has been cast
VoteCast((Winner, StoryPoints)),
/// Sent when a vote has to be done for a story
StartVote(Story),
/// Vote has finished
VotesReceived(HashMap<Winner, StoryPoints>),
/// Initial state
InitialState(RoomInitialState),
/// Ok Response to a ClientMessage request
ServerOk(),
/// Err Response to a ClientMessage request
ServerErr(String),
}
#[derive(Serialize, Deserialize, Debug, Clone)]
/// Messages that are received by the server
pub enum ClientMessages {
/// Want to enter the room
EnterRoom(Winner),
/// Leave the room
LeaveRoom(Winner),
/// Reply to acknowledge the leader
AcknowledgeLeader(bool),
/// Sent when a vote has to be done for a story
StartVote(Story),
/// Sent to cast an actual vote
Vote((Winner, Story, StoryPoints)),
/// Fight resolved
FightResolved,
// Final story points, which should include the leader correct story and storypoints
//FinalStoryPoints((Winner, Story, StoryPoints)),
}
| true
|
1f42c455b12a2984753bc6779a665962362a39f9
|
Rust
|
joeferner/raspberry-pi-ir-hat
|
/drivers/rust/src/bin/irlisten.rs
|
UTF-8
| 5,441
| 2.6875
| 3
|
[] |
no_license
|
use clap::App;
use clap::Arg;
use log::info;
use raspberry_pi_ir_hat::{Config, Hat};
use simple_logger;
use std::{thread, time};
fn main() -> Result<(), String> {
simple_logger::init_with_env().map_err(|err| format!("{}", err))?;
info!("starting");
let args = App::new("Raspberry Pi IrHat - irlisten")
.version("1.0.0")
.author("Joe Ferner <joe@fernsroth.com>")
.about("Listen for remote button presses")
.arg(
Arg::with_name("file")
.short("f")
.long("file")
.value_name("FILE")
.help("File to create/add IR signals to")
.required(true)
.takes_value(true),
)
.arg(
Arg::with_name("port")
.short("p")
.long("port")
.default_value("/dev/serial0")
.help("Path to serial port")
.takes_value(true),
)
.get_matches();
let filename = args.value_of("file").unwrap();
let port = args.value_of("port").unwrap();
let config =
Config::read(filename, false).map_err(|err| format!("failed to read config {}", err))?;
let mut hat = Hat::new(config, port);
hat.open(Box::new(|msg| {
println!("{:#?}", msg);
}))
.map_err(|err| format!("failed to open hat {}", err))?;
println!("press ctrl+c to exit");
loop {
thread::sleep(time::Duration::from_secs(1));
}
}
#[cfg(test)]
mod tests {
use super::*;
use raspberry_pi_ir_hat::hat::HatMessage::ButtonPress;
use raspberry_pi_ir_hat::socat::socat;
use std::sync::Arc;
use std::sync::Mutex;
use std::time::Duration;
#[test]
fn test_irlisten() {
let mut socat_result = socat();
let port = socat_result.get_port();
let mut sp = socat_result.take_serial_port();
let config = Config::from_str(
r#"
remotes:
denon:
interval: 25
repeat: 2
buttons:
power:
debounce: 100
ir_signals:
- protocol: Denon
address: 8
command: 135
volume_up:
debounce: 10
ir_signals:
- protocol: Denon
address: 8
command: 79
volume_down:
debounce: 10
ir_signals:
- protocol: Denon
address: 8
command: 143
"#,
)
.unwrap();
let messages = Arc::new(Mutex::new(Vec::new()));
let hat_messages = messages.clone();
let mut hat = Hat::new(config, &port);
hat.open(Box::new(move |message| {
hat_messages.lock().unwrap().push(message);
}))
.unwrap();
thread::spawn(move || {
thread::sleep(Duration::from_millis(10));
sp.write("!s1,8,135,0,0,0,42\n".as_bytes()).unwrap();
thread::sleep(Duration::from_millis(10));
sp.write("!s1,8,135,0,0,0,42\n".as_bytes()).unwrap();
thread::sleep(Duration::from_millis(10));
sp.write("!s1,8,79,0,0,0,42\n".as_bytes()).unwrap();
thread::sleep(Duration::from_millis(15));
sp.write("!s1,8,143,0,0,0,42\n".as_bytes()).unwrap();
});
let mut message_index = 0;
'outer: for _ in 0..100 {
{
thread::sleep(Duration::from_millis(10));
let mut msgs = messages.lock().unwrap();
while msgs.len() > 0 {
let message = msgs.remove(0);
if message_index == 0 {
if let ButtonPress(bp) = message {
assert_eq!("denon", bp.remote_name);
assert_eq!("power", bp.button_name);
message_index = message_index + 1;
} else {
panic!(
"unexpected message at offset {}: {:?}",
message_index, message
);
}
} else if message_index == 1 {
if let ButtonPress(bp) = message {
assert_eq!("denon", bp.remote_name);
assert_eq!("volume_up", bp.button_name);
message_index = message_index + 1;
} else {
panic!(
"unexpected message at offset {}: {:?}",
message_index, message
);
}
} else if message_index == 2 {
if let ButtonPress(bp) = message {
assert_eq!("denon", bp.remote_name);
assert_eq!("volume_down", bp.button_name);
message_index = message_index + 1;
break 'outer;
} else {
panic!(
"unexpected message at offset {}: {:?}",
message_index, message
);
}
} else {
panic!("unexpected message: {:?}", message);
}
}
}
}
assert_eq!(3, message_index);
}
}
| true
|
1e32a1ba4557374561461dffbc663e4f169f6401
|
Rust
|
casimir/ufind
|
/src/digraph/mod.rs
|
UTF-8
| 1,618
| 3.078125
| 3
|
[
"MIT"
] |
permissive
|
mod data;
use self::data::{Digraph, TABLE};
fn get_char(digraph: &str) -> Option<char> {
let mut chars_it = digraph.chars();
let chars: [char; 2] = [chars_it.next().unwrap(), chars_it.next().unwrap()];
let res = TABLE.into_iter().find(|&x| x.sequence == chars);
match res {
Some(digr) => Some(digr.character),
None => None,
}
}
fn get_digraph(c: &char) -> Option<String> {
let res = TABLE.into_iter().find(|&x| x.character == *c);
match res {
Some(digr) => Some(digr.sequence.iter().cloned().collect::<String>()),
None => None,
}
}
pub fn convert(pattern: &str) -> Option<String> {
match pattern.chars().count() {
1usize => get_digraph(&pattern.chars().next().unwrap()),
2usize => {
match get_char(pattern) {
Some(c) => Some(c.to_string()),
None => None,
}
}
_ => None,
}
}
pub fn filter(pattern: &str) -> Vec<&Digraph> {
match pattern.chars().count() {
1usize => {
let c = pattern.chars().next().unwrap();
TABLE.into_iter().filter(|&x| x.sequence[0] == c).collect()
}
2usize => {
let mut chars_it = pattern.chars();
let chars: [char; 2] = [chars_it.next().unwrap(), chars_it.next().unwrap()];
if chars[0] == '_' {
TABLE.into_iter().filter(|&x| x.sequence[1] == chars[1]).collect()
} else {
TABLE.into_iter().filter(|&x| x.sequence == chars).collect()
}
}
_ => TABLE.iter().collect(),
}
}
| true
|
2d798d25559055a66a888a3f616ed04164a80b0d
|
Rust
|
wasmerio/cranelift
|
/cranelift-simplejit/src/backend.rs
|
UTF-8
| 17,759
| 2.546875
| 3
|
[
"LLVM-exception",
"Apache-2.0"
] |
permissive
|
//! Defines `SimpleJITBackend`.
use crate::memory::Memory;
use cranelift_codegen::binemit::{Addend, CodeOffset, NullTrapSink, Reloc, RelocSink};
use cranelift_codegen::isa::TargetIsa;
use cranelift_codegen::{self, ir, settings};
use cranelift_module::{
Backend, DataContext, DataDescription, Init, Linkage, ModuleNamespace, ModuleResult,
};
use cranelift_native;
use libc;
use std::collections::HashMap;
use std::ffi::CString;
use std::io::Write;
use std::ptr;
use target_lexicon::PointerWidth;
#[cfg(windows)]
use winapi;
const EXECUTABLE_DATA_ALIGNMENT: u8 = 0x10;
const WRITABLE_DATA_ALIGNMENT: u8 = 0x8;
const READONLY_DATA_ALIGNMENT: u8 = 0x1;
/// A builder for `SimpleJITBackend`.
pub struct SimpleJITBuilder {
isa: Box<dyn TargetIsa>,
symbols: HashMap<String, *const u8>,
libcall_names: Box<dyn Fn(ir::LibCall) -> String>,
}
impl SimpleJITBuilder {
/// Create a new `SimpleJITBuilder`.
///
/// The `libcall_names` function provides a way to translate `cranelift_codegen`'s `ir::LibCall`
/// enum to symbols. LibCalls are inserted in the IR as part of the legalization for certain
/// floating point instructions, and for stack probes. If you don't know what to use for this
/// argument, use `cranelift_module::default_libcall_names()`.
pub fn new(libcall_names: Box<dyn Fn(ir::LibCall) -> String>) -> Self {
let flag_builder = settings::builder();
let isa_builder = cranelift_native::builder().unwrap_or_else(|msg| {
panic!("host machine is not supported: {}", msg);
});
let isa = isa_builder.finish(settings::Flags::new(flag_builder));
Self::with_isa(isa, libcall_names)
}
/// Create a new `SimpleJITBuilder` with an arbitrary target. This is mainly
/// useful for testing.
///
/// SimpleJIT requires a `TargetIsa` configured for non-PIC.
///
/// To create a `SimpleJITBuilder` for native use, use the `new` constructor
/// instead.
///
/// The `libcall_names` function provides a way to translate `cranelift_codegen`'s `ir::LibCall`
/// enum to symbols. LibCalls are inserted in the IR as part of the legalization for certain
/// floating point instructions, and for stack probes. If you don't know what to use for this
/// argument, use `cranelift_module::default_libcall_names()`.
pub fn with_isa(
isa: Box<dyn TargetIsa>,
libcall_names: Box<dyn Fn(ir::LibCall) -> String>,
) -> Self {
debug_assert!(!isa.flags().is_pic(), "SimpleJIT requires non-PIC code");
let symbols = HashMap::new();
Self {
isa,
symbols,
libcall_names,
}
}
/// Define a symbol in the internal symbol table.
///
/// The JIT will use the symbol table to resolve names that are declared,
/// but not defined, in the module being compiled. A common example is
/// external functions. With this method, functions and data can be exposed
/// to the code being compiled which are defined by the host.
///
/// If a symbol is defined more than once, the most recent definition will
/// be retained.
///
/// If the JIT fails to find a symbol in its internal table, it will fall
/// back to a platform-specific search (this typically involves searching
/// the current process for public symbols, followed by searching the
/// platform's C runtime).
pub fn symbol<K>(&mut self, name: K, ptr: *const u8) -> &Self
where
K: Into<String>,
{
self.symbols.insert(name.into(), ptr);
self
}
/// Define multiple symbols in the internal symbol table.
///
/// Using this is equivalent to calling `symbol` on each element.
pub fn symbols<It, K>(&mut self, symbols: It) -> &Self
where
It: IntoIterator<Item = (K, *const u8)>,
K: Into<String>,
{
for (name, ptr) in symbols {
self.symbols.insert(name.into(), ptr);
}
self
}
}
/// A `SimpleJITBackend` implements `Backend` and emits code and data into memory where it can be
/// directly called and accessed.
///
/// See the `SimpleJITBuilder` for a convenient way to construct `SimpleJITBackend` instances.
pub struct SimpleJITBackend {
isa: Box<dyn TargetIsa>,
symbols: HashMap<String, *const u8>,
libcall_names: Box<dyn Fn(ir::LibCall) -> String>,
code_memory: Memory,
readonly_memory: Memory,
writable_memory: Memory,
}
/// A record of a relocation to perform.
struct RelocRecord {
offset: CodeOffset,
reloc: Reloc,
name: ir::ExternalName,
addend: Addend,
}
pub struct SimpleJITCompiledFunction {
code: *mut u8,
size: usize,
relocs: Vec<RelocRecord>,
}
pub struct SimpleJITCompiledData {
storage: *mut u8,
size: usize,
relocs: Vec<RelocRecord>,
}
impl SimpleJITBackend {
fn lookup_symbol(&self, name: &str) -> *const u8 {
match self.symbols.get(name) {
Some(&ptr) => ptr,
None => lookup_with_dlsym(name),
}
}
fn get_definition(
&self,
namespace: &ModuleNamespace<Self>,
name: &ir::ExternalName,
) -> *const u8 {
match *name {
ir::ExternalName::User { .. } => {
if namespace.is_function(name) {
let (def, name_str, _signature) = namespace.get_function_definition(&name);
match def {
Some(compiled) => compiled.code,
None => self.lookup_symbol(name_str),
}
} else {
let (def, name_str, _writable) = namespace.get_data_definition(&name);
match def {
Some(compiled) => compiled.storage,
None => self.lookup_symbol(name_str),
}
}
}
ir::ExternalName::LibCall(ref libcall) => {
let sym = (self.libcall_names)(*libcall);
self.lookup_symbol(&sym)
}
_ => panic!("invalid ExternalName {}", name),
}
}
}
impl<'simple_jit_backend> Backend for SimpleJITBackend {
type Builder = SimpleJITBuilder;
/// SimpleJIT compiled function and data objects may have outstanding
/// relocations that need to be performed before the memory can be used.
/// These relocations are performed within `finalize_function` and
/// `finalize_data`.
type CompiledFunction = SimpleJITCompiledFunction;
type CompiledData = SimpleJITCompiledData;
/// SimpleJIT emits code and data into memory, and provides raw pointers
/// to them.
type FinalizedFunction = *const u8;
type FinalizedData = (*mut u8, usize);
/// SimpleJIT emits code and data into memory as it processes them, so it
/// doesn't need to provide anything after the `Module` is complete.
type Product = ();
/// Create a new `SimpleJITBackend`.
fn new(builder: SimpleJITBuilder) -> Self {
Self {
isa: builder.isa,
symbols: builder.symbols,
libcall_names: builder.libcall_names,
code_memory: Memory::new(),
readonly_memory: Memory::new(),
writable_memory: Memory::new(),
}
}
fn isa(&self) -> &dyn TargetIsa {
&*self.isa
}
fn declare_function(&mut self, _name: &str, _linkage: Linkage) {
// Nothing to do.
}
fn declare_data(
&mut self,
_name: &str,
_linkage: Linkage,
_writable: bool,
_align: Option<u8>,
) {
// Nothing to do.
}
fn define_function(
&mut self,
name: &str,
ctx: &cranelift_codegen::Context,
_namespace: &ModuleNamespace<Self>,
code_size: u32,
) -> ModuleResult<Self::CompiledFunction> {
let size = code_size as usize;
let ptr = self
.code_memory
.allocate(size, EXECUTABLE_DATA_ALIGNMENT)
.expect("TODO: handle OOM etc.");
if cfg!(target_os = "linux") && ::std::env::var_os("PERF_BUILDID_DIR").is_some() {
let mut map_file = ::std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(format!("/tmp/perf-{}.map", ::std::process::id()))
.unwrap();
let _ = writeln!(map_file, "{:x} {:x} {}", ptr as usize, code_size, name);
}
let mut reloc_sink = SimpleJITRelocSink::new();
// Ignore traps for now. For now, frontends should just avoid generating code
// that traps.
let mut trap_sink = NullTrapSink {};
unsafe { ctx.emit_to_memory(&*self.isa, ptr, &mut reloc_sink, &mut trap_sink) };
Ok(Self::CompiledFunction {
code: ptr,
size,
relocs: reloc_sink.relocs,
})
}
fn define_data(
&mut self,
_name: &str,
writable: bool,
align: Option<u8>,
data: &DataContext,
_namespace: &ModuleNamespace<Self>,
) -> ModuleResult<Self::CompiledData> {
let &DataDescription {
ref init,
ref function_decls,
ref data_decls,
ref function_relocs,
ref data_relocs,
} = data.description();
let size = init.size();
let storage = if writable {
self.writable_memory
.allocate(size, align.unwrap_or(WRITABLE_DATA_ALIGNMENT))
.expect("TODO: handle OOM etc.")
} else {
self.readonly_memory
.allocate(size, align.unwrap_or(READONLY_DATA_ALIGNMENT))
.expect("TODO: handle OOM etc.")
};
match *init {
Init::Uninitialized => {
panic!("data is not initialized yet");
}
Init::Zeros { .. } => {
unsafe { ptr::write_bytes(storage, 0, size) };
}
Init::Bytes { ref contents } => {
let src = contents.as_ptr();
unsafe { ptr::copy_nonoverlapping(src, storage, size) };
}
}
let reloc = match self.isa.triple().pointer_width().unwrap() {
PointerWidth::U16 => panic!(),
PointerWidth::U32 => Reloc::Abs4,
PointerWidth::U64 => Reloc::Abs8,
};
let mut relocs = Vec::new();
for &(offset, id) in function_relocs {
relocs.push(RelocRecord {
reloc,
offset,
name: function_decls[id].clone(),
addend: 0,
});
}
for &(offset, id, addend) in data_relocs {
relocs.push(RelocRecord {
reloc,
offset,
name: data_decls[id].clone(),
addend,
});
}
Ok(Self::CompiledData {
storage,
size,
relocs,
})
}
fn write_data_funcaddr(
&mut self,
_data: &mut Self::CompiledData,
_offset: usize,
_what: ir::FuncRef,
) {
unimplemented!();
}
fn write_data_dataaddr(
&mut self,
_data: &mut Self::CompiledData,
_offset: usize,
_what: ir::GlobalValue,
_usize: Addend,
) {
unimplemented!();
}
fn finalize_function(
&mut self,
func: &Self::CompiledFunction,
namespace: &ModuleNamespace<Self>,
) -> Self::FinalizedFunction {
use std::ptr::write_unaligned;
for &RelocRecord {
reloc,
offset,
ref name,
addend,
} in &func.relocs
{
let ptr = func.code;
debug_assert!((offset as usize) < func.size);
let at = unsafe { ptr.offset(offset as isize) };
let base = self.get_definition(namespace, name);
// TODO: Handle overflow.
let what = unsafe { base.offset(addend as isize) };
match reloc {
Reloc::Abs4 => {
// TODO: Handle overflow.
#[cfg_attr(feature = "cargo-clippy", allow(clippy::cast_ptr_alignment))]
unsafe {
write_unaligned(at as *mut u32, what as u32)
};
}
Reloc::Abs8 => {
#[cfg_attr(feature = "cargo-clippy", allow(clippy::cast_ptr_alignment))]
unsafe {
write_unaligned(at as *mut u64, what as u64)
};
}
Reloc::X86PCRel4 | Reloc::X86CallPCRel4 => {
// TODO: Handle overflow.
let pcrel = ((what as isize) - (at as isize)) as i32;
#[cfg_attr(feature = "cargo-clippy", allow(clippy::cast_ptr_alignment))]
unsafe {
write_unaligned(at as *mut i32, pcrel)
};
}
Reloc::X86GOTPCRel4 | Reloc::X86CallPLTRel4 => panic!("unexpected PIC relocation"),
_ => unimplemented!(),
}
}
func.code
}
fn get_finalized_function(&self, func: &Self::CompiledFunction) -> Self::FinalizedFunction {
func.code
}
fn finalize_data(
&mut self,
data: &Self::CompiledData,
namespace: &ModuleNamespace<Self>,
) -> Self::FinalizedData {
use std::ptr::write_unaligned;
for &RelocRecord {
reloc,
offset,
ref name,
addend,
} in &data.relocs
{
let ptr = data.storage;
debug_assert!((offset as usize) < data.size);
let at = unsafe { ptr.offset(offset as isize) };
let base = self.get_definition(namespace, name);
// TODO: Handle overflow.
let what = unsafe { base.offset(addend as isize) };
match reloc {
Reloc::Abs4 => {
// TODO: Handle overflow.
#[cfg_attr(feature = "cargo-clippy", allow(clippy::cast_ptr_alignment))]
unsafe {
write_unaligned(at as *mut u32, what as u32)
};
}
Reloc::Abs8 => {
#[cfg_attr(feature = "cargo-clippy", allow(clippy::cast_ptr_alignment))]
unsafe {
write_unaligned(at as *mut u64, what as u64)
};
}
Reloc::X86PCRel4
| Reloc::X86CallPCRel4
| Reloc::X86GOTPCRel4
| Reloc::X86CallPLTRel4 => panic!("unexpected text relocation in data"),
_ => unimplemented!(),
}
}
(data.storage, data.size)
}
fn get_finalized_data(&self, data: &Self::CompiledData) -> Self::FinalizedData {
(data.storage, data.size)
}
fn publish(&mut self) {
// Now that we're done patching, prepare the memory for execution!
self.readonly_memory.set_readonly();
self.code_memory.set_readable_and_executable();
}
/// SimpleJIT emits code and data into memory as it processes them, so it
/// doesn't need to provide anything after the `Module` is complete.
fn finish(self) {}
}
#[cfg(not(windows))]
fn lookup_with_dlsym(name: &str) -> *const u8 {
let c_str = CString::new(name).unwrap();
let c_str_ptr = c_str.as_ptr();
let sym = unsafe { libc::dlsym(libc::RTLD_DEFAULT, c_str_ptr) };
if sym.is_null() {
panic!("can't resolve symbol {}", name);
}
sym as *const u8
}
#[cfg(windows)]
fn lookup_with_dlsym(name: &str) -> *const u8 {
const MSVCRT_DLL: &[u8] = b"msvcrt.dll\0";
let c_str = CString::new(name).unwrap();
let c_str_ptr = c_str.as_ptr();
unsafe {
let handles = [
// try to find the searched symbol in the currently running executable
ptr::null_mut(),
// try to find the searched symbol in local c runtime
winapi::um::libloaderapi::GetModuleHandleA(MSVCRT_DLL.as_ptr() as *const i8),
];
for handle in &handles {
let addr = winapi::um::libloaderapi::GetProcAddress(*handle, c_str_ptr);
if addr.is_null() {
continue;
}
return addr as *const u8;
}
let msg = if handles[1].is_null() {
"(msvcrt not loaded)"
} else {
""
};
panic!("cannot resolve address of symbol {} {}", name, msg);
}
}
struct SimpleJITRelocSink {
pub relocs: Vec<RelocRecord>,
}
impl SimpleJITRelocSink {
pub fn new() -> Self {
Self { relocs: Vec::new() }
}
}
impl RelocSink for SimpleJITRelocSink {
fn reloc_ebb(&mut self, _offset: CodeOffset, _reloc: Reloc, _ebb_offset: CodeOffset) {
unimplemented!();
}
fn reloc_external(
&mut self,
offset: CodeOffset,
reloc: Reloc,
name: &ir::ExternalName,
addend: Addend,
) {
self.relocs.push(RelocRecord {
offset,
reloc,
name: name.clone(),
addend,
});
}
fn reloc_jt(&mut self, _offset: CodeOffset, reloc: Reloc, _jt: ir::JumpTable) {
match reloc {
Reloc::X86PCRelRodata4 => {
// Not necessary to record this unless we are going to split apart code and its
// jumptbl/rodata.
}
_ => {
panic!("Unhandled reloc");
}
}
}
}
| true
|
b69777b2d96568a33b547b7a48b41fdb7e7fbe7a
|
Rust
|
veldsla/faimm
|
/src/lib.rs
|
UTF-8
| 15,228
| 2.890625
| 3
|
[
"MIT"
] |
permissive
|
#![doc(html_root_url = "https://docs.rs/faimm/0.4.0")]
//! This crate provides indexed fasta access by using a memory mapped file to read the sequence
//! data. It is intended for accessing sequence data on genome sized fasta files and provides
//! random access based on base coordinates. Because an indexed fasta file uses a limited number of
//! bases per line separated by (sometimes platform-specific) newlines you cannot directly use the
//! bytes available from the mmap.
//!
//! Access is provided using a view of the mmap using zero-based base coordinates. This view can
//! then be used to iterate over bases (represented as `u8`) or parsed into a string. Naive gc
//! counting is also available.
//!
//! Access to the sequence data doesn't require the `IndexedFasta` to be mutable. This makes
//! it easy to share.
//!
//! # Example
//! ```
//! use faimm::IndexedFasta;
//! let fa = IndexedFasta::from_file("test/genome.fa").expect("Error opening fa");
//! let chr_index = fa.fai().tid("ACGT-25").expect("Cannot find chr in index");
//! let v = fa.view(chr_index,0,50).expect("Cannot get .fa view");
//! //count the bases
//! let counts = v.count_bases();
//! //or print the sequence
//! println!("{}", v.to_string());
//! ```
//! # Limitations
//! The parser uses a simple ascii mask for allowable characters (64..128), does not apply any
//! IUPAC converson or validation. Anything outside this range is silently skipped. This means that
//! also invalid `fasta` will be parsed. The mere presence of an accompanying `.fai` provides the
//! assumption of a valid fasta.
//! Requires Rust >=1.64
//!
//! # Alternatives
//! [Rust-bio](https://crates.io/crates/bio) provides a competent indexed fasta reader. The major
//! difference is that it has an internal buffer an therefore needs to be mutable when performing
//! read operations. faimm is also faster. If you want record based access (without an .fai index
//! file) [rust-bio](https://crates.io/crates/bio) or [seq_io](https://crates.io/crates/seq_io)
//! provide this.
//!
//! # Performance
//! Calculating the gc content of target regions of an exome (231_410 regions) on the Human
//! reference (GRCh38) takes about 0.7 seconds (warm cache), slightly faster than bedtools nuc (0.9s probably a more
//! sound implementation) and rust-bio (1.3s same implementation as example)
//! Some tests show counting can also be improved using simd, but nothing has been released.
use std::fs::File;
use std::io::{self, BufRead, BufReader, Read};
use std::path::Path;
use indexmap::IndexSet;
use memmap2::{Mmap, MmapOptions};
/// The object that stores the parsed fasta index file. You can use it to map chromosome names to
/// indexes and lookup offsets for chr-start:end coordinates
#[derive(Debug, Clone)]
pub struct Fai {
chromosomes: Vec<FaiRecord>,
name_map: IndexSet<String>,
}
impl Fai {
/// Open a fasta index file from path `P`.
pub fn from_file<P: AsRef<Path>>(path: P) -> io::Result<Self> {
let f = File::open(path)?;
let br = BufReader::new(f);
let mut name_map = IndexSet::new();
let mut chromosomes = Vec::new();
for l in br.lines() {
let line = l?;
let p: Vec<_> = line.split('\t').collect();
if p.len() != 5 {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"Expected 5 columns in .fai file.",
));
}
name_map.insert(p[0].to_owned());
let ioerr =
|e, msg| io::Error::new(io::ErrorKind::InvalidData, format!("{}:{}", msg, e));
chromosomes.push(FaiRecord {
len: p[1]
.parse()
.map_err(|e| ioerr(e, "Error parsing chr len in .fai"))?,
offset: p[2]
.parse()
.map_err(|e| ioerr(e, "Error parsing chr offset in .fai"))?,
line_bases: p[3]
.parse()
.map_err(|e| ioerr(e, "Error parsing chr line_bases in .fai"))?,
line_width: p[4]
.parse()
.map_err(|e| ioerr(e, "Error parsing chr line_width in .fai"))?,
});
}
Ok(Fai {
chromosomes,
name_map,
})
}
/// Calculate the slice coordinates (byte offsets).
/// tid is the index of the chromosome (lookup with `Fai::tid` if necessary.
/// start, end: zero based coordinates of the requested range.
///
/// Returns an tuple (start, end) if successful. `io::Error` otherwise.
#[inline]
pub fn offset(&self, tid: usize, start: usize, stop: usize) -> io::Result<(usize, usize)> {
let chr = &self.chromosomes.get(tid).ok_or_else(|| {
io::Error::new(io::ErrorKind::Other, "Chromomsome tid was out of bounds")
})?;
if stop > chr.len {
return Err(io::Error::new(
io::ErrorKind::Other,
"FASTA read interval was out of bounds",
));
}
let start_offset =
chr.offset + (start / chr.line_bases) * chr.line_width + start % chr.line_bases;
let stop_offset =
chr.offset + (stop / chr.line_bases) * chr.line_width + stop % chr.line_bases;
Ok((start_offset, stop_offset))
}
/// Calculate the slice coordinates (byte offsets).
/// tid is the index of the chromosome (lookup with `Fai::tid` if necessary.
///
/// Returns an tuple (start, end) if successful. `io::Error` otherwise.
#[inline]
pub fn offset_tid(&self, tid: usize) -> io::Result<(usize, usize)> {
let chr = &self.chromosomes.get(tid).ok_or_else(|| {
io::Error::new(io::ErrorKind::Other, "Chromomsome tid was out of bounds")
})?;
let start_offset = chr.offset;
let stop_offset =
chr.offset + (chr.len / chr.line_bases) * chr.line_width + chr.len % chr.line_bases;
Ok((start_offset, stop_offset))
}
/// Return the index of the chromosome by name in the fasta index.
///
/// Returns the position of chr `name` if succesful, None otherwise.
#[inline]
pub fn tid(&self, name: &str) -> Option<usize> {
self.name_map.get_index_of(name)
}
/// Return the index of a chromosome in the fasta index.
///
/// Returns the size in bases as usize.
pub fn size(&self, tid: usize) -> io::Result<usize> {
let chr = &self.chromosomes.get(tid).ok_or_else(|| {
io::Error::new(io::ErrorKind::Other, "Chromomsome tid was out of bounds")
})?;
Ok(chr.len)
}
/// Return the name of the chromomsome at index tid
pub fn name(&self, tid: usize) -> io::Result<&String> {
self.name_map.get_index(tid).ok_or_else(|| {
io::Error::new(io::ErrorKind::Other, "Chromomsome tid was out of bounds")
})
}
/// Return the names of the chromosomes from the fasta index in the same order as in the
/// `.fai`. You can use `Fai::tid` to map it back to an index.
///
/// Returns a `Vec<&str>` with the chromosome names.
pub fn names(&self) -> Vec<&str> {
self.name_map.iter().map(|s| s.as_str()).collect()
}
}
/// FaiRecord stores the length, offset, and fasta file characterics of a single chromosome
#[derive(Debug, Clone)]
pub struct FaiRecord {
len: usize,
offset: usize,
line_bases: usize,
line_width: usize,
}
/// The `IndexFasta` can be used to open a fasta file that has a valid .fai index file.
pub struct IndexedFasta {
mmap: Mmap,
fasta_index: Fai,
}
impl IndexedFasta {
/// Open a fasta file from path `P`. It is assumed that it has a valid .fai index file. The
/// .fai file is created by appending .fai to the fasta file.
pub fn from_file<P: AsRef<Path>>(path: P) -> io::Result<Self> {
let mut fai_path = path.as_ref().as_os_str().to_owned();
fai_path.push(".fai");
let fasta_index = Fai::from_file(&fai_path)?;
let file = File::open(path)?;
let mmap = unsafe { MmapOptions::new().map(&file)? };
Ok(IndexedFasta { mmap, fasta_index })
}
/// Use tid, start and end to calculate a slice on the Fasta file. Use this view to iterate
/// over the bases.
///
/// Returns FastaView for the provided chromsome, start, end if successful, Error otherwise.
pub fn view(&self, tid: usize, start: usize, stop: usize) -> io::Result<FastaView> {
if start > stop {
return Err(io::Error::new(
io::ErrorKind::Other,
"Invalid query interval",
));
}
let (start_byte, stop_byte) = self.fasta_index.offset(tid, start, stop)?;
//println!("offset for chr {}:{}-{} is {}-{}", tid, start, stop, start_byte, stop_byte);
Ok(FastaView(&self.mmap[start_byte..stop_byte]))
}
/// Use tid to return a view of an entire chromosome.
///
/// Returns FastaView for the provided chromsome indicated by tid if successful, Error otherwise.
pub fn view_tid(&self, tid: usize) -> io::Result<FastaView> {
let (start_byte, stop_byte) = self.fasta_index.offset_tid(tid)?;
//println!("offset for chr {}:{}-{} is {}-{}", tid, start, stop, start_byte, stop_byte);
Ok(FastaView(&self.mmap[start_byte..stop_byte]))
}
/// Return a reference to the `Fai` that contains information from the fasta index.
///
/// Returns a reference to `Fai`.
pub fn fai(&self) -> &Fai {
&self.fasta_index
}
}
/// A view of a slice of the fasta file bounded by provided coordinates
pub struct FastaView<'a>(&'a [u8]);
impl<'a> FastaView<'a> {
/// Count the occurences of A, C, G, T, N, and other in the current view. This function does
/// not differentiate between upper or lower case bases.
///
/// Returns a `BasecCounts` object.
pub fn count_bases(&self) -> BaseCounts {
let mut bc: BaseCounts = Default::default();
for b in self.bases() {
let v: u8 = b << 3;
if v ^ 8 == 0 {
bc.a += 1;
} else if v ^ 24 == 0 {
bc.c += 1;
} else if v ^ 56 == 0 {
bc.g += 1;
} else if v ^ 112 == 0 {
bc.n += 1;
} else if v ^ 160 == 0 {
bc.t += 1;
} else {
bc.other += 1;
}
}
bc
}
/// Iterator over the bases in the current view. Bases are returned as `u8` representations of
/// the `char`s in the fasta file. Keep only that chars between 164 and 128 (effectively
/// skipping newlines)
pub fn bases(&self) -> impl Iterator<Item = &'a u8> {
self.0.iter().filter(|&&b| b & 192 == 64)
}
}
/// Returns a newly allocated, utf8-validated string with the sequence data in `Self`
impl<'a> ToString for FastaView<'a> {
fn to_string(&self) -> String {
String::from_utf8(self.bases().cloned().collect()).unwrap()
}
}
impl<'a> Read for FastaView<'a> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
let mut read = 0;
let mut skipped = 0;
for (t, s) in buf.iter_mut().zip(self.0.iter().filter(|&&c| {
let base = c & 192 == 64;
if !base {
skipped += 1;
}
base
})) {
*t = *s;
read += 1;
}
self.0 = &self.0[(skipped + read)..];
Ok(read)
}
}
/// Object that contains count occurrences of the most common bases in DNA genome references: A, C, G,
/// T, N and other.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct BaseCounts {
pub a: usize,
pub c: usize,
pub g: usize,
pub t: usize,
pub n: usize,
pub other: usize,
}
/// Initialize basecount with zeros
impl Default for BaseCounts {
fn default() -> BaseCounts {
BaseCounts {
a: 0,
c: 0,
g: 0,
t: 0,
n: 0,
other: 0,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn fai() {
let ir = IndexedFasta::from_file("test/genome.fa").unwrap();
assert_eq!(ir.fai().names().len(), 3);
assert_eq!(ir.fai().tid("ACGT-25"), Some(2));
assert_eq!(ir.fai().tid("NotFound"), None);
assert_eq!(ir.fai().size(2).unwrap(), 100);
assert_eq!(ir.fai().name(2).unwrap(), "ACGT-25");
assert!(ir.fai().name(3).is_err());
}
#[test]
fn view() {
let ir = IndexedFasta::from_file("test/genome.fa").unwrap();
assert_eq!(ir.view(0, 0, 10).unwrap().to_string(), "AAAAAAAAAA");
assert!(ir.view(0, 0, 11).is_err());
assert_eq!(
ir.view(2, 38, 62).unwrap().to_string(),
"CCCCCCCCCCCCGGGGGGGGGGGG"
);
assert_eq!(
ir.view(2, 74, 100).unwrap().to_string(),
"GTTTTTTTTTTTTTTTTTTTTTTTTT"
);
assert!(ir.view(0, 120, 130).is_err());
}
#[test]
fn view_tid() {
let ir = IndexedFasta::from_file("test/genome.fa").unwrap();
assert_eq!(ir.view_tid(0).unwrap().to_string(), "AAAAAAAAAA");
assert_eq!(ir.view_tid(1).unwrap().to_string(),
"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
assert_eq!(ir.view_tid(2).unwrap().to_string(),
"AAAAAAAAAAAAAAAAAAAAAAAAACCCCCCCCCCCCCCCCCCCCCCCCCGGGGGGGGGGGGGGGGGGGGGGGGGTTTTTTTTTTTTTTTTTTTTTTTTT");
assert!(ir.view_tid(3).is_err());
}
#[test]
fn view_bases() {
let ir = IndexedFasta::from_file("test/genome.fa").unwrap();
let v = ir.view(2, 48, 52).unwrap();
let mut b = v.bases();
assert_eq!(b.next(), Some(&b'C'));
assert_eq!(b.next(), Some(&b'C'));
assert_eq!(b.next(), Some(&b'G'));
assert_eq!(b.next(), Some(&b'G'));
assert_eq!(b.next(), None);
}
#[test]
fn view_counts() {
let ir = IndexedFasta::from_file("test/genome.fa").unwrap();
assert_eq!(
ir.view(2, 48, 52).unwrap().count_bases(),
BaseCounts {
c: 2,
g: 2,
..Default::default()
}
);
}
#[test]
fn read_view() {
let ir = IndexedFasta::from_file("test/genome.fa").unwrap();
let mut buf = vec![0; 25];
let mut v = ir.view_tid(2).unwrap();
println!("{}", v.to_string());
assert_eq!(v.read(&mut buf).unwrap(), 25);
assert_eq!(buf, vec![b'A'; 25]);
assert_eq!(v.read(&mut buf).unwrap(), 25);
assert_eq!(buf, vec![b'C'; 25]);
assert_eq!(v.read(&mut buf).unwrap(), 25);
assert_eq!(buf, vec![b'G'; 25]);
let mut buf2 = vec![0; 10];
assert_eq!(v.read(&mut buf2).unwrap(), 10);
assert_eq!(buf2, vec![b'T'; 10]);
assert_eq!(v.read(&mut buf2).unwrap(), 10);
assert_eq!(buf2, vec![b'T'; 10]);
assert_eq!(v.read(&mut buf2).unwrap(), 5);
assert_eq!(&buf2[0..5], vec![b'T'; 5].as_slice());
}
}
| true
|
5b10dda3d1be0f1cbaacdc0c20f78dc4acdfe983
|
Rust
|
endoli/disassemble.rs
|
/src/instruction.rs
|
UTF-8
| 2,139
| 3.046875
| 3
|
[
"Apache-2.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use crate::address::Address;
use std::fmt;
/// An assembly instruction, bytecode operation, VM operation, etc.
///
/// This trait will be implemented for a variety of backends and
/// provides the general means by which the rest of the code in this
/// library can be re-used.
///
/// This is intended to be fairly generic and is how other parts
/// of this library query information that is specific to a given
/// platform and body of generated code.
pub trait Instruction: fmt::Debug + fmt::Display {
/// The [`address`] of this `Instruction`.
///
/// The [`address`] of an instruction must be unique within a
/// [`function`].
///
/// [`address`]: Address
/// [`function`]: crate::Function
fn address(&self) -> Address;
/// The mnemonic for this `Instruction`.
fn mnemonic(&self) -> &str;
/// Any associated `comment` text for this instruction.
fn comment(&self) -> Option<String>;
/// Does this instruction terminate a `BasicBlock`?
///
/// This is used when constructing a [control flow graph]
/// to help break a sequence of instructions into basic
/// blocks.
///
/// [`BasicBlock`]: crate::BasicBlock
fn is_block_terminator(&self) -> bool {
self.is_call() || self.is_local_jump() || self.is_return()
}
/// Does this instruction represent a call?
fn is_call(&self) -> bool;
/// Does this instruction represent a local conditional jump?
fn is_local_conditional_jump(&self) -> bool;
/// Does this instruction represent a local conditional or unconditional jump?
fn is_local_jump(&self) -> bool;
/// Does this instruction represent a function return?
fn is_return(&self) -> bool;
/// If this is a call or local jump, what is the target address?
fn target_address(&self) -> Option<Address>;
}
| true
|
5b4374b8d4143da00a32ec2cf78e4a3c9b34b497
|
Rust
|
ajunlonglive/mockiato
|
/src/arguments.rs
|
UTF-8
| 472
| 2.671875
| 3
|
[
"MIT"
] |
permissive
|
use std::fmt::{Debug, Display};
#[allow(missing_docs)]
pub trait Arguments: Display + Debug {}
#[cfg(test)]
pub(crate) use self::mock::*;
#[cfg(test)]
mod mock {
use super::Arguments;
use std::fmt;
#[derive(Debug)]
pub(crate) struct ArgumentsMock;
impl Arguments for ArgumentsMock {}
impl std::fmt::Display for ArgumentsMock {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "mock")
}
}
}
| true
|
81a4d8cde1579c3d4580ac30a967cdfbc0e4cb01
|
Rust
|
qoollo/bob
|
/bob-common/src/metrics/collector/accumulator.rs
|
UTF-8
| 2,409
| 2.65625
| 3
|
[
"MIT"
] |
permissive
|
use super::snapshot::*;
use std::convert::TryInto;
use std::sync::Arc;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use tokio::sync::mpsc::Receiver;
use tokio::time::{interval, timeout};
const METRICS_RECV_TIMEOUT: Duration = Duration::from_millis(100);
const MAX_METRICS_PER_PERIOD: u64 = 100_000;
pub(crate) struct MetricsAccumulator {
rx: Receiver<Metric>,
interval: Duration,
snapshot: MetricsSnapshot,
readable_snapshot: SharedMetricsSnapshot,
}
impl MetricsAccumulator {
pub(super) fn new(rx: Receiver<Metric>, interval: Duration) -> Self {
Self {
rx,
interval,
snapshot: MetricsSnapshot::default(),
readable_snapshot: Arc::default(),
}
}
// this function runs in other thread, so it would be better if it will take control of arguments
// themselves, not just references
#[allow(clippy::needless_pass_by_value)]
pub(crate) async fn run(mut self) {
let mut interval = interval(self.interval);
loop {
interval.tick().await;
let mut metrics_received = 0;
let timestamp = get_current_unix_timestamp();
while let Ok(om) = timeout(METRICS_RECV_TIMEOUT, self.rx.recv()).await {
match om.map(|m| m.with_timestamp(timestamp)) {
Some(Metric::Counter(counter)) => self.snapshot.process_counter(counter),
Some(Metric::Gauge(gauge)) => self.snapshot.process_gauge(gauge),
Some(Metric::Time(time)) => self.snapshot.process_time(time),
// if recv returns None, then sender is dropped, then no more metrics would come
None => return,
}
metrics_received += 1;
if metrics_received == MAX_METRICS_PER_PERIOD {
break;
}
}
let s = self.snapshot.update_and_get_moment_snapshot();
*self.readable_snapshot.write().expect("rwlock") = s;
}
}
pub(crate) fn get_shared_snapshot(&self) -> SharedMetricsSnapshot {
self.readable_snapshot.clone()
}
}
fn get_current_unix_timestamp() -> i64 {
match SystemTime::now().duration_since(UNIX_EPOCH) {
Ok(n) => n.as_secs().try_into().expect("timestamp conversion"),
Err(_) => panic!("SystemTime before UNIX EPOCH!"),
}
}
| true
|
a4e00e301a80d80d50ece8b0c67d31a21a2d30dd
|
Rust
|
albedium/redox
|
/filesystem/apps/sodium/keystate.rs
|
UTF-8
| 359
| 3.171875
| 3
|
[
"MIT"
] |
permissive
|
/// A key state
pub struct KeyState {
/// Shift pressed
pub shift: bool,
/// Ctrl pressed
pub ctrl: bool,
/// Alt pressed
pub alt: bool,
}
impl KeyState {
/// Create new default keystate
pub fn new() -> KeyState {
KeyState {
shift: false,
ctrl: false,
alt: false,
}
}
}
| true
|
52b3769c2b8322fb7bb94206dc1d46c0052b6389
|
Rust
|
tekjar/rust-learn
|
/tiny-try/read_console/src/main.rs
|
UTF-8
| 2,205
| 3.234375
| 3
|
[
"MIT"
] |
permissive
|
use std::io::{self, BufRead};
fn main(){
let stdin = io::stdin();
for line in stdin.lock().lines(){
println!("{:?}", line);
}
}
/*
pub fn stdin() -> Stdin
-----------------------
Constructs a new handle to the standard input of the current process.
Each handle returned is a reference to a shared global buffer whose access is synchronized via a mutex.
If you need more explicit control over locking, see the lock() method.
*/
/*
Q. Why doesn't this work ?
for line in io::stdin().lock().lines(){
println!("{:?}", line);
}
stdin() returns handle of stdin buffer and lock() returns a reference to the handle. Since hadle isn't binded by any variable, it
gets destroyed at the end of statement and reference returned by lock() would have been pointing to destroyed handle.
XXXXXXXXXXX
XXXXXXXX XXXXXXX
XX Gets destroyed after X Hence rust doesn't allow this.
X the end of statement XX
XX if not binded XX
+-----+ XXXXXX XXXXXXXXXX
| XXXXXXXX
v
+-------------+ +-------------+ +----------------+
| .lock() | | io::stdin()| | |
| +--------> +--------> Global |
| Lock | | StdinReader | Stdin Buffer |
| | | | | |
| | | | | |
+------^------+ +-------------+ +----------------+
|
|
|
|
+------+-------+
| .lines() |
| |
| Iterator |
| |
| |
+--------------+
References:
-----------
http://stackoverflow.com/questions/27468558/rust-lifetime-chaining-function-calls-vs-using-intermediate-variables
http://stackoverflow.com/questions/23440793/why-do-i-get-borrowed-value-does-not-live-long-enough-in-this-example
MADE WITH: http://asciiflow.com/
*/
| true
|
51057e721753979ad27f7e78c43e9e55b10a1875
|
Rust
|
mfonism/jwtvault_examples
|
/src/bin/04_async_postgres_static.rs
|
UTF-8
| 9,820
| 2.625
| 3
|
[] |
no_license
|
use jwtvault::prelude::*;
use jwtvault_examples::database::setup::connection;
use jwtvault_examples::database::users_setup::signup_app_users;
use std::collections::HashMap;
use std::collections::hash_map::DefaultHasher;
use jwtvault::errors::LoginFailed::PasswordHashingFailed;
use postgres::NoTls;
use r2d2::Pool;
use r2d2_postgres::PostgresConnectionManager;
async fn resolve_password_for_user<T: AsRef<str>>(pool: Pool<PostgresConnectionManager<NoTls>>, user: T) -> Result<Option<String>, Error> {
let mut conn = pool.get()?;
let query = format!("SELECT user_password FROM tbl_users WHERE user_id = '{}' ", user.as_ref());
let rs = conn.query(query.as_str(), &[])?;
for row in rs {
let rs: Option<String> = row.get(0);
return Ok(rs);
}
return Ok(None);
}
#[derive(Debug, Clone)]
pub struct DBVault {
public_authentication_certificate: PublicKey,
private_authentication_certificate: PrivateKey,
public_refresh_certificate: PublicKey,
private_refresh_certificate: PrivateKey,
password_hashing_secret: PrivateKey,
store: HashMap<u64, String>,
pool: Pool<PostgresConnectionManager<NoTls>>,
}
impl PersistenceHasher<DefaultHasher> for DBVault {}
impl TrustToken for DBVault {
fn trust_token_bearer(&self) -> bool {
false
}
}
impl PasswordHasher<ArgonHasher<'static>> for DBVault {
fn hash_user_password<T: AsRef<str>>(&self, user: T, password: T) -> Result<String, Error> {
let secret_key = self.password_hashing_secret.as_str();
hash_password_with_argon::<&str>(password.as_ref(), secret_key).map_err(|e| {
PasswordHashingFailed(user.as_ref().to_string(), e.to_string()).into()
})
}
fn verify_user_password<T: AsRef<str>>(&self, user: T, password: T, hash: T) -> Result<bool, Error> {
let secret_key = self.password_hashing_secret.as_str();
verify_user_password_with_argon::<&str>(password.as_ref(), secret_key, hash.as_ref()).map_err(|e| {
PasswordHashingFailed(user.as_ref().to_string(), e.to_string()).into()
})
}
}
impl Store for DBVault {
fn public_authentication_certificate(&self) -> &PublicKey {
&self.public_authentication_certificate
}
fn private_authentication_certificate(&self) -> &PrivateKey {
&self.private_authentication_certificate
}
fn public_refresh_certificate(&self) -> &PublicKey {
&self.public_refresh_certificate
}
fn private_refresh_certificate(&self) -> &PrivateKey {
&self.private_refresh_certificate
}
}
impl DBVault {
pub fn new<T: Keys>(loader: T, pool: Pool<PostgresConnectionManager<NoTls>>) -> Self {
let public_authentication_certificate = loader.public_authentication_certificate().clone();
let private_authentication_certificate = loader.private_authentication_certificate().clone();
let public_refresh_certificate = loader.public_refresh_certificate().clone();
let private_refresh_certificate = loader.private_refresh_certificate().clone();
let password_hashing_secret = loader.password_hashing_secret();
let store = HashMap::new();
Self {
public_authentication_certificate,
private_authentication_certificate,
public_refresh_certificate,
private_refresh_certificate,
password_hashing_secret,
store,
pool,
}
}
}
#[async_trait]
impl Persistence for DBVault {
async fn store(&mut self, key: u64, value: String) {
self.store.insert(key, value);
}
async fn load(&self, key: u64) -> Option<&String> {
self.store.get(&key)
}
async fn remove(&mut self, key: u64) -> Option<String> {
self.store.remove(&key)
}
}
#[async_trait]
impl UserIdentity for DBVault {
async fn check_same_user(&self, _: &str, _: &str) -> Result<(), Error> {
// If the user was encrypted then it can be decrypted and compared
Ok(())
}
}
#[async_trait]
impl UserAuthentication for DBVault {
async fn check_user_valid(&mut self, user: &str, password: &str) -> Result<Option<Session>, Error> {
// lookup database instead of im-memory
let password_from_disk = resolve_password_for_user::<&str>(self.pool.clone(), user).await?;
// let password_from_disk = self.users.get(&user.to_string());
if password_from_disk.is_none() {
let msg = "Login Failed".to_string();
let reason = "Invalid userid/password".to_string();
return Err(LoginFailed::InvalidPassword(msg, reason).into());
};
let password_from_disk = password_from_disk.unwrap();
let result = verify_user_password_with_argon(password, self.password_hashing_secret.as_str(), password_from_disk.as_str())?;
if !result {
let msg = "Login Failed".to_string();
let reason = "Invalid userid/password".to_string();
return Err(LoginFailed::InvalidPassword(msg, reason).into());
};
let reference = digest::<_, DefaultHasher>(user.as_bytes());
let mut server = HashMap::new();
server.insert(reference, user.clone().as_bytes().to_vec());
let session = Session::new(None, Some(server));
Ok(Some(session))
}
}
#[async_trait]
impl Workflow<DefaultHasher, ArgonHasher<'static>> for DBVault {
async fn login(&mut self, user: &str, pass: &str, authentication_token_expiry_in_seconds: Option<i64>, refresh_token_expiry_in_seconds: Option<i64>) -> Result<Token, Error> {
continue_login(self, user, pass, authentication_token_expiry_in_seconds, refresh_token_expiry_in_seconds).await
}
async fn renew(&mut self, user: &str, client_refresh_token: &String, authentication_token_expiry_in_seconds: Option<i64>) -> Result<String, Error> {
continue_renew(self, user, client_refresh_token, authentication_token_expiry_in_seconds).await
}
async fn logout(&mut self, user: &str, client_authentication_token: &String) -> Result<(), Error> {
continue_logout(self, user, client_authentication_token).await
}
async fn revoke(&mut self, client_refresh_token: &String) -> Result<(), Error> {
continue_revoke(self, client_refresh_token).await
}
}
impl Default for DBVault {
fn default() -> Self {
let pool = connection();
if let Err(e) = pool {
eprintln!("DB Connection failed Reason: {}", e.to_string());
};
let pool = connection().ok().unwrap();
Self::new(CertificateManger::default(), pool)
}
}
fn main() {
dotenv::dotenv().ok();
let mut vault = DBVault::default();
// This should be done during user signup
block_on(signup_app_users());
let user_john = "john_doe";
let user_jane = "jane_doe";
// John needs to login now
let token = block_on(vault.login(
user_john,
"john",
None,
None,
));
let token = token.ok().unwrap();
// When John presents authentication token, it can be used to restore John's session info
let server_refresh_token = block_on(resolve_session_from_client_authentication_token(
&mut vault,
user_john,
token.authentication(),
));
let server_refresh_token = server_refresh_token.ok().unwrap();
// server_refresh_token (variable) contains server method which captures client private info
// which never leaves the server
let private_info_about_john = server_refresh_token.server().unwrap();
let key = digest::<_, DefaultHasher>(user_john);
let data_on_server_side = private_info_about_john.get(&key).unwrap();
// server_refresh_token (variable) contains client method which captures client public info
// which is also send back to client
assert!(server_refresh_token.client().is_none());
// Check out the data on client and server which are public and private respectively
println!("[Private] John Info: {}",
String::from_utf8_lossy(data_on_server_side.as_slice()).to_string());
// lets renew authentication token
let new_token = block_on(vault.renew(
user_john,
token.refresh(),
None,
));
let new_token = new_token.ok().unwrap();
// When John presents new authentication token it can be used to restore session info
let result = block_on(resolve_session_from_client_authentication_token(
&mut vault,
user_john,
new_token.as_str(),
));
let _ = result.ok().unwrap();
// Jane needs to login now
let token = block_on(vault.login(
user_jane,
"jane",
None,
None,
));
let token = token.ok().unwrap();
// When Jane presents authentication token, it can be used to restore John's session info
let server_refresh_token = block_on(resolve_session_from_client_authentication_token(
&mut vault,
user_jane,
token.authentication(),
));
let server_refresh_token = server_refresh_token.ok().unwrap();
// server_refresh_token (variable) contains server method which captures client private info
// which never leaves the server
let private_info_about_jane = server_refresh_token.server().unwrap();
let key = digest::<_, DefaultHasher>(user_jane);
let data_on_server_side = private_info_about_jane.get(&key).unwrap();
// server_refresh_token (variable) contains client method which captures client public info
// which is also send back to client
assert!(server_refresh_token.client().is_none());
// Check out the data on client and server which are public and private respectively
println!("[Private] Jane Info: {}",
String::from_utf8_lossy(data_on_server_side.as_slice()).to_string());
}
| true
|
d515c6c05d311607762de771bbd4a3c4e3c60af7
|
Rust
|
morpheyesh/megam_api.rs
|
/src/megam_api/util/sshkeys.rs
|
UTF-8
| 908
| 2.828125
| 3
|
[
"Apache-2.0"
] |
permissive
|
use std::result;
//use rustc_serialize::json;
pub type Result<Success, Error> = result::Result<Success, Error>;
#[derive(Debug)]
pub enum Success { Success }
#[derive(Debug)]
pub enum Error {
NotOkResponse,
}
pub struct SSHKey {
pub name : String,
pub accounts_id : String,
pub path : String,
}
impl SSHKey {
pub fn create(self) -> Result<Success, Error> {
//let CREATE = "/accounts/content";
println!("format {} arguments", "hai");
// you can access struct values using self.first_name
//let body = json::encode(data).unwrap();
// self.megam_api.create(CREATE, body.as_bytes())
if 1 == 1 {
return Ok(Success::Success);
} else {
return Err(Error::NotOkResponse);
}
}
pub fn failure() -> Result<Success, Error> {
if 1 == 1 {
return Err(Error::NotOkResponse);
} else {
return Ok(Success::Success);
}
}
}
| true
|
2009a65e1d6b67b027efa21db7ee1359923609b4
|
Rust
|
kenkoooo/competitive-programming-rs
|
/src/math/determinant.rs
|
UTF-8
| 884
| 3.375
| 3
|
[
"CC0-1.0"
] |
permissive
|
pub fn calc_determinant<T>(mut matrix: Vec<Vec<T>>) -> T
where
T: Copy + std::ops::Sub<Output = T> + std::ops::Mul<Output = T> + std::ops::Div<Output = T>,
{
let n = matrix.len();
assert!(
matrix.iter().all(|row| row.len() == n),
"The matrix is not square!"
);
for i in 0..n {
for j in (i + 1)..n {
let b = matrix[j][i] / matrix[i][i];
for k in 0..n {
matrix[j][k] = matrix[j][k] - matrix[i][k] * b;
}
}
}
let mut det = matrix[0][0];
for i in 1..n {
det = det * matrix[i][i];
}
det
}
#[cfg(test)]
mod tests {
use crate::math::determinant::calc_determinant;
#[test]
fn test_calc_determinant() {
let a = vec![vec![1, 2, 3], vec![2, 2, 4], vec![2, 4, 5]];
let det = calc_determinant(a);
assert_eq!(det, 2);
}
}
| true
|
c4b50ff6b1488fe4a620654a970018a966cd03dd
|
Rust
|
sirkibsirkib/naive_fourier
|
/src/lib.rs
|
UTF-8
| 644
| 2.578125
| 3
|
[] |
no_license
|
extern crate simple_vector2d;
extern crate textplots;
use simple_vector2d::consts::ZERO_F32 as ZERO;
use std::ops::Add;
type Pt = simple_vector2d::Vector2<f32>;
pub fn fourier(samples: &[f32], sample_period: f32, query_frequency: f32) -> f32 {
let in_step = sample_period / samples.len() as f32;
samples
.iter()
.enumerate()
.map(|(i, &sample)| {
let rotations: f32 = query_frequency * i as f32 * in_step;
let p: Pt = Pt::unit_vector(rotations) * sample;
p
})
.fold(ZERO, Pt::add)
.length()
/ samples.len() as f32
}
#[cfg(test)]
mod tests;
| true
|
6e9b1cb7e5964f02c77d5c58afffdb4fd6f64441
|
Rust
|
tuxmark5/north
|
/north_core/src/model/member/reference_link.rs
|
UTF-8
| 1,950
| 2.65625
| 3
|
[] |
no_license
|
use {
crate::{
Node, NodeId,
model::member::{
Member, Reference,
member_descr::MemberDescr
},
util::downcast::{
Downcast, DowncastEntry
}
},
std::{
any::{Any, TypeId},
fmt::{Debug},
mem
},
};
////////////////////////////////////////////////////////////////////////////////////////////////
pub trait ReferenceLink: Member {
fn reference_obj<'a>(&self, object: &'a dyn Node) -> &'a dyn Any;
fn reference_obj_debug<'a>(&self, object: &'a dyn Node) -> &'a dyn Debug;
fn reference_obj_mut<'a>(&self, object: &'a mut dyn Node) -> &'a mut dyn Any;
fn target_node<'a>(&self, object: &'a dyn Node) -> &'a Option<NodeId>;
fn target_node_mut<'a>(&self, object: &'a mut dyn Node) -> &'a mut Option<NodeId>;
}
////////////////////////////////////////////////////////////////////////////////////////////////
impl<O, N, T> Downcast for MemberDescr<O, Reference<N, T>> where
O: 'static, N: Node + ?Sized, T: 'static + Debug
{
impl_downcast!(dyn ReferenceLink);
}
impl<O, N, T> ReferenceLink for MemberDescr<O, Reference<N, T>> where
O: 'static, N: Node + ?Sized, T: 'static + Debug
{
fn reference_obj<'a>(&self, object: &'a dyn Node) -> &'a dyn Any {
&self.data(object).ref_object
}
fn reference_obj_debug<'a>(&self, object: &'a dyn Node) -> &'a dyn Debug {
&self.data(object).ref_object
}
fn reference_obj_mut<'a>(&self, object: &'a mut dyn Node) -> &'a mut dyn Any {
&mut self.data_mut(object).ref_object
}
fn target_node<'a>(&self, object: &'a dyn Node) -> &'a Option<NodeId> {
let result = &self.data(object).target_node;
unsafe { mem::transmute(result) }
}
fn target_node_mut<'a>(&self, object: &'a mut dyn Node) -> &'a mut Option<NodeId> {
let result = &mut self.data_mut(object).target_node;
unsafe { mem::transmute(result) }
}
}
////////////////////////////////////////////////////////////////////////////////////////////////
| true
|
f37d114ea29087824686d70847f28b3494a9c270
|
Rust
|
sisshiki1969/ruruby
|
/ruruby/src/builtin/exception.rs
|
UTF-8
| 5,804
| 2.546875
| 3
|
[
"MIT"
] |
permissive
|
use crate::*;
pub(crate) fn init(globals: &mut Globals) -> Value {
let exception = Module::class_under_object();
globals.set_toplevel_constant("Exception", exception);
exception.add_builtin_class_method(globals, "new", exception_new);
exception.add_builtin_class_method(globals, "exception", exception_new);
exception.add_builtin_class_method(globals, "allocate", exception_allocate);
exception.add_builtin_method_by_str(globals, "inspect", inspect);
exception.add_builtin_method_by_str(globals, "to_s", tos);
builtin::module::set_attr_accessor(
globals,
exception,
&Args::new2(
Value::symbol_from_str("message"),
Value::symbol_from_str("backtrace"),
),
)
.unwrap();
// StandardError.
let standard_error = Module::class_under(exception);
BUILTINS.with(|m| m.borrow_mut().standard = standard_error.into());
globals.set_toplevel_constant("StandardError", standard_error);
let err = Module::class_under(standard_error);
globals.set_toplevel_constant("ArgumentError", err);
let err = Module::class_under(standard_error);
globals.set_toplevel_constant("IndexError", err);
let err = Module::class_under(standard_error);
globals.set_toplevel_constant("RegexpError", err);
let err = Module::class_under(standard_error);
globals.set_toplevel_constant("TypeError", err);
let err = Module::class_under(standard_error);
globals.set_toplevel_constant("FiberError", err);
let name_error = Module::class_under(standard_error);
globals.set_toplevel_constant("NameError", name_error);
let err = Module::class_under(name_error);
globals.set_toplevel_constant("NoMethodError", err);
let err = Module::class_under(standard_error);
globals.set_toplevel_constant("ZeroDivisionError", err);
let err = Module::class_under(standard_error);
globals.set_toplevel_constant("StopIteration", err);
let err = Module::class_under(standard_error);
globals.set_toplevel_constant("LocalJumpError", err);
// RuntimeError
let runtime_error = Module::class_under(standard_error);
globals.set_toplevel_constant("RuntimeError", runtime_error);
let frozen_error = Module::class_under(runtime_error);
globals.set_toplevel_constant("FrozenError", frozen_error);
let script_error = Module::class_under(exception);
globals.set_toplevel_constant("ScriptError", script_error);
// Subclasses of ScriptError.
let err = Module::class_under(script_error);
globals.set_toplevel_constant("SyntaxError", err);
let err = Module::class_under(exception);
globals.set_toplevel_constant("SystemExit", err);
exception.into()
}
// Class methods
fn exception_new(vm: &mut VM, self_val: Value, args: &Args2) -> VMResult {
args.check_args_range(0, 1)?;
let self_val = self_val.into_module();
let new_instance = if args.len() == 0 {
let class_name = self_val.name();
Value::exception(self_val, RubyError::none(class_name))
} else {
let mut arg = vm[0];
let err = arg.expect_string("1st arg")?;
Value::exception(self_val, RubyError::none(err))
};
// Call initialize method if it exists.
vm.eval_initialize(self_val, new_instance, args)?;
Ok(new_instance)
}
fn exception_allocate(_: &mut VM, self_val: Value, args: &Args2) -> VMResult {
args.check_args_num(0)?;
let self_val = self_val.into_module();
let new_instance = Value::exception(self_val, RubyError::none(""));
Ok(new_instance)
}
// Instance methods
fn inspect(_: &mut VM, self_val: Value, args: &Args2) -> VMResult {
args.check_args_num(0)?;
let val = self_val;
let err = match val.if_exception() {
Some(err) => err,
_ => unreachable!("Not a Exception."),
};
Ok(Value::string(format!(
"#<{}: {}>",
val.get_class_name(),
err.message()
)))
}
fn tos(_: &mut VM, self_val: Value, args: &Args2) -> VMResult {
args.check_args_num(0)?;
let val = self_val;
let err = match val.if_exception() {
Some(err) => err,
_ => unreachable!("Not a Exception."),
};
Ok(Value::string(err.message()))
}
#[cfg(test)]
mod tests {
use crate::tests::*;
#[test]
fn exception() {
let program = r##"
assert Exception, StandardError.superclass
assert StandardError, RuntimeError.superclass
assert StandardError, ArgumentError.superclass
assert StandardError, NameError.superclass
assert StandardError, TypeError.superclass
assert StandardError, Math::DomainError.superclass
assert RuntimeError, FrozenError.superclass
assert NameError, NoMethodError.superclass
assert "#<Exception: Exception>", Exception.new.inspect
assert "#<Exception: foo>", Exception.new("foo").inspect
assert "Exception", Exception.new.to_s
assert "foo", Exception.new("foo").to_s
assert "#<StandardError: StandardError>", StandardError.new.inspect
assert "#<StandardError: foo>", StandardError.new("foo").inspect
assert "StandardError", StandardError.new.to_s
assert "foo", StandardError.new("foo").to_s
assert Exception.singleton_class, StandardError.singleton_class.superclass
assert "#<NoMethodError: NoMethodError>", NoMethodError.new.inspect
assert "#<NoMethodError: foo>", NoMethodError.new("foo").inspect
assert "NoMethodError", NoMethodError.new.to_s
assert "foo", NoMethodError.new("foo").to_s
assert StandardError.singleton_class, NameError.singleton_class.superclass
assert StandardError.singleton_class, TypeError.singleton_class.superclass
"##;
assert_script(program);
}
}
| true
|
6273742ecc71c65434b5b07ada58bc38b2a1aea3
|
Rust
|
jonwingfield/atsamd09-rs
|
/atsamd09d14a/pm/apbbmask/mod.rs
|
UTF-8
| 10,522
| 2.53125
| 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::APBBMASK {
#[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 = r" Value of the field"]
pub struct PAC1_R {
bits: bool,
}
impl PAC1_R {
#[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 DSU_R {
bits: bool,
}
impl DSU_R {
#[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 NVMCTRL_R {
bits: bool,
}
impl NVMCTRL_R {
#[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 PORT_R {
bits: bool,
}
impl PORT_R {
#[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 DMAC_R {
bits: bool,
}
impl DMAC_R {
#[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 HMATRIX_R {
bits: bool,
}
impl HMATRIX_R {
#[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" Proxy"]
pub struct _PAC1_W<'a> {
w: &'a mut W,
}
impl<'a> _PAC1_W<'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 = 0;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _DSU_W<'a> {
w: &'a mut W,
}
impl<'a> _DSU_W<'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 _NVMCTRL_W<'a> {
w: &'a mut W,
}
impl<'a> _NVMCTRL_W<'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 _PORT_W<'a> {
w: &'a mut W,
}
impl<'a> _PORT_W<'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 = 3;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _DMAC_W<'a> {
w: &'a mut W,
}
impl<'a> _DMAC_W<'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 = r" Proxy"]
pub struct _HMATRIX_W<'a> {
w: &'a mut W,
}
impl<'a> _HMATRIX_W<'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
}
}
impl R {
#[doc = r" Value of the register as raw bits"]
#[inline]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bit 0 - PAC1 APB Clock Enable"]
#[inline]
pub fn pac1_(&self) -> PAC1_R {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 0;
((self.bits >> OFFSET) & MASK as u32) != 0
};
PAC1_R { bits }
}
#[doc = "Bit 1 - DSU APB Clock Enable"]
#[inline]
pub fn dsu_(&self) -> DSU_R {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 1;
((self.bits >> OFFSET) & MASK as u32) != 0
};
DSU_R { bits }
}
#[doc = "Bit 2 - NVMCTRL APB Clock Enable"]
#[inline]
pub fn nvmctrl_(&self) -> NVMCTRL_R {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 2;
((self.bits >> OFFSET) & MASK as u32) != 0
};
NVMCTRL_R { bits }
}
#[doc = "Bit 3 - PORT APB Clock Enable"]
#[inline]
pub fn port_(&self) -> PORT_R {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 3;
((self.bits >> OFFSET) & MASK as u32) != 0
};
PORT_R { bits }
}
#[doc = "Bit 4 - DMAC APB Clock Enable"]
#[inline]
pub fn dmac_(&self) -> DMAC_R {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 4;
((self.bits >> OFFSET) & MASK as u32) != 0
};
DMAC_R { bits }
}
#[doc = "Bit 6 - HMATRIX APB Clock Enable"]
#[inline]
pub fn hmatrix_(&self) -> HMATRIX_R {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 6;
((self.bits >> OFFSET) & MASK as u32) != 0
};
HMATRIX_R { bits }
}
}
impl W {
#[doc = r" Reset value of the register"]
#[inline]
pub fn reset_value() -> W {
W { bits: 127 }
}
#[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 - PAC1 APB Clock Enable"]
#[inline]
pub fn pac1_(&mut self) -> _PAC1_W {
_PAC1_W { w: self }
}
#[doc = "Bit 1 - DSU APB Clock Enable"]
#[inline]
pub fn dsu_(&mut self) -> _DSU_W {
_DSU_W { w: self }
}
#[doc = "Bit 2 - NVMCTRL APB Clock Enable"]
#[inline]
pub fn nvmctrl_(&mut self) -> _NVMCTRL_W {
_NVMCTRL_W { w: self }
}
#[doc = "Bit 3 - PORT APB Clock Enable"]
#[inline]
pub fn port_(&mut self) -> _PORT_W {
_PORT_W { w: self }
}
#[doc = "Bit 4 - DMAC APB Clock Enable"]
#[inline]
pub fn dmac_(&mut self) -> _DMAC_W {
_DMAC_W { w: self }
}
#[doc = "Bit 6 - HMATRIX APB Clock Enable"]
#[inline]
pub fn hmatrix_(&mut self) -> _HMATRIX_W {
_HMATRIX_W { w: self }
}
}
| true
|
85db5d321a35d170a0e9c77ed72c1bc8dc523abf
|
Rust
|
orium/rustybit
|
/src/datatype/value.rs
|
UTF-8
| 455
| 3.28125
| 3
|
[] |
no_license
|
use std::fmt::Show;
use std::fmt::Formatter;
/* This makes it safe to change to subunits of satoshi in the future without
* creating nasty bugs, because type system.
*/
#[allow(dead_code)]
pub enum Value
{
Satoshi(u64)
}
impl Show for Value
{
fn fmt(&self, f : &mut Formatter) -> Result<(), ::std::fmt::Error>
{
match *self
{
Value::Satoshi(v) => write!(f,"{}.{:05} m฿",v/100_000,v%100_000)
}
}
}
| true
|
31d189350c6ffe50bcc178aca29069ae55848d04
|
Rust
|
derekdreery/pipewire-rs
|
/libspa/src/dict.rs
|
UTF-8
| 10,044
| 3.359375
| 3
|
[
"MIT"
] |
permissive
|
use bitflags::bitflags;
use std::{ffi::CStr, fmt, marker::PhantomData};
pub trait ReadableDict {
/// Obtain the pointer to the raw `spa_dict` struct.
fn get_dict_ptr(&self) -> *const spa_sys::spa_dict;
/// An iterator over all raw key-value pairs.
/// The iterator element type is `(&CStr, &CStr)`.
fn iter_cstr(&self) -> CIter {
let first_elem_ptr = unsafe { (*self.get_dict_ptr()).items };
CIter {
next: first_elem_ptr,
end: unsafe { first_elem_ptr.offset((*self.get_dict_ptr()).n_items as isize) },
_phantom: PhantomData,
}
}
/// An iterator over all key-value pairs that are valid utf-8.
/// The iterator element type is `(&str, &str)`.
fn iter(&self) -> Iter {
Iter {
inner: self.iter_cstr(),
}
}
/// An iterator over all keys that are valid utf-8.
/// The iterator element type is &str.
fn keys(&self) -> Keys {
Keys {
inner: self.iter_cstr(),
}
}
/// An iterator over all values that are valid utf-8.
/// The iterator element type is &str.
fn values(&self) -> Values {
Values {
inner: self.iter_cstr(),
}
}
/// Returns the number of key-value-pairs in the dict.
/// This is the number of all pairs, not only pairs that are valid-utf8.
fn len(&self) -> usize {
unsafe { (*self.get_dict_ptr()).n_items as usize }
}
/// Returns `true` if the dict is empty, `false` if it is not.
fn is_empty(&self) -> bool {
self.len() == 0
}
/// Returns the bitflags that are set for the dict.
fn flags(&self) -> Flags {
Flags::from_bits_truncate(unsafe { (*self.get_dict_ptr()).flags })
}
/// Get the value associated with the provided key.
///
/// If the dict does not contain the key or the value is non-utf8, `None` is returned.
/// Use [`iter_cstr`] if you need a non-utf8 key or value.
///
/// [`iter_cstr`]: #method.iter_cstr
// FIXME: Some items might be integers, booleans, floats, doubles or pointers instead of strings.
// Perhaps we should return an enum that can be any of these values.
// See https://gitlab.freedesktop.org/pipewire/pipewire-rs/-/merge_requests/12#note_695914.
fn get(&self, key: &str) -> Option<&str> {
self.iter().find(|(k, _)| *k == key).map(|(_, v)| v)
}
}
pub trait WritableDict {
/// Insert the key-value pair, overwriting any old value.
fn insert<T: Into<Vec<u8>>>(&mut self, key: T, value: T);
/// Remove the key-value pair if it exists.
fn remove<T: Into<Vec<u8>>>(&mut self, key: T);
/// Clear the object, removing all key-value pairs.
fn clear(&mut self);
}
/// A wrapper for a `*const spa_dict` struct that does not take ownership of the data,
/// useful for dicts shared to us via FFI.
pub struct ForeignDict(*const spa_sys::spa_dict);
impl ForeignDict {
/// Wraps the provided pointer in a read-only `ForeignDict` struct without taking ownership of the struct pointed to.
///
/// # Safety
///
/// - The provided pointer must point to a valid, well-aligned `spa_dict` struct, and must not be `NULL`.
/// - The struct pointed to must be kept valid for the entire lifetime of the created `Dict`.
///
/// Violating any of these rules will result in undefined behaviour.
pub unsafe fn from_ptr(dict: *const spa_sys::spa_dict) -> Self {
debug_assert!(
!dict.is_null(),
"Dict must not be created from a pointer that is NULL"
);
Self(dict)
}
}
impl ReadableDict for ForeignDict {
fn get_dict_ptr(&self) -> *const spa_sys::spa_dict {
self.0
}
}
impl fmt::Debug for ForeignDict {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// FIXME: Find a way to display flags too.
f.debug_map().entries(self.iter_cstr()).finish()
}
}
bitflags! {
pub struct Flags: u32 {
// These flags are redefinitions from
// https://gitlab.freedesktop.org/pipewire/pipewire/-/blob/master/spa/include/spa/utils/dict.h
const SORTED = spa_sys::SPA_DICT_FLAG_SORTED;
}
}
pub struct CIter<'a> {
next: *const spa_sys::spa_dict_item,
/// Points to the first element outside of the allocated area.
end: *const spa_sys::spa_dict_item,
_phantom: PhantomData<&'a str>,
}
impl<'a> Iterator for CIter<'a> {
type Item = (&'a CStr, &'a CStr);
fn next(&mut self) -> Option<Self::Item> {
if !self.next.is_null() && self.next < self.end {
let k = unsafe { CStr::from_ptr((*self.next).key) };
let v = unsafe { CStr::from_ptr((*self.next).value) };
self.next = unsafe { self.next.add(1) };
Some((k, v))
} else {
None
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
let bound: usize = unsafe { self.next.offset_from(self.end) as usize };
// We know the exact value, so lower bound and upper bound are the same.
(bound, Some(bound))
}
}
pub struct Iter<'a> {
inner: CIter<'a>,
}
impl<'a> Iterator for Iter<'a> {
type Item = (&'a str, &'a str);
fn next(&mut self) -> Option<Self::Item> {
self.inner
.find_map(|(k, v)| k.to_str().ok().zip(v.to_str().ok()))
}
fn size_hint(&self) -> (usize, Option<usize>) {
// Lower bound is 0, as all keys left might not be valid UTF-8.
(0, self.inner.size_hint().1)
}
}
pub struct Keys<'a> {
inner: CIter<'a>,
}
impl<'a> Iterator for Keys<'a> {
type Item = &'a str;
fn next(&mut self) -> Option<Self::Item> {
self.inner.find_map(|(k, _)| k.to_str().ok())
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
}
pub struct Values<'a> {
inner: CIter<'a>,
}
impl<'a> Iterator for Values<'a> {
type Item = &'a str;
fn next(&mut self) -> Option<Self::Item> {
self.inner.find_map(|(_, v)| v.to_str().ok())
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
}
#[cfg(test)]
mod tests {
use super::{Flags, ForeignDict, ReadableDict};
use spa_sys::{spa_dict, spa_dict_item};
use std::{ffi::CString, ptr};
/// Create a raw dict with the specified number of key-value pairs.
///
/// `num_items` must not be zero, or this function will panic.
///
/// Each key value pair is `("K<n>", "V<n>")`, with *\<n\>* being an element of the range `0..num_items`.
///
/// The function returns a tuple consisting of:
/// 1. An allocation (`Vec`) containing the raw Key and Value Strings.
/// 2. An allocation (`Vec`) containing all the items.
/// 3. The created `spa_dict` struct.
///
/// The first two items must be kept alive for the entire lifetime of the returned `spa_dict` struct.
fn make_raw_dict(
num_items: u32,
) -> (
Vec<(CString, CString)>,
Vec<spa_dict_item>,
spa_sys::spa_dict,
) {
assert!(num_items != 0, "num_items must not be zero");
let mut strings: Vec<(CString, CString)> = Vec::with_capacity(num_items as usize);
let mut items: Vec<spa_dict_item> = Vec::with_capacity(num_items as usize);
for i in 0..num_items {
let k = CString::new(format!("K{}", i)).unwrap();
let v = CString::new(format!("V{}", i)).unwrap();
let item = spa_dict_item {
key: k.as_ptr(),
value: v.as_ptr(),
};
strings.push((k, v));
items.push(item);
}
let raw = spa_dict {
flags: Flags::empty().bits,
n_items: num_items,
items: items.as_ptr(),
};
(strings, items, raw)
}
#[test]
fn test_empty_dict() {
let raw = spa_dict {
flags: Flags::empty().bits,
n_items: 0,
items: ptr::null(),
};
let dict = unsafe { ForeignDict::from_ptr(&raw) };
let iter = dict.iter_cstr();
assert_eq!(0, dict.len());
iter.for_each(|_| panic!("Iterated over non-existing item"));
}
#[test]
fn test_iter_cstr() {
let (_strings, _items, raw) = make_raw_dict(2);
let dict = unsafe { ForeignDict::from_ptr(&raw) };
let mut iter = dict.iter_cstr();
assert_eq!(
(
CString::new("K0").unwrap().as_c_str(),
CString::new("V0").unwrap().as_c_str()
),
iter.next().unwrap()
);
assert_eq!(
(
CString::new("K1").unwrap().as_c_str(),
CString::new("V1").unwrap().as_c_str()
),
iter.next().unwrap()
);
assert_eq!(None, iter.next());
}
#[test]
fn test_iterators() {
let (_strings, _items, raw) = make_raw_dict(2);
let dict = unsafe { ForeignDict::from_ptr(&raw) };
let mut iter = dict.iter();
assert_eq!(("K0", "V0"), iter.next().unwrap());
assert_eq!(("K1", "V1"), iter.next().unwrap());
assert_eq!(None, iter.next());
let mut key_iter = dict.keys();
assert_eq!("K0", key_iter.next().unwrap());
assert_eq!("K1", key_iter.next().unwrap());
assert_eq!(None, key_iter.next());
let mut val_iter = dict.values();
assert_eq!("V0", val_iter.next().unwrap());
assert_eq!("V1", val_iter.next().unwrap());
assert_eq!(None, val_iter.next());
}
#[test]
fn test_get() {
let (_strings, _items, raw) = make_raw_dict(1);
let dict = unsafe { ForeignDict::from_ptr(&raw) };
assert_eq!(Some("V0"), dict.get("K0"));
}
#[test]
fn test_debug() {
let (_strings, _items, raw) = make_raw_dict(1);
let dict = unsafe { ForeignDict::from_ptr(&raw) };
assert_eq!(r#"{"K0": "V0"}"#, &format!("{:?}", dict))
}
}
| true
|
bc5f0ca80693c34b6df9dc4998b47a2211e55581
|
Rust
|
apache/incubator-teaclave-sgx-sdk
|
/samplecode/unit-test/enclave/src/test_serialize.rs
|
UTF-8
| 9,426
| 2.890625
| 3
|
[
"BSD-3-Clause",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
use sgx_serialize::{DeSerializable, DeSerializeHelper, Serializable, SerializeHelper};
use std::fmt::Debug;
use std::string::{String, ToString};
use std::vec::Vec;
fn test_serialize_internal<T: Serializable + DeSerializable>(target: &T) -> Option<T> {
let helper = SerializeHelper::new();
let data = helper.encode(target).unwrap();
let helper = DeSerializeHelper::<T>::new(data);
helper.decode()
}
pub fn test_serialize_struct() {
#[derive(Serializable, DeSerializable, PartialEq, Debug)]
struct TestSturct {
a1: u32,
a2: u32,
}
let a = TestSturct {
a1: 2017u32,
a2: 829u32,
};
let c = test_serialize_internal::<TestSturct>(&a).unwrap();
assert_eq!(a, c);
#[derive(Serializable, DeSerializable, PartialEq, Debug)]
struct TestStructUnit;
let a = TestStructUnit;
let c = test_serialize_internal::<TestStructUnit>(&a).unwrap();
assert_eq!(a, c);
#[derive(Serializable, DeSerializable, PartialEq, Debug)]
struct TestStructNewType(i32);
let a = TestStructNewType(2017i32);
let c = test_serialize_internal::<TestStructNewType>(&a).unwrap();
assert_eq!(a, c);
#[derive(Serializable, DeSerializable, PartialEq, Debug)]
struct TestStructTuple(i32, i32);
let a = TestStructTuple(2017i32, 928i32);
let c = test_serialize_internal::<TestStructTuple>(&a).unwrap();
assert_eq!(a, c);
}
pub fn test_serialize_enum() {
#[derive(Serializable, DeSerializable, PartialEq, Debug)]
struct TestSturct {
a1: u32,
a2: u32,
}
#[derive(Serializable, DeSerializable, PartialEq, Debug)]
enum TestEnum {
EnumUnit,
EnumNewType(u32),
EnumTuple(u32, u32),
EnumStruct { a1: i32, a2: i32 },
EnumSubStruct(TestSturct),
}
let a = TestSturct {
a1: 2017u32,
a2: 928u32,
};
let a = TestEnum::EnumSubStruct(a);
let c = test_serialize_internal::<TestEnum>(&a).unwrap();
assert_eq!(a, c);
let a = TestEnum::EnumTuple(2017, 829);
let c = test_serialize_internal::<TestEnum>(&a).unwrap();
assert_eq!(a, c);
let a = TestEnum::EnumNewType(2017);
let c = test_serialize_internal::<TestEnum>(&a).unwrap();
assert_eq!(a, c);
let a = TestEnum::EnumStruct { a1: 2017, a2: 829 };
let c = test_serialize_internal::<TestEnum>(&a).unwrap();
assert_eq!(a, c);
}
pub fn test_serialize_base() {
#[derive(Serializable, DeSerializable, PartialEq, Clone, Debug)]
struct Struct {
a: (),
b: u8,
c: u16,
d: u32,
e: u64,
f: usize,
g: i8,
h: i16,
i: i32,
j: i64,
k: isize,
l: char,
m: String,
n: f32,
o: f64,
p: bool,
q: Option<u32>,
}
fn check_round_trip<T: Serializable + DeSerializable + PartialEq + Debug>(values: Vec<T>) {
for value in values {
let decoded = test_serialize_internal::<T>(&value).unwrap();
assert_eq!(value, decoded);
}
}
fn test_unit() {
check_round_trip(vec![(), (), (), ()]);
}
fn test_u8() {
let mut vec = vec![];
for i in ::std::u8::MIN..::std::u8::MAX {
vec.push(i);
}
check_round_trip(vec);
}
fn test_u16() {
for i in ::std::u16::MIN..::std::u16::MAX {
check_round_trip(vec![1, 2, 3, i, i, i]);
}
}
fn test_u32() {
check_round_trip(vec![1, 2, 3, ::std::u32::MIN, 0, 1, ::std::u32::MAX, 2, 1]);
}
fn test_u64() {
check_round_trip(vec![1, 2, 3, ::std::u64::MIN, 0, 1, ::std::u64::MAX, 2, 1]);
}
fn test_usize() {
check_round_trip(vec![
1,
2,
3,
::std::usize::MIN,
0,
1,
::std::usize::MAX,
2,
1,
]);
}
fn test_i8() {
let mut vec = vec![];
for i in ::std::i8::MIN..::std::i8::MAX {
vec.push(i);
}
check_round_trip(vec);
}
fn test_i16() {
for i in ::std::i16::MIN..::std::i16::MAX {
check_round_trip(vec![-1, 2, -3, i, i, i, 2]);
}
}
fn test_i32() {
check_round_trip(vec![
-1,
2,
-3,
::std::i32::MIN,
0,
1,
::std::i32::MAX,
2,
1,
]);
}
fn test_i64() {
check_round_trip(vec![
-1,
2,
-3,
::std::i64::MIN,
0,
1,
::std::i64::MAX,
2,
1,
]);
}
fn test_isize() {
check_round_trip(vec![
-1,
2,
-3,
::std::isize::MIN,
0,
1,
::std::isize::MAX,
2,
1,
]);
}
fn test_bool() {
check_round_trip(vec![false, true, true, false, false]);
}
fn test_f32() {
let mut vec = vec![];
for i in -100..100 {
vec.push((i as f32) / 3.0);
}
check_round_trip(vec);
}
fn test_f64() {
let mut vec = vec![];
for i in -100..100 {
vec.push((i as f64) / 3.0);
}
check_round_trip(vec);
}
fn test_char() {
let vec = vec!['a', 'b', 'c', 'd', 'A', 'X', ' ', '#', 'Ö', 'Ä', 'µ', '€'];
check_round_trip(vec);
}
fn test_string() {
let vec = vec![
"abcbuÖeiovÄnameÜavmpßvmea€µsbpnvapeapmaebn".to_string(),
"abcbuÖganeiovÄnameÜavmpßvmea€µsbpnvapeapmaebn".to_string(),
"abcbuÖganeiovÄnameÜavmpßvmea€µsbpapmaebn".to_string(),
"abcbuÖganeiovÄnameÜavmpßvmeabpnvapeapmaebn".to_string(),
"abcbuÖganeiÄnameÜavmpßvmea€µsbpnvapeapmaebn".to_string(),
"abcbuÖganeiovÄnameÜavmpßvmea€µsbpmaebn".to_string(),
"abcbuÖganeiovÄnameÜavmpßvmea€µnvapeapmaebn".to_string(),
];
check_round_trip(vec);
}
fn test_option() {
check_round_trip(vec![Some(-1i8)]);
check_round_trip(vec![Some(-2i16)]);
check_round_trip(vec![Some(-3i32)]);
check_round_trip(vec![Some(-4i64)]);
check_round_trip(vec![Some(-5isize)]);
let none_i8: Option<i8> = None;
check_round_trip(vec![none_i8]);
let none_i16: Option<i16> = None;
check_round_trip(vec![none_i16]);
let none_i32: Option<i32> = None;
check_round_trip(vec![none_i32]);
let none_i64: Option<i64> = None;
check_round_trip(vec![none_i64]);
let none_isize: Option<isize> = None;
check_round_trip(vec![none_isize]);
}
fn test_struct() {
check_round_trip(vec![Struct {
a: (),
b: 10,
c: 11,
d: 12,
e: 13,
f: 14,
g: 15,
h: 16,
i: 17,
j: 18,
k: 19,
l: 'x',
m: "abc".to_string(),
n: 20.5,
o: 21.5,
p: false,
q: None,
}]);
check_round_trip(vec![Struct {
a: (),
b: 101,
c: 111,
d: 121,
e: 131,
f: 141,
g: -15,
h: -16,
i: -17,
j: -18,
k: -19,
l: 'y',
m: "def".to_string(),
n: -20.5,
o: -21.5,
p: true,
q: Some(1234567),
}]);
}
#[derive(PartialEq, Clone, Debug, Serializable, DeSerializable)]
enum Enum {
Variant1,
Variant2(usize, f32),
Variant3 { a: i32, b: char, c: bool },
}
fn test_enum() {
check_round_trip(vec![
Enum::Variant1,
Enum::Variant2(1, 2.5),
Enum::Variant3 {
a: 3,
b: 'b',
c: false,
},
Enum::Variant3 {
a: -4,
b: 'f',
c: true,
},
]);
}
fn test_sequence() {
let mut vec = vec![];
for i in -100i64..100i64 {
vec.push(i * 100000);
}
check_round_trip(vec![vec]);
}
fn test_hash_map() {
use std::collections::HashMap;
let mut map = HashMap::new();
for i in -100i64..100i64 {
map.insert(i * 100000, i * 10000);
}
check_round_trip(vec![map]);
}
fn test_tuples() {
check_round_trip(vec![('x', (), false, 0.5f32)]);
check_round_trip(vec![(9i8, 10u16, 1.5f64)]);
check_round_trip(vec![(-12i16, 11u8, 12usize)]);
check_round_trip(vec![(1234567isize, 100000000000000u64, 99999999999999i64)]);
check_round_trip(vec![(String::new(), "some string".to_string())]);
}
test_unit();
test_u8();
test_u16();
test_u32();
test_u64();
test_usize();
test_i8();
test_i16();
test_i32();
test_i64();
test_isize();
test_bool();
test_f32();
test_f64();
test_char();
test_string();
test_option();
test_struct();
test_enum();
test_sequence();
test_hash_map();
test_tuples();
}
| true
|
35e6cc2c9be7aace1253906021362aa6183a16d5
|
Rust
|
SDRust/png_decode
|
/src/lib.rs
|
UTF-8
| 5,944
| 2.875
| 3
|
[] |
no_license
|
extern crate flate2;
use std::fs::File;
use std::io::Read;
pub struct Chunk {
typ: u32,
data: Vec<u8>,
}
pub fn eat_u32(i: &mut usize, data: &[u8]) -> u32 {
let mut b: u32 = 0;
b |= data[3 + *i] as u32;
b |= (data[2 + *i] as u32) << 8;
b |= (data[1 + *i] as u32) << 16;
b |= (data[0 + *i] as u32) << 24;
*i += 4;
return b;
}
pub fn read_chunks(contents: Vec<u8>) -> Vec<Chunk> {
let mut build: Vec<Chunk> = Vec::new();
let mut i: usize = 8;
while i < contents.len() {
let chunklen: u32 = eat_u32(&mut i, &contents);
let typ: u32 = eat_u32(&mut i, &contents);
println!("chunklen is {}, type={:x}", chunklen, typ);
let bytes: Vec<u8> = Vec::from(&contents[i .. i + (chunklen as usize)]);
// + 4 to skip past CRC.
i = i + (chunklen as usize) + 4;
build.push(Chunk{typ: typ, data: bytes});
println!("Done read {} bytes", i);
}
return build;
}
pub fn read_png(filename: &str) -> Vec<Chunk> {
let mut file = File::open(filename).unwrap();
let mut contents: Vec<u8> = Vec::new();
let result = file.read_to_end(&mut contents).unwrap();
println!("Read {} bytes", result);
let chunks: Vec<Chunk> = read_chunks(contents);
return chunks;
}
#[derive(Default)]
pub struct IHDRInfo {
width: u32,
height: u32,
bit_depth: u8,
color_type: u8,
compression_method: u8,
filter_method: u8,
interlace_method: u8,
}
pub fn process_ihdr(ch: &Chunk) -> IHDRInfo {
assert!(ch.data.len() == 13);
let mut info: IHDRInfo = IHDRInfo::default();
let mut i: usize = 0;
info.width = eat_u32(&mut i, &ch.data);
info.height = eat_u32(&mut i, &ch.data);
info.bit_depth = ch.data[i];
info.color_type = ch.data[i + 1];
info.compression_method = ch.data[i + 2];
info.filter_method = ch.data[i + 3];
info.interlace_method = ch.data[i + 4];
return info;
}
#[derive(Clone, Copy)]
pub struct RGBA { dat: [u8; 4] }
pub struct Row { pixels: Vec<RGBA>, }
const ZERO_RGBA: RGBA = RGBA{dat:[0; 4]};
pub fn convert_to_rows(ihdr: &IHDRInfo, data: Vec<u8>) -> Vec<Row> {
assert!(ihdr.bit_depth == 8);
assert!(ihdr.color_type == 2);
println!("data length: {}, height: {}, width: {}", data.len(), ihdr.height, ihdr.width);
let pixelsize: usize = 3;
let row_width: usize = (ihdr.width as usize) * pixelsize + 1;
let prev_scan_line: Vec<RGBA> = vec![ZERO_RGBA; ihdr.width as usize];
for rownum in 0 .. ihdr.height as usize {
let mut i: usize = rownum * row_width;
let filtertype: u8 = data[i];
i += 1;
let mut build: Vec<RGBA> = vec![ZERO_RGBA; ihdr.width as usize];
let mut prev: RGBA = ZERO_RGBA;
let mut prev_scan_line_prev: RGBA = ZERO_RGBA;
for colnum in 0 .. ihdr.width as usize {
let r: u8 = data[i + colnum*3];
let g: u8 = data[i + colnum*3 + 1];
let b: u8 = data[i + colnum*3 + 2];
let pix: RGBA = RGBA{dat:[r, g, b, 0]};
let up: RGBA = prev_scan_line[colnum];
let newpix: RGBA = filter_pixel(filtertype, pix,
prev,
up,
prev_scan_line_prev);
build[colnum] = newpix;
prev = pix;
prev_scan_line_prev = up;
}
}
return Vec::new();
}
pub fn filter_pixel(filtertype: u8, pix: RGBA, left: RGBA, up: RGBA, upleft: RGBA) -> RGBA {
let mut build: RGBA = ZERO_RGBA;
for i in 0..3 {
build.dat[i] = match filtertype {
0 => pix.dat[i],
1 => pix.dat[i].wrapping_add(left.dat[i]),
2 => pix.dat[i].wrapping_add(up.dat[i]),
3 => pix.dat[i].wrapping_add((((left.dat[i] as u32) + (up.dat[i] as u32)) >> 1) as u8),
4 => pix.dat[i].wrapping_add(paeth_predictor(left.dat[i] as i32, up.dat[i] as i32, upleft.dat[i] as i32)),
_ => panic!("bad filtertype")
}
}
return build;
}
use std::num;
pub fn paeth_predictor(a: i32, b: i32, c: i32) -> u8 {
let p: i32 = a + b - c;
let pa: i32 = (p - a).abs();
let pb: i32 = (p - b).abs();
let pc: i32 = (p - c).abs();
if pa <= pb && pa <= pc {
return a as u8;
} else if pb <= pc {
return b as u8;
} else {
return c as u8;
}
}
pub fn process_png(png: Vec<Chunk>) {
let ihdr: IHDRInfo = process_ihdr(&png[0]);
assert!(ihdr.compression_method == 0); // assert deflate
assert!(ihdr.filter_method == 0); // assert adaptive
// TODON'T: this.
assert!(ihdr.interlace_method == 0); // assert non-interlaced
let mut compressed_data: Vec<u8> = Vec::new();
for i in 1..png.len()-1 {
if png[i].typ == 0x49444154 {
compressed_data.extend(&png[i].data);
}
}
assert!(png[png.len()-1].typ == 0x49454e44);
assert!(png[png.len()-1].data.len() == 0);
let inflated_data: Vec<u8> = inflate_bytes(&compressed_data);
let rows: Vec<Row> = convert_to_rows(&ihdr, inflated_data);
let mut num_zeros: usize = 0;
for row in rows.iter() {
for pix in row.pixels.iter() {
if pix.dat[0] == 0 && pix.dat[1] == 0 && pix.dat[2] == 0 {
num_zeros += 1;
}
}
}
println!("There were {} zeros.", num_zeros);
}
use flate2::read::*;
pub fn inflate_bytes(b: &[u8]) -> Vec<u8> {
let mut d = ZlibDecoder::new(b);
let mut res: Vec<u8> = Vec::new();
d.read_to_end(&mut res);
println!("res length = {}", res.len());
return res;
}
pub fn printbytes(bytes: &[u8]) {
for i in 0..40 {
print!("{:02x}", bytes[i]);
}
println!("");
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
let v: Vec<Chunk> = read_png("PNG_demo.png");
process_png(v);
}
}
| true
|
3b1e9dd3406c3bb79f16058bf085aa8465c68d63
|
Rust
|
RoccoDev/bbCraft
|
/server/mc_server_impl/src/net/connection.rs
|
UTF-8
| 3,784
| 2.59375
| 3
|
[
"MIT"
] |
permissive
|
// Copyright (c) 2019 RoccoDev
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
use std::ffi::CString;
use std::net::{Shutdown, TcpStream};
use crate::api::player_connect;
use crate::net::encryption::EncryptionResponsePacket;
use crate::net::handshake::{DisconnectPacket, HandshakePacket, LoginPacket};
use crate::net::packet::PacketHandler;
use crate::util::ssl::SslInfo;
use super::packet::Packet;
#[derive(Debug)]
pub enum State {
HANDSHAKE, LOGIN, STATUS
}
#[derive(Deserialize, Clone)]
pub struct PlayerIdentity {
pub name: String,
pub id: String
}
pub struct Connection {
pub stream: TcpStream,
pub state: State,
pub alive: bool,
pub key: &'static SslInfo,
pub player: PlayerIdentity,
pub verify_token: i32,
pub is_online: bool
}
impl Connection {
pub fn new(stream: TcpStream, key: &'static SslInfo, is_online: bool) -> Connection {
let verify_token: i32 = rand::random();
Connection {
stream,
state: State::HANDSHAKE,
alive: true,
key,
player: PlayerIdentity {
name: String::new(),
id: String::new()
},
verify_token,
is_online
}
}
pub fn disconnect(&mut self) {
self.stream.shutdown(Shutdown::Both);
self.alive = false;
std::thread::yield_now();
}
pub fn kick(&mut self, reason: String) {
DisconnectPacket::new(reason).packet.write(self).unwrap();
}
fn call_api(&mut self, uuid: String, name: String) -> String {
unsafe {
let uuid_ptr =
if uuid.len() == 0 {std::ptr::null_mut()} else {CString::new(uuid).unwrap().into_raw()};
let name_ptr =
if name.len() == 0 {std::ptr::null_mut()} else {CString::new(name).unwrap().into_raw()};
let result = player_connect(uuid_ptr, name_ptr);
let result = CString::from_raw(result);
let result = result.to_str().unwrap();
String::from(result)
}
}
pub fn api_kick(&mut self, uuid: String, name: String) {
unsafe {
let string = Connection::call_api(self, uuid, name);
DisconnectPacket::new(string).packet.write(self).unwrap();
}
}
pub fn api_kick_enc(&mut self, uuid: String, name: String, enc_key: Vec<u8>) {
unsafe {
let string = Connection::call_api(self, uuid, name);
DisconnectPacket::new(string).packet.write_enc(self, enc_key).unwrap();
}
}
pub fn listen(&mut self) {
loop {
if !self.alive {
break;
}
let packet = Packet::new(&mut self.stream);
match packet {
Ok(packet) => {
match packet.info.id {
0x0 => {
match self.state {
State::HANDSHAKE => {
HandshakePacket {packet: &packet}.handle(self);
},
State::LOGIN => {
LoginPacket {packet: &packet}
.handle(self);
},
_ => {}
}
},
0x01 => {
EncryptionResponsePacket {packet}.handle(self);
}
_ => {}
}
}
Err(error) => {
self.disconnect();
}
}
}
}
}
| true
|
3400cd998e2ccaf55f904157c6ca2213256dff40
|
Rust
|
marco-c/gecko-dev-wordified
|
/third_party/rust/extend/tests/compile_pass/hello_world.rs
|
UTF-8
| 266
| 2.953125
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
use
extend
:
:
ext
;
#
[
ext
]
impl
i32
{
fn
add_one
(
&
self
)
-
>
Self
{
self
+
1
}
fn
foo
(
)
-
>
MyType
{
MyType
}
}
#
[
derive
(
Debug
Eq
PartialEq
)
]
struct
MyType
;
fn
main
(
)
{
assert_eq
!
(
i32
:
:
foo
(
)
MyType
)
;
assert_eq
!
(
1
.
add_one
(
)
2
)
;
}
| true
|
fee1d77bde6049b62557f954c098f43b41c2415b
|
Rust
|
vshotarov/advent-of-code-2020
|
/day09/src/main.rs
|
UTF-8
| 1,957
| 3.359375
| 3
|
[] |
no_license
|
use std::io::{self, Read};
use std::collections::VecDeque;
static BUFFER_SIZE: usize = 25;
fn main() -> std::io::Result<()> {
let mut input = String::new();
io::stdin().read_to_string(&mut input)?;
let first_invalid_number = solve_part1(&input)?;
solve_part2(&input, first_invalid_number)?;
Ok(())
}
fn solve_part1(input: &str) -> std::io::Result<i64> {
let mut buffer: VecDeque<i64> = VecDeque::new();
for line in input.lines() {
let buffer_len = buffer.len();
let number = line.parse::<i64>().unwrap();
if buffer_len == BUFFER_SIZE {
let mut found_two_sum = false;
for n in &buffer {
if buffer.contains(&(number - n)) {
found_two_sum = true;
break;
}
}
if !found_two_sum {
println!("Part 1: {}", number);
return Ok(number);
}
}
buffer.push_back(number);
if buffer_len > BUFFER_SIZE - 1 {
buffer.pop_front();
}
}
Ok(-1)
}
fn solve_part2(input: &str, sum: i64) -> std::io::Result<()> {
let numbers: Vec<i64> = input.lines().map(|x| x.parse::<i64>().unwrap()).collect();
let mut left_pointer = 0;
let mut right_pointer = 1;
let mut running_sum = numbers[0] + numbers[1];
loop {
if running_sum == sum {
println!("Part 2: {}",
numbers[left_pointer..right_pointer+1].iter().min().unwrap() +
numbers[left_pointer..right_pointer+1].iter().max().unwrap());
break;
}
else if running_sum < sum {
right_pointer += 1;
running_sum += numbers[right_pointer];
}
else {
left_pointer += 1;
right_pointer = left_pointer + 1;
running_sum = numbers[left_pointer] + numbers[right_pointer];
}
}
Ok(())
}
| true
|
6d8e31ee91fbae7933a1fe7c6607db9a7ea4a1a1
|
Rust
|
doyoubi/Blastoise
|
/src/test/utils.rs
|
UTF-8
| 3,633
| 2.734375
| 3
|
[] |
no_license
|
use std::fmt::{Display, Debug};
use std::option::Option::None;
use std::result::Result::Ok;
use std::ptr::{write, read};
use libc::malloc;
use ::parser::lexer::TokenIter;
use ::parser::compile_error::ErrorList;
use ::parser::common::exp_list_to_string;
use ::utils::pointer::{write_string, read_string};
use ::store::buffer::DataPtr;
macro_rules! gen_token {
($input_str:expr) => ({
let line = ::parser::lexer::TokenLine::parse($input_str);
assert!(line.errors.is_empty());
line.tokens.clone()
});
}
macro_rules! assert_pattern {
($expression:expr, $pattern:pat) => (
match $expression {
$pattern => (),
other => panic!("assert pattern fail, pattern not matched, found {:?}", other),
}
)
}
pub fn test_by_display_str<Res : Display + Debug>(
input_str : &str,
token_num : usize,
parse_func : fn(&mut TokenIter) -> Result<Res, ErrorList>,
debug_str : &str) {
let tokens = gen_token!(input_str);
assert_eq!(tokens.len(), token_num);
let mut it = tokens.iter();
let res = parse_func(&mut it);
let res = extract!(res, Ok(res), res);
assert_eq!(format!("{}", res), debug_str);
assert_pattern!(it.next(), None);
}
pub fn test_by_list_to_str<Res : Display + Debug>(
input_str : &str,
token_num : usize,
parse_func : fn(&mut TokenIter) -> Result<Vec<Res>, ErrorList>,
debug_str : &str) {
let tokens = gen_token!(input_str);
assert_eq!(tokens.len(), token_num);
let mut it = tokens.iter();
let res = parse_func(&mut it);
let res = extract!(res, Ok(res), res);
assert_eq!(exp_list_to_string(&res), debug_str);
assert_pattern!(it.next(), None);
}
pub fn remove_blanks(s : &str) -> String {
let mut result = String::new();
for c in s.chars() {
match c {
'\n' | ' ' | '\t' => continue,
_ => result.push(c),
};
}
result
}
macro_rules! gen_plan_helper {
($input_str:expr, $manager:expr) => ({
use ::exec::gen_plan::gen_table_set;
use ::parser::common::Statement;
use ::parser::sem_check::check_sem;
use ::exec::gen_plan::gen_plan;
let tokens = gen_token!($input_str);
let stmt = Statement::parse(&mut tokens.iter());
let mut stmt = extract!(stmt, Ok(stmt), stmt);
let table_set = gen_table_set(&stmt, &$manager);
assert_pattern!(check_sem(&mut stmt, &table_set), Ok(()));
gen_plan(stmt, $manager)
})
}
macro_rules! gen_parse_result {
($class:ident :: $parse_func:ident, $input_str:expr) => ({
let tokens = gen_token!($input_str);
extract!($class::$parse_func(&mut tokens.iter()), Ok(result), result)
})
}
// test code in ::utils
#[test]
fn test_raw_str_convert() {
unsafe{
let p : DataPtr = malloc(3);
let s = "ab".to_string();
write_string(p, &s, 3);
assert_eq!(read::<u8>(p as *const u8), 97);
assert_eq!(read::<u8>((p as *const u8).offset(1)), 98);
assert_eq!(read_string(p, 2), "ab");
assert_eq!(read_string(p, 3), "ab");
}
unsafe{
let p : DataPtr = malloc(3);
let s = "abc".to_string();
write_string(p, &s, 3);
assert_eq!(read::<u8>(p as *const u8), 97);
assert_eq!(read::<u8>((p as *const u8).offset(1)), 98);
assert_eq!(read::<u8>((p as *const u8).offset(2)), 99);
assert_eq!(read_string(p, 3), "abc");
}
}
| true
|
5e6a161421af6f5fbb7ee92a8078690d58556355
|
Rust
|
lu-zero/testcase-wasi-alloc
|
/src/main.rs
|
UTF-8
| 1,862
| 3
| 3
|
[] |
no_license
|
use std::marker::PhantomData;
use std::alloc::*;
use std::mem;
#[derive(Debug, PartialEq, Eq)]
pub struct PlaneData {
ptr: std::ptr::NonNull<u8>,
_marker: PhantomData<u8>,
len: usize,
align: usize,
}
unsafe impl Send for PlaneData {}
unsafe impl Sync for PlaneData {}
impl Clone for PlaneData {
fn clone(&self) -> Self {
let mut pd = unsafe { Self::new_uninitialized(self.len, self.align) };
pd.copy_from_slice(self);
pd
}
}
impl std::ops::Deref for PlaneData {
type Target = [u8];
fn deref(&self) -> &[u8] {
unsafe {
let p = self.ptr.as_ptr();
std::slice::from_raw_parts(p, self.len)
}
}
}
impl std::ops::DerefMut for PlaneData {
fn deref_mut(&mut self) -> &mut [u8] {
unsafe {
let p = self.ptr.as_ptr();
std::slice::from_raw_parts_mut(p, self.len)
}
}
}
impl std::ops::Drop for PlaneData {
fn drop(&mut self) {
unsafe {
dealloc(self.ptr.as_ptr() as *mut u8, Self::layout(self.len, self.align));
}
}
}
impl PlaneData {
unsafe fn layout(len: usize, align: usize) -> Layout {
Layout::from_size_align_unchecked(
len * mem::size_of::<u8>(),
1 << align,
)
}
unsafe fn new_uninitialized(len: usize, align: usize) -> Self {
let ptr = {
let ptr = alloc(Self::layout(len, align)) as *mut u8;
std::ptr::NonNull::new_unchecked(ptr)
};
PlaneData { ptr, len, align, _marker: PhantomData }
}
pub fn new(len: usize, align: usize) -> Self {
let mut pd = unsafe { Self::new_uninitialized(len, align) };
for (i, v) in pd.iter_mut().enumerate() {
eprintln!("index at {} len {}", i, len);
*v = 128;
}
pd
}
}
fn main() {
use std::str::FromStr;
let align = usize::from_str(&std::env::args().nth(1).unwrap_or("5".into())).unwrap();
let _pd = PlaneData::new(640 * 480, align);
}
| true
|
db98e47d368a1357b224d4244cd95301918c99f6
|
Rust
|
canhmai/BLAKE3f
|
/src/gpu/mod.rs
|
UTF-8
| 20,307
| 2.890625
| 3
|
[
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"CC0-1.0"
] |
permissive
|
//! GPU acceleration for BLAKE3.
//!
//! This module allows accelerating a [`Hasher`] through SPIR-V shaders.
//!
//! [`Hasher`]: ../struct.Hasher.html
use super::*;
use core::mem;
use core::ops::{Deref, DerefMut};
use core::slice;
/// Control uniform for the BLAKE3 shader.
///
/// This uniform contains the information necessary for a BLAKE3 shader to
/// correctly hash one level of the BLAKE3 tree structure.
#[repr(C)]
#[derive(Clone)]
pub struct GpuControl {
k: [u32; 8],
t: [u32; 2],
d: u32,
}
impl GpuControl {
fn new(key: &CVWords, chunk_counter: u64, flags: u8) -> Self {
Self {
k: *key,
t: [counter_low(chunk_counter), counter_high(chunk_counter)],
d: flags.into(),
}
}
fn plus_chunks(&self, chunks: u64) -> Self {
let t = self.chunk_counter() + chunks;
Self {
k: self.k,
t: [counter_low(t), counter_high(t)],
d: self.d,
}
}
#[inline]
fn key(&self) -> &CVWords {
&self.k
}
#[inline]
fn chunk_counter(&self) -> u64 {
self.t[0] as u64 | (self.t[1] as u64) << 32
}
#[inline]
fn flags(&self) -> u8 {
self.d as u8
}
/// Returns the bytes to be copied to the control uniform in the GPU.
///
/// The contents of the returned slice are opaque and should be interpreted
/// only by the shader.
#[inline]
pub fn as_bytes(&self) -> &[u8] {
// According to the specification, the host and the device must have
// the same endianness, so no endian conversion is necessary even on
// big-endian hosts.
debug_assert_eq!(
mem::size_of_val(self),
shaders::blake3::CONTROL_UNIFORM_SIZE,
"must not have padding"
);
unsafe { slice::from_raw_parts(self as *const Self as *const u8, mem::size_of_val(self)) }
}
}
// Variant of compress_subtree_wide which takes parents as input.
fn compress_parents_wide<J: Join>(
input: &[u8],
key: &CVWords,
flags: u8,
platform: Platform,
out: &mut [u8],
) -> usize {
debug_assert!(input.len().is_power_of_two());
// Note that the single block case does *not* bump the SIMD degree up to 2
// when it is 1. This allows Rayon the option of multi-threading even the
// 2-block case, which can help performance on smaller platforms.
if input.len() <= platform.simd_degree() * BLOCK_LEN {
return compress_parents_parallel(input, key, flags, platform, out);
}
// With more than simd_degree blocks, we need to recurse. Start by dividing
// the input into left and right subtrees. (Note that this is only optimal
// as long as the SIMD degree is a power of 2. If we ever get a SIMD degree
// of 3 or something, we'll need a more complicated strategy.)
debug_assert_eq!(platform.simd_degree().count_ones(), 1, "power of 2");
let (left, right) = input.split_at(input.len() / 2);
// Make space for the child outputs. Here we use MAX_SIMD_DEGREE_OR_2 to
// account for the special case of returning 2 outputs when the SIMD degree
// is 1.
let mut cv_array = [0; 2 * MAX_SIMD_DEGREE_OR_2 * OUT_LEN];
let degree = if left.len() == BLOCK_LEN {
// The "simd_degree=1 and we're at the leaf nodes" case.
debug_assert_eq!(platform.simd_degree(), 1);
1
} else {
cmp::max(platform.simd_degree(), 2)
};
let (left_out, right_out) = cv_array.split_at_mut(degree * OUT_LEN);
// Recurse! This uses multiple threads if the "rayon" feature is enabled.
let (left_n, right_n) = J::join(
|| compress_parents_wide::<J>(left, key, flags, platform, left_out),
|| compress_parents_wide::<J>(right, key, flags, platform, right_out),
left.len(),
right.len(),
);
// The special case again. If simd_degree=1, then we'll have left_n=1 and
// right_n=1. Rather than compressing them into a single output, return
// them directly, to make sure we always have at least two outputs.
debug_assert_eq!(left_n, degree);
debug_assert!(right_n >= 1 && right_n <= left_n);
if left_n == 1 {
out[..2 * OUT_LEN].copy_from_slice(&cv_array[..2 * OUT_LEN]);
return 2;
}
// Otherwise, do one layer of parent node compression.
let num_children = left_n + right_n;
compress_parents_parallel(
&cv_array[..num_children * OUT_LEN],
key,
flags,
platform,
out,
)
}
// Variant of compress_subtree_to_parent_node which takes parents as input.
fn compress_parents_to_parent_node<J: Join>(
input: &[u8],
key: &CVWords,
flags: u8,
platform: Platform,
) -> [u8; BLOCK_LEN] {
debug_assert!(input.len() > BLOCK_LEN);
let mut cv_array = [0; 2 * MAX_SIMD_DEGREE_OR_2 * OUT_LEN];
let mut num_cvs = compress_parents_wide::<J>(input, &key, flags, platform, &mut cv_array);
debug_assert!(num_cvs >= 2);
// If MAX_SIMD_DEGREE is greater than 2 and there's enough input,
// compress_parents_wide() returns more than 2 chaining values. Condense
// them into 2 by forming parent nodes repeatedly.
let mut out_array = [0; MAX_SIMD_DEGREE_OR_2 * OUT_LEN / 2];
while num_cvs > 2 {
let cv_slice = &cv_array[..num_cvs * OUT_LEN];
num_cvs = compress_parents_parallel(cv_slice, key, flags, platform, &mut out_array);
cv_array[..num_cvs * OUT_LEN].copy_from_slice(&out_array[..num_cvs * OUT_LEN]);
}
*array_ref!(cv_array, 0, 2 * OUT_LEN)
}
/// GPU-accelerated Hasher.
///
/// This is a wrapper around a [`Hasher`] which also allows exporting the key
/// and flags to be used by a GPU shader, and importing the shader's result.
///
/// This wrapper should be used with care, since incorrect use can lead to a
/// wrong hash output. It also allows extracting the key from the state, which
/// would otherwise not be allowed in safe code.
///
/// This wrapper can be freely converted to its inner [`Hasher`], through the
/// `Deref`, `DerefMut`, and `Into` traits. Prefer to use the inner [`Hasher`]
/// wherever the extra functionality from this wrapper is not needed.
///
/// [`Hasher`]: ../struct.Hasher.html
#[derive(Clone, Debug, Default)]
pub struct GpuHasher {
inner: Hasher,
}
impl GpuHasher {
/// Wrapper for [`Hasher::new`](../struct.Hasher.html#method.new).
#[inline]
pub fn new() -> Self {
Self {
inner: Hasher::new(),
}
}
/// Wrapper for [`Hasher::new_keyed`](../struct.Hasher.html#method.new_keyed).
#[inline]
pub fn new_keyed(key: &[u8; KEY_LEN]) -> Self {
Self {
inner: Hasher::new_keyed(key),
}
}
/// Wrapper for [`Hasher::new_derive_key`](../struct.Hasher.html#method.new_derive_key).
#[inline]
pub fn new_derive_key(context: &str) -> Self {
Self {
inner: Hasher::new_derive_key(context),
}
}
/// Obtain the [`GpuControl`](struct.GpuControl.html) to hash full chunks starting with `chunk_counter`
/// or parent nodes.
pub fn gpu_control(&self, chunk_counter: u64) -> GpuControl {
GpuControl::new(&self.key, chunk_counter, self.chunk_state.flags)
}
/// GPU-accelerated version of [`update_with_join`].
///
/// Unlike [`update_with_join`], this method receives the parents computed
/// by one or more applications of the BLAKE3 shader.
///
/// This method has several restrictions. The size of the shader input must
/// be a power of two, it must be naturally aligned within the hash input,
/// and the hasher state must not have any leftover bytes in its internal
/// buffers. The simplest way to follow these invariants is to use this
/// method, with the same chunk count and buffer size, for all of the input
/// except for a variable-sized tail, which can use [`update_with_join`] or
/// [`update`].
///
/// Note: the chunk counter is implicit in this method, but it must be the
/// same as the chunk counter in the [`GpuControl`] passed to the shader,
/// otherwise it will lead to a wrong hash output.
///
/// Note: on a big-endian host, this method will swap the endianness of the
/// shader output in-place.
///
/// [`update`]: #method.update
/// [`update_with_join`]: #method.update_with_join
/// [`GpuControl`]: struct.GpuControl.html
pub fn update_from_gpu<J: Join>(&mut self, chunk_count: u64, parents: &mut [u8]) -> &mut Self {
assert_eq!(self.chunk_state.len(), 0, "leftover buffered bytes");
let chunk_counter = self.chunk_state.chunk_counter;
// These three checks make sure the increment of t0 in the shader did not overflow.
assert!(chunk_count.is_power_of_two(), "bad chunk count");
assert!(chunk_count <= (1 << 32), "chunk count overflow");
assert_eq!(chunk_counter % chunk_count, 0, "misaligned hash");
assert_eq!(parents.len() % OUT_LEN, 0, "invalid hash size");
let parent_count = (parents.len() / OUT_LEN) as u64;
assert_eq!(chunk_count % parent_count, 0, "invalid child count");
// The lazy merge of the CV stack needs at least 2 inputs.
// And compress_parents_to_parent_node needs at least 2 blocks.
assert!(parent_count > 2, "invalid parent count");
// The shader inputs and outputs are 32-bit words, which are in native byte order.
// The chunk shader byte swaps its input, but neither shader byte swaps its output.
// Since the rest of the code assumes little endian, byte swap the buffer here.
Self::swap_endian::<J>(parents);
let cv_pair = compress_parents_to_parent_node::<J>(
parents,
&self.key,
self.chunk_state.flags,
self.chunk_state.platform,
);
let left_cv = array_ref!(cv_pair, 0, 32);
let right_cv = array_ref!(cv_pair, 32, 32);
// Push the two CVs we received into the CV stack in order. Because
// the stack merges lazily, this guarantees we aren't merging the
// root.
self.push_cv(left_cv, chunk_counter);
self.push_cv(right_cv, chunk_counter + (chunk_count / 2));
self.chunk_state.chunk_counter += chunk_count;
self
}
// CPU simulation of the BLAKE3 chunk shader.
//
// This can be used to test the real shader.
//
// Note: unlike the real shader, this simulation always uses little-endian
// inputs and outputs.
#[doc(hidden)]
pub fn simulate_chunk_shader<J: Join>(
&self,
count: usize,
input: &[u8],
output: &mut [u8],
control: &GpuControl,
) {
assert_eq!(input.len(), count * CHUNK_LEN, "invalid input size");
assert_eq!(output.len(), count * OUT_LEN, "invalid output size");
if count > self.chunk_state.platform.simd_degree() {
let mid = count / 2;
let (left_in, right_in) = input.split_at(mid * CHUNK_LEN);
let (left_out, right_out) = output.split_at_mut(mid * OUT_LEN);
let control_r = control.plus_chunks(mid as u64);
J::join(
|| self.simulate_chunk_shader::<J>(mid, left_in, left_out, control),
|| self.simulate_chunk_shader::<J>(count - mid, right_in, right_out, &control_r),
left_in.len(),
right_in.len(),
);
} else if count > 0 {
let mut chunks = ArrayVec::<[&[u8; CHUNK_LEN]; MAX_SIMD_DEGREE]>::new();
for chunk in input.chunks_exact(CHUNK_LEN) {
chunks.push(array_ref!(chunk, 0, CHUNK_LEN));
}
self.chunk_state.platform.hash_many(
&chunks,
control.key(),
control.chunk_counter(),
IncrementCounter::Yes,
control.flags(),
CHUNK_START,
CHUNK_END,
output,
);
}
}
// CPU simulation of the BLAKE3 parent shader.
//
// This can be used to test the real shader.
//
// Note: unlike the real shader, this simulation always uses little-endian
// inputs and outputs.
#[doc(hidden)]
pub fn simulate_parent_shader<J: Join>(
&self,
count: usize,
input: &[u8],
output: &mut [u8],
control: &GpuControl,
) {
assert_eq!(input.len(), count * BLOCK_LEN, "invalid input size");
assert_eq!(output.len(), count * OUT_LEN, "invalid output size");
if count > self.chunk_state.platform.simd_degree() {
let mid = count / 2;
let (left_in, right_in) = input.split_at(mid * BLOCK_LEN);
let (left_out, right_out) = output.split_at_mut(mid * OUT_LEN);
let control_r = control.plus_chunks(mid as u64);
J::join(
|| self.simulate_parent_shader::<J>(mid, left_in, left_out, control),
|| self.simulate_parent_shader::<J>(count - mid, right_in, right_out, &control_r),
left_in.len(),
right_in.len(),
);
} else if count > 0 {
let mut parents = ArrayVec::<[&[u8; BLOCK_LEN]; MAX_SIMD_DEGREE]>::new();
for parent in input.chunks_exact(BLOCK_LEN) {
parents.push(array_ref!(parent, 0, BLOCK_LEN));
}
self.chunk_state.platform.hash_many(
&parents,
control.key(),
0,
IncrementCounter::No,
control.flags() | PARENT,
0,
0,
output,
);
}
}
#[doc(hidden)]
#[cfg(target_endian = "big")]
pub fn swap_endian<J: Join>(buffer: &mut [u8]) {
debug_assert!(buffer.len().is_power_of_two(), "invalid buffer size");
debug_assert_eq!(buffer.len() % OUT_LEN, 0, "invalid buffer size");
if buffer.len() > OUT_LEN {
let (left, right) = buffer.split_at_mut(buffer.len() / 2);
let left_len = left.len();
let right_len = right.len();
J::join(
|| Self::swap_endian::<J>(left),
|| Self::swap_endian::<J>(right),
left_len,
right_len,
);
} else {
for buf in buffer.chunks_exact_mut(4) {
buf.swap(0, 3);
buf.swap(1, 2);
}
}
}
#[doc(hidden)]
#[inline(always)]
#[cfg(target_endian = "little")]
pub fn swap_endian<J: Join>(_buffer: &mut [u8]) {}
}
impl Deref for GpuHasher {
type Target = Hasher;
#[inline]
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl DerefMut for GpuHasher {
#[inline]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.inner
}
}
impl From<GpuHasher> for Hasher {
#[inline]
fn from(hasher: GpuHasher) -> Hasher {
hasher.inner
}
}
/// SPIR-V shader modules.
pub mod shaders {
/// Shader module for one level of the BLAKE3 tree.
pub mod blake3 {
/// Returns the SPIR-V code for the chunk shader module.
#[cfg(target_endian = "big")]
pub fn chunk_shader() -> &'static [u8] {
include_bytes!("shaders/blake3-chunk-be.spv")
}
/// Returns the SPIR-V code for the chunk shader module.
#[cfg(target_endian = "little")]
pub fn chunk_shader() -> &'static [u8] {
include_bytes!("shaders/blake3-chunk-le.spv")
}
/// Returns the SPIR-V code for the parent shader module.
pub fn parent_shader() -> &'static [u8] {
include_bytes!("shaders/blake3-parent.spv")
}
/// The local workgroup size.
pub const WORKGROUP_SIZE: usize = 128;
/// The descriptor binding for the input buffer.
pub const INPUT_BUFFER_BINDING: u32 = 0;
/// The descriptor binding for the output buffer.
pub const OUTPUT_BUFFER_BINDING: u32 = 1;
/// The size of the control uniform.
pub const CONTROL_UNIFORM_SIZE: usize = 11 * 4;
}
}
#[cfg(test)]
#[cfg(feature = "std")]
mod tests {
use super::*;
fn selftest_seq(len: usize) -> Vec<u8> {
let seed = len as u32;
let mut out = Vec::with_capacity(len);
let mut a = seed.wrapping_mul(0xDEAD4BAD);
let mut b = 1;
for _ in 0..len {
let t = a.wrapping_add(b);
a = b;
b = t;
out.push((t >> 24) as u8);
}
out
}
#[cfg(not(feature = "rayon"))]
type Join = join::SerialJoin;
#[cfg(feature = "rayon")]
type Join = join::RayonJoin;
#[test]
fn simulate_shader_one_level_once() {
let len = CHUNK_LEN * 128;
let input = selftest_seq(len);
let expected = Hasher::new().update_with_join::<Join>(&input).finalize();
let mut hasher = GpuHasher::new();
let mut buffer = vec![0; OUT_LEN * 128];
hasher.simulate_chunk_shader::<Join>(128, &input, &mut buffer, &hasher.gpu_control(0));
GpuHasher::swap_endian::<Join>(&mut buffer);
hasher.update_from_gpu::<Join>(128, &mut buffer);
assert_eq!(hasher.finalize(), expected);
}
#[test]
fn simulate_shader_one_level_twice() {
let len = CHUNK_LEN * 128;
let input = selftest_seq(2 * len);
let expected = Hasher::new().update_with_join::<Join>(&input).finalize();
let mut hasher = GpuHasher::new();
let mut buffer = vec![0; OUT_LEN * 128];
hasher.simulate_chunk_shader::<Join>(
128,
&input[..len],
&mut buffer,
&hasher.gpu_control(0),
);
GpuHasher::swap_endian::<Join>(&mut buffer);
hasher.update_from_gpu::<Join>(128, &mut buffer);
hasher.simulate_chunk_shader::<Join>(
128,
&input[len..],
&mut buffer,
&hasher.gpu_control(128),
);
GpuHasher::swap_endian::<Join>(&mut buffer);
hasher.update_from_gpu::<Join>(128, &mut buffer);
assert_eq!(hasher.finalize(), expected);
}
#[test]
fn simulate_shader_two_levels_once() {
let len = 2 * CHUNK_LEN * 128;
let input = selftest_seq(len);
let expected = Hasher::new().update_with_join::<Join>(&input).finalize();
let mut hasher = GpuHasher::new();
let mut buffer1 = vec![0; 2 * OUT_LEN * 128];
let mut buffer2 = vec![0; OUT_LEN * 128];
hasher.simulate_chunk_shader::<Join>(2 * 128, &input, &mut buffer1, &hasher.gpu_control(0));
hasher.simulate_parent_shader::<Join>(128, &buffer1, &mut buffer2, &hasher.gpu_control(0));
GpuHasher::swap_endian::<Join>(&mut buffer2);
hasher.update_from_gpu::<Join>(2 * 128, &mut buffer2);
assert_eq!(hasher.finalize(), expected);
}
#[test]
fn simulate_shader_two_levels_twice() {
let len = 2 * CHUNK_LEN * 128;
let input = selftest_seq(2 * len);
let expected = Hasher::new().update_with_join::<Join>(&input).finalize();
let mut hasher = GpuHasher::new();
let mut buffer1 = vec![0; 2 * OUT_LEN * 128];
let mut buffer2 = vec![0; OUT_LEN * 128];
hasher.simulate_chunk_shader::<Join>(
2 * 128,
&input[..len],
&mut buffer1,
&hasher.gpu_control(0),
);
hasher.simulate_parent_shader::<Join>(128, &buffer1, &mut buffer2, &hasher.gpu_control(0));
GpuHasher::swap_endian::<Join>(&mut buffer2);
hasher.update_from_gpu::<Join>(2 * 128, &mut buffer2);
hasher.simulate_chunk_shader::<Join>(
2 * 128,
&input[len..],
&mut buffer1,
&hasher.gpu_control(2 * 128),
);
hasher.simulate_parent_shader::<Join>(
128,
&buffer1,
&mut buffer2,
&hasher.gpu_control(2 * 128),
);
GpuHasher::swap_endian::<Join>(&mut buffer2);
hasher.update_from_gpu::<Join>(2 * 128, &mut buffer2);
assert_eq!(hasher.finalize(), expected);
}
}
| true
|
db5d615c44e1335c2988195fb7f82354cac8968d
|
Rust
|
stijnh/rust-advent-of-code-2018
|
/src/day20.rs
|
UTF-8
| 3,247
| 3.078125
| 3
|
[] |
no_license
|
use crate::common::read_file_lines;
use std::collections::{HashMap as Map, HashSet as Set, VecDeque as Deque};
type Point = [i32; 2];
type Door = (Point, Point);
#[derive(Debug, Clone)]
enum MyRegex {
Leaf(char), // Single character
Seq(Vec<MyRegex>), // Sequence of exprs
Alt(Vec<MyRegex>), // Options for exprs
}
fn parse_myregex(iter: &mut Deque<char>) -> MyRegex {
let mut options = vec![];
let mut curr = vec![];
while let Some(c) = iter.pop_front() {
match c {
'|' => {
options.push(MyRegex::Seq(curr));
curr = vec![];
}
'(' => {
curr.push(parse_myregex(iter));
assert!(iter.pop_front() == Some(')'));
}
'N' | 'S' | 'E' | 'W' => {
curr.push(MyRegex::Leaf(c));
}
_ => {
iter.push_front(c);
break;
}
}
}
options.push(MyRegex::Seq(curr));
MyRegex::Alt(options)
}
fn parse_input() -> MyRegex {
let lines = read_file_lines("inputs/day20");
let mut iter = lines[0].chars().collect::<Deque<_>>();
assert!(iter.pop_front() == Some('^'));
assert!(iter.pop_back() == Some('$'));
parse_myregex(&mut iter)
}
fn walk_paths(node: &MyRegex, active: &Set<Point>, doors: &mut Set<Door>) -> Set<Point> {
match node {
MyRegex::Seq(vec) => vec
.iter()
.fold(active.clone(), |c, node| walk_paths(node, &c, doors)),
MyRegex::Alt(vec) => vec
.iter()
.map(|node| walk_paths(node, active, doors))
.flatten()
.collect(),
MyRegex::Leaf(c) => active
.iter()
.cloned()
.map(|src| {
let [x, y] = src;
let dst = match c {
'N' => [x, y + 1],
'S' => [x, y - 1],
'E' => [x + 1, y],
'W' => [x - 1, y],
_ => panic!("unknown symbol {:?}", c),
};
doors.insert((src, dst));
doors.insert((dst, src));
dst
})
.collect(),
}
}
fn find_room_dists(center: Point, doors: &Set<Door>) -> Map<Point, i32> {
let mut adj = Map::<Point, Vec<Point>>::new();
for (a, b) in doors {
adj.entry(*a).or_insert(vec![]).push(*b);
}
let mut dists = Map::new();
let mut queue = Deque::new();
queue.push_back((center, 0));
while let Some((v, d)) = queue.pop_front() {
if !dists.contains_key(&v) {
dists.insert(v, d);
for u in &adj[&v] {
queue.push_back((*u, d + 1));
}
}
}
dists
}
pub fn run(_: &[&str]) {
let root = parse_input();
let mut doors = Set::new();
let mut active = Set::new();
active.insert([0, 0]);
let _ = walk_paths(&root, &active, &mut doors);
let dists = find_room_dists([0, 0], &doors);
let max_dist = dists.values().max();
println!("answer A: {:?}", max_dist);
let num_paths = dists.values().filter(|v| **v >= 1000).count();
println!("answer B: {:?}", num_paths);
}
| true
|
3c45bee754354f8b1a5ad3ba2fe8b97013c1d8d3
|
Rust
|
burzek/katas
|
/AdventOfCode2021/src/day1.rs
|
UTF-8
| 759
| 3.40625
| 3
|
[] |
no_license
|
pub fn day1_task1(input: String) {
let lines = input.lines();
let mut increased = 0;
lines
.map(|s| { s.parse::<i32>().unwrap() })
.reduce(|prev, current| {
if prev < current { increased = increased + 1 };
current
});
println!("day1, task1 : {}", increased);
}
pub fn day1_task2(input: String) {
let lines = input.lines();
let mut increased = 0;
let values: Vec<i32> = lines
.map(|s| { s.parse::<i32>().unwrap() })
.collect();
for i in 3..values.len() {
if values[i - 1] + values[i - 2] + values[i - 3] < values[i] + values[i - 1] + values[i - 2] {
increased = increased + 1;
};
}
println!("day1, task2 : {}", increased);
}
| true
|
aee3d4b6c2054c6669e32d0d6ab5e7f54bf3c0d0
|
Rust
|
dainslef/RustPractice
|
/src/leetcode/q96_unique_binary_search_trees.rs
|
UTF-8
| 1,968
| 3.8125
| 4
|
[
"BSD-3-Clause"
] |
permissive
|
/*!
[96. Unique Binary Search Trees](https://leetcode.com/problems/unique-binary-search-trees/)
Given an integer n, return the number of structurally unique BST's (binary search trees)
which has exactly n nodes of unique values from 1 to n.
Example 1:
```html
Input: n = 3
Output: 5
```
Example 2:
```html
Input: n = 1
Output: 1
```
Constraints:
```html
1 <= n <= 19
```
*/
/**
Runtime: 0 ms, faster than 100.00% of Rust online submissions for Unique Binary Search Trees.<br>
Memory Usage: 2 MB, less than 62.50% of Rust online submissions for Unique Binary Search Trees.
Use dynamic programming, split the big BST tree into small tree,
count the small tree and save data for reuse.
*/
fn num_trees(n: i32) -> i32 {
use std::collections::HashMap;
/*
Same range size with different rang size have same count,
so we don't need save the start/end index for each range,
just save range size for reuse.
*/
let mut bst_count: HashMap<i32, i32> = vec![(1, 1)].into_iter().collect();
/*
"range size" means how many elements the sub tree can hold,
compute and save the count of each range size, then reuse it.
The count of last range size(n) will be the answer.
*/
for range_size in 2..=n {
let mut count = 0;
for i in 1..=range_size {
// get count of the left sub tree (start: 1, end: i - 1)
let left = bst_count.get(&(i - 1)).unwrap_or(&1);
// get count of the left sub tree (start: i + 1, end: rang size)
let right = bst_count.get(&(range_size - i)).unwrap_or(&1);
count += left * right;
}
// save the range size into hash map
bst_count.entry(range_size).or_insert(count);
}
bst_count[&n]
}
#[test]
fn q96_test() {
assert_eq!(num_trees(1), 1);
assert_eq!(num_trees(2), 2);
assert_eq!(num_trees(3), 5);
assert_eq!(num_trees(4), 14);
assert_eq!(num_trees(5), 42);
assert_eq!(num_trees(6), 132);
assert_eq!(num_trees(7), 429);
assert_eq!(num_trees(19), 1767263190);
}
| true
|
905b6243f2fb56c2c65edf0a885aca0565283bf2
|
Rust
|
Cytosine2020/authernet
|
/src/athernet/physical.rs
|
UTF-8
| 6,832
| 2.609375
| 3
|
[] |
no_license
|
use std::collections::VecDeque;
use crate::athernet::mac::MacFrame;
const SYMBOL_LEN: usize = 5;
const BARKER: [bool; 7] = [true, true, true, false, false, true, false];
pub const PHY_PAYLOAD_MAX: usize = 256;
pub type PhyPayload = [u8; PHY_PAYLOAD_MAX];
lazy_static!(
static ref CARRIER: [i16; SYMBOL_LEN] = {
let mut carrier = [0i16; SYMBOL_LEN];
const ZERO: f32 = SYMBOL_LEN as f32 / 2. - 0.5;
for i in 0..SYMBOL_LEN {
let t = (i as f32 - ZERO) * std::f32::consts::PI * 2. / SYMBOL_LEN as f32;
let sinc = if t.abs() < 1e-6 { 1. } else { t.sin() / t };
carrier[i] = (sinc * std::i16::MAX as f32) as i16;
}
carrier
};
);
fn carrier() -> impl Iterator<Item=i16> + 'static { CARRIER.iter().cloned() }
pub struct ByteToBitIter<T> {
iter: T,
buffer: u8,
index: u8,
}
impl<T> From<T> for ByteToBitIter<T> {
fn from(iter: T) -> Self { Self { iter, buffer: 0, index: 8 } }
}
impl<T: Iterator<Item=u8>> Iterator for ByteToBitIter<T> {
type Item = bool;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
if self.index == 8 {
if let Some(byte) = self.iter.next() {
self.index = 0;
self.buffer = byte;
} else {
return None;
}
};
let index = self.index;
self.index += 1;
Some(((self.buffer >> index) & 1) == 1)
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
let (min, max) = self.iter.size_hint();
let extra = 8 - self.index as usize;
(min * 8 + extra, max.map(|value| value * 8 + extra))
}
}
fn pulse_shaping<I: Iterator<Item=bool>>(iter: I) -> impl Iterator<Item=i16> {
iter.map(move |bit| {
carrier().map(move |item| if bit { item } else { -item })
}).flatten()
}
pub fn modulate(buffer: MacFrame) -> impl Iterator<Item=i16> {
let size = buffer.get_total_size();
let raw = buffer.into_raw();
pulse_shaping(BARKER.iter().cloned().chain(ByteToBitIter::from(
(0..size).map(move |index| raw[index])
)))
}
#[derive(Copy, Clone)]
struct BitReceive {
inner: PhyPayload,
count: usize,
mac_addr: u8,
}
impl BitReceive {
#[inline]
pub fn new(mac_addr: u8) -> Self { Self { inner: [0; PHY_PAYLOAD_MAX], count: 0, mac_addr } }
#[inline]
pub fn push(&mut self, bit: bool) -> Option<Option<MacFrame>> {
self.inner[self.count / 8] |= (bit as u8) << (self.count % 8);
self.count += 1;
if self.count <= (MacFrame::MAC_DATA_SIZE + 1) * 8 {
None
} else {
let size = if (self.inner[MacFrame::OP_INDEX] & 0b1111) == MacFrame::OP_DATA {
self.inner[MacFrame::MAC_DATA_SIZE] as usize + 1 + 2
} else {
1
} + MacFrame::MAC_DATA_SIZE;
if size > PHY_PAYLOAD_MAX { return Some(None); }
if self.count < size * 8 {
None
} else {
Some(Some(MacFrame::from_raw(self.inner)))
}
}
}
#[inline]
pub fn is_self(&self) -> bool {
self.count < 4 || (self.inner[MacFrame::MAC_INDEX] & 0b1111) == self.mac_addr
}
}
enum DemodulateState {
WAITE,
RECEIVE(usize, BitReceive),
}
pub struct Demodulator {
window: VecDeque<i16>,
state: DemodulateState,
last_prod: i64,
moving_average: i64,
mac_addr: u8,
}
impl Demodulator {
const PREAMBLE_LEN: usize = SYMBOL_LEN * BARKER.len();
const HEADER_THRESHOLD_SCALE: i64 = 1 << 19;
const MOVING_AVERAGE: i64 = 16;
const ACTIVE_THRESHOLD: i64 = 512;
const JAMMING_THRESHOLD: i64 = 4096;
fn dot_product<I: Iterator<Item=i16>, U: Iterator<Item=i16>>(iter_a: I, iter_b: U) -> i64 {
iter_a.zip(iter_b).map(|(a, b)| a as i64 * b as i64).sum::<i64>()
}
fn preamble_product(&self) -> i64 {
Self::dot_product(self.window.iter().cloned(), pulse_shaping(BARKER.iter().cloned()))
}
fn section_product(&self, offset: usize) -> i64 {
Self::dot_product(self.window.iter().skip(offset).cloned(), carrier())
}
fn moving_average(last: i64, new: i64) -> i64 {
(last * (Self::MOVING_AVERAGE - 1) + new) / Self::MOVING_AVERAGE
}
pub fn new(mac_addr: u8) -> Self {
Self {
window: VecDeque::with_capacity(Self::PREAMBLE_LEN),
state: DemodulateState::WAITE,
last_prod: 0,
moving_average: 0,
mac_addr,
}
}
pub fn is_active(&self) -> bool {
if self.moving_average > Self::JAMMING_THRESHOLD { return true; }
if let DemodulateState::RECEIVE(_, receiver) = self.state {
!receiver.is_self()
} else {
false
}
}
pub fn push_back(&mut self, item: i16) -> Option<MacFrame> {
if self.window.len() == Self::PREAMBLE_LEN { self.window.pop_front(); }
self.window.push_back(item);
self.moving_average = Self::moving_average(self.moving_average, (item as i64).abs());
let threshold = self.moving_average * Self::HEADER_THRESHOLD_SCALE;
let mut prod = 0;
match self.state {
DemodulateState::WAITE => {
if self.window.len() == Self::PREAMBLE_LEN &&
self.moving_average > Self::ACTIVE_THRESHOLD {
prod = self.preamble_product();
if prod > threshold && self.last_prod > prod && BARKER.iter()
.enumerate().all(|(index, bit)| {
*bit == (self.section_product(index * SYMBOL_LEN) > 0)
}) {
self.state = DemodulateState::RECEIVE(0, BitReceive::new(self.mac_addr));
prod = 0;
}
}
}
DemodulateState::RECEIVE(mut count, mut buffer) => {
if self.moving_average > Self::JAMMING_THRESHOLD {
self.state = DemodulateState::WAITE;
self.window.clear();
return None;
}
count += 1;
self.state = if count == SYMBOL_LEN {
let prod = self.section_product(Self::PREAMBLE_LEN - SYMBOL_LEN);
if let Some(result) = buffer.push(prod > 0) {
self.state = DemodulateState::WAITE;
self.window.clear();
return result;
}
DemodulateState::RECEIVE(0, buffer)
} else {
DemodulateState::RECEIVE(count, buffer)
}
}
}
self.last_prod = prod;
None
}
}
| true
|
20dad656b0d5a538d3851aff4bbde4c70c8cc87f
|
Rust
|
rramsden/uoinspect
|
/src/utils.rs
|
UTF-8
| 558
| 3.0625
| 3
|
[] |
no_license
|
use std::{
path::{Path}
};
pub fn print_json<T>(entries: Vec<T>, s: &Fn(&T) -> std::result::Result<std::string::String, serde_json::error::Error>) {
print!("[");
for i in 0..entries.len() {
let entry = &entries[i];
let json = s(&entry).unwrap();
print!("{}", json);
if i != entries.len() - 1 {
print!(",")
}
}
print!("]\n")
}
pub fn base_path(path: &str) -> String {
let file_name = Path::new(path).file_name().unwrap().to_str().unwrap();
str::replace(path, file_name, "")
}
| true
|
0b04b57e50ded57fd3ca0a51db20378c3fe611cc
|
Rust
|
slpcat/actix
|
/src/mailbox.rs
|
UTF-8
| 2,553
| 2.5625
| 3
|
[
"MIT",
"Apache-2.0"
] |
permissive
|
use futures::{Async, Stream};
use std::fmt;
use actor::{Actor, AsyncContext};
use address::EnvelopeProxy;
use address::{channel, Addr, AddressReceiver, AddressSenderProducer};
/// Maximum number of consecutive polls in a loop
const MAX_SYNC_POLLS: u32 = 256;
/// Default address channel capacity
pub const DEFAULT_CAPACITY: usize = 16;
pub struct Mailbox<A>
where
A: Actor,
A::Context: AsyncContext<A>,
{
msgs: AddressReceiver<A>,
}
impl<A> fmt::Debug for Mailbox<A> where
A: Actor,
A::Context: AsyncContext<A>,
{
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.debug_struct("Mailbox")
.field("capacity", &self.capacity())
.finish()
}
}
impl<A> Default for Mailbox<A>
where
A: Actor,
A::Context: AsyncContext<A>,
{
#[inline]
fn default() -> Self {
let (_, rx) = channel::channel(DEFAULT_CAPACITY);
Mailbox { msgs: rx }
}
}
struct NumPolls(u32);
impl NumPolls {
fn inc(&mut self) -> u32 {
self.0 += 1;
self.0
}
}
impl<A> Mailbox<A>
where
A: Actor,
A::Context: AsyncContext<A>,
{
#[inline]
pub fn new(msgs: AddressReceiver<A>) -> Self {
Mailbox { msgs }
}
pub fn capacity(&self) -> usize {
self.msgs.capacity()
}
pub fn set_capacity(&mut self, cap: usize) {
self.msgs.set_capacity(cap);
}
#[inline]
pub fn connected(&self) -> bool {
self.msgs.connected()
}
pub fn address(&self) -> Addr<A> {
Addr::new(self.msgs.sender())
}
pub fn sender_producer(&self) -> AddressSenderProducer<A> {
self.msgs.sender_producer()
}
pub fn poll(&mut self, act: &mut A, ctx: &mut A::Context) {
let mut n_polls = NumPolls(0);
loop {
let mut not_ready = true;
// sync messages
loop {
if ctx.waiting() {
return;
}
match self.msgs.poll() {
Ok(Async::Ready(Some(mut msg))) => {
not_ready = false;
msg.handle(act, ctx);
}
Ok(Async::Ready(None)) | Ok(Async::NotReady) | Err(_) => break,
}
debug_assert!(
n_polls.inc() < MAX_SYNC_POLLS,
"Use Self::Context::notify() instead of direct use of address"
);
}
if not_ready {
return;
}
}
}
}
| true
|
a67e05a4ff7d3fcdc974aff22c22798b0beab9a1
|
Rust
|
evopen/maligog
|
/src/sampler.rs
|
UTF-8
| 1,881
| 2.6875
| 3
|
[] |
no_license
|
use std::ffi::CString;
use std::sync::Arc;
use crate::device::Device;
use ash::vk;
use ash::vk::Handle;
pub(crate) struct SamplerRef {
pub(crate) handle: vk::Sampler,
device: Device,
name: Option<String>,
}
#[derive(Clone)]
pub struct Sampler {
pub(crate) inner: Arc<SamplerRef>,
}
impl Sampler {
pub fn new(
device: Device,
name: Option<&str>,
mag_filter: vk::Filter,
min_filter: vk::Filter,
address_mode_u: vk::SamplerAddressMode,
address_mode_v: vk::SamplerAddressMode,
) -> Self {
let info = vk::SamplerCreateInfo::builder()
.mag_filter(mag_filter)
.min_filter(min_filter)
.address_mode_u(address_mode_u)
.address_mode_v(address_mode_v)
.build();
unsafe {
let handle = device.inner.handle.create_sampler(&info, None).unwrap();
if let Some(name) = name {
device.debug_set_object_name(name, handle.as_raw(), vk::ObjectType::SAMPLER);
}
Self {
inner: Arc::new(SamplerRef {
handle,
device,
name: name.map(|s| s.to_owned()),
}),
}
}
}
}
impl Device {
pub fn create_sampler(
&self,
name: Option<&str>,
mag_filter: vk::Filter,
min_filter: vk::Filter,
address_mode_u: vk::SamplerAddressMode,
address_mode_v: vk::SamplerAddressMode,
) -> Sampler {
Sampler::new(
self.clone(),
name,
mag_filter,
min_filter,
address_mode_u,
address_mode_v,
)
}
}
impl Drop for SamplerRef {
fn drop(&mut self) {
unsafe {
self.device.inner.handle.destroy_sampler(self.handle, None);
}
}
}
| true
|
8bba01b4ef351208c3041c2e6988140ca1a52429
|
Rust
|
CoffeJunkStudio/daab
|
/src/diagnostics/mod.rs
|
UTF-8
| 7,813
| 3.109375
| 3
|
[
"Apache-2.0"
] |
permissive
|
//!
//! # Extensive debugging and analysis module.
//!
//! **Notice: This module is only available if the `diagnostics` feature has been activated**.
//!
//! This module contains the types used in debugging the [`ArtifactCache`].
//! The most important one is [`Doctor`] which conducts a diagnosis on a
//! `ArtifactCache` if constructed via [`ArtifactCache::new_with_doctor()`].
//!
//! `Doctor` has methods for various events happening in the `ArtifactCache`
//! receiving the relevant builder or artifact as argument
//! (as [`ArtifactHandle`] or [`BuilderHandle`] respectivly).
//! See the respective method of the `Doctor` for details.
//!
//! Additionally, to the generic `Doctor` trait, there are several pre-implemented
//! Doctors such as: [`VisgraphDoc`] or [`TextualDoc`].
//!
//![`ArtifactCache`]: ../struct.ArtifactCache.html
//![`Doctor`]: trait.Doctor.html
//![`ArtifactCache::new_with_doctor()`]: ../struct.ArtifactCache.html#method.new_with_doctor
//![`ArtifactHandle`]: struct.ArtifactHandle.html
//![`BuilderHandle`]: struct.BuilderHandle.html
//![`VisgraphDoc`]: struct.VisgraphDoc.html
//![`TextualDoc`]: struct.TextualDoc.html
//!
use std::any::Any;
use std::hash::Hash;
use std::hash::Hasher;
use std::fmt::Debug;
use crate::canning::Can;
use crate::canning::CanBase;
use crate::canning::CanSized;
use crate::Promise;
use crate::BuilderId;
mod visgraph;
pub use visgraph::VisgraphDocOptions;
pub use visgraph::VisgraphDoc;
mod textual;
pub use textual::TextualDocOptions;
pub use textual::TextualDoc;
/// Debugger for the [`ArtifactCache`].
///
/// **Notice: This trait is only available if the `diagnostics` feature has been activated**.
///
/// The Doctor conducts diagnoses on the `ArtifactCache`, if it is passed
/// with [`ArtifactCache::new_with_doctor()`]. The `ArtifactCache` will
/// call the methods of this trait whenever the respective event happens.
/// It will be supplied with relevant object(s), such as `Builder`s and artifacts.
/// For details on each event see the respective method.
///
/// Each method as a default implementation to ease implementing specialized `Doctor`s which don't need all the events. The default implementations do nothing, i.e. are no-ops.
///
///[`ArtifactCache`]: ../struct.ArtifactCache.html
///[`ArtifactCache::new_with_doctor()`]: ../struct.ArtifactCache.html#method.new_with_doctor
///
pub trait Doctor<ArtCan, BCan> {
/// One `Builder` resolves another `Builder`.
///
/// This methods means that `builder` appearently depends on `used`.
///
fn resolve(&mut self, _builder: &BuilderHandle<BCan>, _used: &BuilderHandle<BCan>) {
// NOOP
}
/// One `Builder` builds its artifact.
///
/// This method is called each time `builder` is invoked to build
/// its `artifact`. Notice, this function is only called when a fresh
/// artifact is actually constructed, i.e. first time it is resolved
/// or when it is resolved after a reset or invalidation.
///
fn build(&mut self, _builder: &BuilderHandle<BCan>, _artifact: &ArtifactHandle<ArtCan>) {
// NOOP
}
/// The entire cache is cleared via `ArtifactCache::clear()`.
///
fn clear(&mut self) {
// NOOP
}
/// The given `Builder` is invalidate.
///
/// This method is only called if invalidation is call directly with
/// `builder` as its argument.
///
/// **Notice:** All dependants of `builder` are invalidated as well, but
/// this function will not be called for the dependant invalidations. If
/// deep invalidation tracking is desirable, the dependencies have to be
/// tracked via the `resolve` call back.
///
/// **Notice:** This invalidation might result in clearing the entire cache,
/// but `clear` will not be called in such a case.
///
fn invalidate(&mut self, _builder: &BuilderHandle<BCan>) {
// NOOP
}
}
/// Encapsulates a generic artifact with some debugging information.
///
/// This struct encapsulates a artifact as `Rc<dyn Any>` which might be fairly useless,
/// unless one wants to cast or test it against a concrete type.
/// Thus this struct also contains the stringified type name of that value
/// as well as the `Debug` string of the value.
/// Also notice, that different values can be differentiated by the allocation
/// pointer thus the implementation of `Hash` and `Eq`.
///
#[derive(Clone, Debug)]
pub struct ArtifactHandle<ArtCan> {
/// The actual artifact value.
pub value: ArtCan,
/// The type name of the artifact as of `std::any::type_name`.
pub type_name: &'static str,
/// The value of the artifact as of `std::fmt::Debug`.
pub dbg_text: String,
}
impl<ArtCan> ArtifactHandle<ArtCan> {
/// Constructs a new artifact handle with the given value.
///
pub fn new<T: Any + Debug>(value: ArtCan::Bin) -> Self
where ArtCan: CanSized<T> {
let dbg_text = format!("{:#?}", value);
ArtifactHandle {
value: ArtCan::from_bin(value),
type_name: std::any::type_name::<T>(),
dbg_text,
}
}
/// Extract artifact from handle.
///
/// Since the artifact is canned it is only useful it the exact type of the
/// artifact is known or at least assumed and a downcast is going to be
/// attempt.
///
pub fn into_inner(self) -> ArtCan {
self.value
}
}
impl<ArtCan> Hash for ArtifactHandle<ArtCan> where ArtCan: CanBase {
fn hash<H: Hasher>(&self, state: &mut H) {
(self.value.can_as_ptr()).hash(state);
}
}
impl<ArtCan> PartialEq for ArtifactHandle<ArtCan> where ArtCan: CanBase {
fn eq(&self, other: &Self) -> bool {
(self.value.can_as_ptr())
.eq(&other.value.can_as_ptr())
}
}
impl<ArtCan: CanBase> Eq for ArtifactHandle<ArtCan> {
}
/// Encapsulates a generic builder with some debugging information.
///
/// This struct encapsulates a builder as `Blueprint<dyn Any>` which might
/// be fairly useless.
/// Thus this struct also contains the stringified type name of that value
/// as well as the `Debug` string of the value.
/// Also notice, that different builders can be differentiated by the allocation
/// pointer thus the implementation of `Hash` and `Eq`.
///
#[derive(Clone, Debug)]
pub struct BuilderHandle<BCan> {
/// The actual builder as promise.
value: BCan,
/// The unique id of that builder.
pub id: BuilderId,
/// The type name of the builder as of `std::any::type_name`.
pub type_name: &'static str,
/// The value of the builder as of `std::fmt::Debug`.
pub dbg_text: String,
}
impl<BCan> BuilderHandle<BCan> {
/// Constructs a new builder handle with the given value.
///
pub fn new<AP>(value: &AP) -> Self
where
BCan: Can<AP::Builder>,
AP: Promise<BCan = BCan> {
let dbg_text = format!("{:#?}", &value.builder().builder);
let id = value.id();
BuilderHandle {
value: value.canned().can,
id,
type_name: std::any::type_name::<AP::Builder>(),
dbg_text,
}
}
/// The unique id of that builder.
///
pub fn id(&self) -> BuilderId {
self.id
}
}
impl<BCan> Hash for BuilderHandle<BCan> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.id.hash(state);
}
}
impl<BCan> PartialEq for BuilderHandle<BCan> {
fn eq(&self, other: &Self) -> bool {
self.id.eq(&other.id)
}
}
impl<BCan> Eq for BuilderHandle<BCan> {
}
/// Default no-op `Doctor`.
///
/// **Notice: This struct is only available if the `diagnostics` feature has been activated**.
///
/// A no-op implementation of the `Doctor` i.e. a `Doctor` that does nothing. It is used as default `Doctor`,
/// i.e. if no actual `Doctor` is specified.
///
pub struct NoopDoctor;
impl NoopDoctor {
/// Create a new dummy doctor
///
/// **Notice: This function is only available if the `diagnostics` feature has been activated**.
///
pub fn new() -> Self {
Self::default()
}
}
impl<ArtCan, BCan> Doctor<ArtCan, BCan> for NoopDoctor {
// Use default impl
}
impl Default for NoopDoctor {
fn default() -> Self {
NoopDoctor
}
}
| true
|
1d37091959e72aedd4bcccbada801a27f3e8902a
|
Rust
|
haptics-nri/nri
|
/crates/utils/src/iter.rs
|
UTF-8
| 599
| 3.125
| 3
|
[] |
no_license
|
use std::{mem, ops};
use std::ops::Add;
/// StepBy iterator
pub struct StepBy<T> {
range: ops::Range<T>,
step: T
}
impl<T> Iterator for StepBy<T> where T: PartialOrd, for<'a> &'a T: Add<Output=T> {
type Item = T;
fn next(&mut self) -> Option<T> {
if self.range.start < self.range.end {
let new = &self.range.start + &self.step;
Some(mem::replace(&mut self.range.start, new))
} else {
None
}
}
}
/// create a StepBy iterator
pub fn step<T>(range: ops::Range<T>, step: T) -> StepBy<T> {
StepBy { range, step }
}
| true
|
53a8e9b5dd7f279d4531975e2574c56ce1f7eb61
|
Rust
|
MattRoelle/rustgame
|
/src/game/player.rs
|
UTF-8
| 579
| 2.8125
| 3
|
[
"MIT"
] |
permissive
|
use crate::engine::{sprite::Sprite, game_context::GameObject};
use super::assets::Assets;
#[derive(Debug, Copy, Clone)]
pub struct PlayerProps {
}
pub struct Player<'a> {
sprite: Sprite<'a>
}
impl<'a> Player<'a> {
pub fn new(props: PlayerProps, assets: &'a Assets<'a>) -> Self {
Self {
sprite: Sprite::new(&assets.green_rect, 0.0 ,0.0, 32.0, 32.0)
}
}
}
impl<'a> GameObject for Player<'a> {
fn tags(&self) -> Vec<String> {
vec![]
}
fn update(&mut self) {
}
fn set_pos(&mut self, x: f32, y: f32) {
}
}
| true
|
36fb461d0833d8c91148d8518427d1a101c3141a
|
Rust
|
pstetz/misc
|
/leetcode/1266.rs
|
UTF-8
| 360
| 2.96875
| 3
|
[] |
no_license
|
use std::cmp;
impl Solution {
pub fn min_time_to_visit_all_points(points: Vec<Vec<i32>>) -> i32 {
let mut time: i32 = 0;
for i in 1..points.len() {
let x = (points[i-1][0] - points[i][0]).abs();
let y = (points[i-1][1] - points[i][1]).abs();
time = time + cmp::max(x, y);
}
time
}
}
| true
|
e2174d9d5d8dba3a25e5d412f46e0e5b3be3de6e
|
Rust
|
Swatinem/druid
|
/druid/src/widget/value_textbox.rs
|
UTF-8
| 16,380
| 2.84375
| 3
|
[
"Apache-2.0"
] |
permissive
|
// Copyright 2021 The Druid Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! A textbox that that parses and validates data.
use tracing::instrument;
use super::TextBox;
use crate::text::{Formatter, Selection, TextComponent, ValidationError};
use crate::widget::prelude::*;
use crate::{Data, Selector};
const BEGIN_EDITING: Selector = Selector::new("druid.builtin.textbox-begin-editing");
const COMPLETE_EDITING: Selector = Selector::new("druid.builtin.textbox-complete-editing");
/// A `TextBox` that uses a [`Formatter`] to handle formatting and validation
/// of its data.
///
/// There are a number of ways to customize the behaviour of the text box
/// in relation to the provided [`Formatter`]:
///
/// - [`ValueTextBox::validate_while_editing`] takes a flag that determines whether
/// or not the textbox can display text that is not valid, while editing is
/// in progress. (Text will still be validated when the user attempts to complete
/// editing.)
///
/// - [`ValueTextBox::update_data_while_editing`] takes a flag that determines
/// whether the output value is updated during editing, when possible.
///
/// - [`ValueTextBox::delegate`] allows you to provide some implementation of
/// the [`ValidationDelegate`] trait, which receives a callback during editing;
/// this can be used to report errors further back up the tree.
pub struct ValueTextBox<T> {
child: TextBox<String>,
formatter: Box<dyn Formatter<T>>,
callback: Option<Box<dyn ValidationDelegate>>,
is_editing: bool,
validate_while_editing: bool,
update_data_while_editing: bool,
/// the last data that this textbox saw or created.
/// This is used to determine when a change to the data is originating
/// elsewhere in the application, which we need to special-case
last_known_data: Option<T>,
force_selection: Option<Selection>,
old_buffer: String,
buffer: String,
}
/// A type that can be registered to receive callbacks as the state of a
/// [`ValueTextBox`] changes.
pub trait ValidationDelegate {
/// Called with a [`TextBoxEvent`] whenever the validation state of a
/// [`ValueTextBox`] changes.
fn event(&mut self, ctx: &mut EventCtx, event: TextBoxEvent, current_text: &str);
}
/// Events sent to a [`ValidationDelegate`].
pub enum TextBoxEvent {
/// The textbox began editing.
Began,
/// An edit occured which was considered valid by the [`Formatter`].
Changed,
/// An edit occured which was rejected by the [`Formatter`].
PartiallyInvalid(ValidationError),
/// The user attempted to finish editing, but the input was not valid.
Invalid(ValidationError),
/// The user finished editing, with valid input.
Complete,
/// Editing was cancelled.
Cancel,
}
impl TextBox<String> {
/// Turn this `TextBox` into a [`ValueTextBox`], using the [`Formatter`] to
/// manage the value.
///
/// For simple value formatting, you can use the [`ParseFormatter`].
///
/// [`ValueTextBox`]: ValueTextBox
/// [`Formatter`]: crate::text::format::Formatter
/// [`ParseFormatter`]: crate::text::format::ParseFormatter
pub fn with_formatter<T: Data>(
self,
formatter: impl Formatter<T> + 'static,
) -> ValueTextBox<T> {
ValueTextBox::new(self, formatter)
}
}
impl<T: Data> ValueTextBox<T> {
/// Create a new `ValueTextBox` from a normal [`TextBox`] and a [`Formatter`].
///
/// [`TextBox`]: crate::widget::TextBox
/// [`Formatter`]: crate::text::format::Formatter
pub fn new(mut child: TextBox<String>, formatter: impl Formatter<T> + 'static) -> Self {
child.text_mut().borrow_mut().send_notification_on_return = true;
child.text_mut().borrow_mut().send_notification_on_cancel = true;
child.handles_tab_notifications = false;
ValueTextBox {
child,
formatter: Box::new(formatter),
callback: None,
is_editing: false,
last_known_data: None,
validate_while_editing: true,
update_data_while_editing: false,
old_buffer: String::new(),
buffer: String::new(),
force_selection: None,
}
}
/// Builder-style method to set an optional [`ValidationDelegate`] on this
/// textbox.
pub fn delegate(mut self, delegate: impl ValidationDelegate + 'static) -> Self {
self.callback = Some(Box::new(delegate));
self
}
/// Builder-style method to set whether or not this text box validates
/// its contents during editing.
///
/// If `true` (the default) edits that fail validation
/// ([`Formatter::validate_partial_input`]) will be rejected. If `false`,
/// those edits will be accepted, and the text box will be updated.
pub fn validate_while_editing(mut self, validate: bool) -> Self {
self.validate_while_editing = validate;
self
}
/// Builder-style method to set whether or not this text box updates the
/// incoming data during editing.
///
/// If `false` (the default) the data is only updated when editing completes.
pub fn update_data_while_editing(mut self, flag: bool) -> Self {
self.update_data_while_editing = flag;
self
}
fn complete(&mut self, ctx: &mut EventCtx, data: &mut T) -> bool {
match self.formatter.value(&self.buffer) {
Ok(new_data) => {
*data = new_data;
self.buffer = self.formatter.format(data);
self.is_editing = false;
ctx.request_update();
self.send_event(ctx, TextBoxEvent::Complete);
true
}
Err(err) => {
if self.child.text().can_write() {
if let Some(inval) = self
.child
.text_mut()
.borrow_mut()
.set_selection(Selection::new(0, self.buffer.len()))
{
ctx.invalidate_text_input(inval);
}
}
self.send_event(ctx, TextBoxEvent::Invalid(err));
// our content isn't valid
// ideally we would flash the background or something
false
}
}
}
fn cancel(&mut self, ctx: &mut EventCtx, data: &T) {
self.is_editing = false;
self.buffer = self.formatter.format(data);
ctx.request_update();
ctx.resign_focus();
self.send_event(ctx, TextBoxEvent::Cancel);
}
fn begin(&mut self, ctx: &mut EventCtx, data: &T) {
self.is_editing = true;
self.buffer = self.formatter.format_for_editing(data);
self.last_known_data = Some(data.clone());
ctx.request_update();
self.send_event(ctx, TextBoxEvent::Began);
}
fn send_event(&mut self, ctx: &mut EventCtx, event: TextBoxEvent) {
if let Some(delegate) = self.callback.as_mut() {
delegate.event(ctx, event, &self.buffer)
}
}
}
impl<T: Data + std::fmt::Debug> Widget<T> for ValueTextBox<T> {
#[instrument(
name = "ValueTextBox",
level = "trace",
skip(self, ctx, event, data, env)
)]
fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut T, env: &Env) {
if matches!(event, Event::Command(cmd) if cmd.is(BEGIN_EDITING)) {
return self.begin(ctx, data);
}
if self.is_editing {
// if we reject an edit we want to reset the selection
let pre_sel = if self.child.text().can_read() {
Some(self.child.text().borrow().selection())
} else {
None
};
match event {
// this is caused by an external focus change, like the mouse being clicked
// elsewhere.
Event::Command(cmd) if cmd.is(COMPLETE_EDITING) => {
if !self.complete(ctx, data) {
self.cancel(ctx, data);
}
return;
}
Event::Notification(cmd) if cmd.is(TextComponent::TAB) => {
ctx.set_handled();
ctx.request_paint();
if self.complete(ctx, data) {
ctx.focus_next();
}
return;
}
Event::Notification(cmd) if cmd.is(TextComponent::BACKTAB) => {
ctx.request_paint();
ctx.set_handled();
if self.complete(ctx, data) {
ctx.focus_prev();
}
return;
}
Event::Notification(cmd) if cmd.is(TextComponent::RETURN) => {
ctx.set_handled();
if self.complete(ctx, data) {
ctx.resign_focus();
}
return;
}
Event::Notification(cmd) if cmd.is(TextComponent::CANCEL) => {
ctx.set_handled();
self.cancel(ctx, data);
return;
}
event => {
self.child.event(ctx, event, &mut self.buffer, env);
}
}
// if an edit occured, validate it with the formatter
// notifications can arrive before update, so we always ignore them
if !matches!(event, Event::Notification(_)) && self.buffer != self.old_buffer {
let mut validation = self
.formatter
.validate_partial_input(&self.buffer, &self.child.text().borrow().selection());
if self.validate_while_editing {
let new_buf = match (validation.text_change.take(), validation.is_err()) {
(Some(new_text), _) => {
// be helpful: if the formatter is misbehaved, log it.
if self
.formatter
.validate_partial_input(&new_text, &Selection::caret(0))
.is_err()
{
tracing::warn!(
"formatter replacement text does not validate: '{}'",
&new_text
);
None
} else {
Some(new_text)
}
}
(None, true) => Some(self.old_buffer.clone()),
_ => None,
};
let new_sel = match (validation.selection_change.take(), validation.is_err()) {
(Some(new_sel), _) => Some(new_sel),
(None, true) if pre_sel.is_some() => pre_sel,
_ => None,
};
if let Some(new_buf) = new_buf {
self.buffer = new_buf;
}
self.force_selection = new_sel;
if self.update_data_while_editing && !validation.is_err() {
if let Ok(new_data) = self.formatter.value(&self.buffer) {
*data = new_data;
self.last_known_data = Some(data.clone());
}
}
}
match validation.error() {
Some(err) => {
self.send_event(ctx, TextBoxEvent::PartiallyInvalid(err.to_owned()))
}
None => self.send_event(ctx, TextBoxEvent::Changed),
};
ctx.request_update();
}
// if we *aren't* editing:
} else {
if let Event::MouseDown(_) = event {
self.begin(ctx, data);
}
self.child.event(ctx, event, &mut self.buffer, env);
}
}
#[instrument(
name = "ValueTextBox",
level = "trace",
skip(self, ctx, event, data, env)
)]
fn lifecycle(&mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &T, env: &Env) {
match event {
LifeCycle::WidgetAdded => {
self.buffer = self.formatter.format(data);
self.old_buffer = self.buffer.clone();
}
LifeCycle::FocusChanged(true) if !self.is_editing => {
ctx.submit_command(BEGIN_EDITING.to(ctx.widget_id()));
}
LifeCycle::FocusChanged(false) => {
ctx.submit_command(COMPLETE_EDITING.to(ctx.widget_id()));
}
_ => (),
}
self.child.lifecycle(ctx, event, &self.buffer, env);
}
#[instrument(
name = "ValueTextBox",
level = "trace",
skip(self, ctx, old, data, env)
)]
fn update(&mut self, ctx: &mut UpdateCtx, old: &T, data: &T, env: &Env) {
if let Some(sel) = self.force_selection.take() {
if self.child.text().can_write() {
if let Some(change) = self.child.text_mut().borrow_mut().set_selection(sel) {
ctx.invalidate_text_input(change);
}
}
}
let changed_by_us = self
.last_known_data
.as_ref()
.map(|d| d.same(data))
.unwrap_or(false);
if self.is_editing {
if changed_by_us {
self.child.update(ctx, &self.old_buffer, &self.buffer, env);
self.old_buffer = self.buffer.clone();
} else {
// textbox is not well equipped to deal with the fact that, in
// druid, data can change anywhere in the tree. If we are actively
// editing, and new data arrives, we ignore the new data and keep
// editing; the alternative would be to cancel editing, which
// could also make sense.
tracing::warn!(
"ValueTextBox data changed externally, idk: '{}'",
self.formatter.format(data)
);
}
} else {
if !old.same(data) {
// we aren't editing and data changed
let new_text = self.formatter.format(data);
// it's possible for different data inputs to produce the same formatted
// output, in which case we would overwrite our actual previous data
if !new_text.same(&self.buffer) {
self.old_buffer = std::mem::replace(&mut self.buffer, new_text);
}
}
if !self.old_buffer.same(&self.buffer) {
// child widget handles calling request_layout, as needed
self.child.update(ctx, &self.old_buffer, &self.buffer, env);
self.old_buffer = self.buffer.clone();
} else if ctx.env_changed() {
self.child.update(ctx, &self.buffer, &self.buffer, env);
}
}
}
#[instrument(
name = "ValueTextBox",
level = "trace",
skip(self, ctx, bc, _data, env)
)]
fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, _data: &T, env: &Env) -> Size {
self.child.layout(ctx, bc, &self.buffer, env)
}
#[instrument(name = "ValueTextBox", level = "trace", skip(self, ctx, _data, env))]
fn paint(&mut self, ctx: &mut PaintCtx, _data: &T, env: &Env) {
self.child.paint(ctx, &self.buffer, env);
}
}
| true
|
65d28bf537d43cf9f9f8cfcf7b461fc71d24fd4f
|
Rust
|
hephex/api
|
/examples/httpbin.rs
|
UTF-8
| 1,283
| 2.65625
| 3
|
[
"MIT"
] |
permissive
|
#![cfg(feature = "use-hyper")]
extern crate api;
extern crate hyper;
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
use std::collections::BTreeMap;
use std::io;
use api::Client;
struct Delay {
delay: u8
}
#[derive(Debug, Deserialize)]
struct Info {
origin: String,
url: String,
headers: BTreeMap<String, String>,
}
impl api::Api for Delay {
type Reply = Info;
type Body = io::Empty;
type Error = serde_json::Error;
fn method(&self) -> api::Method {
api::Method::Get
}
fn path(&self) -> String {
format!("/delay/{}", self.delay)
}
fn query(&self) -> api::Query {
api::Query::new()
}
fn headers(&self) -> api::Headers {
let mut headers = api::Headers::new();
headers.insert("X-Request-ID".to_string(), vec!["abcde".to_string()]);
headers
}
fn body(&self) -> io::Empty {
io::empty()
}
fn parse<H>(&self, resp: &mut H) -> Result<Info, serde_json::Error>
where H: api::HttpResponse
{
serde_json::from_reader(resp.body())
}
}
fn main() {
let mut client = hyper::Client::new();
let resp = client.send("http://httpbin.org/", Delay { delay: 1 });
println!("{:?}", resp);
}
| true
|
2f2651eb57f7af92501e1796c5fbbc35f6062f5e
|
Rust
|
Harzu/wasm-rsa
|
/src/lib/private_keys.rs
|
UTF-8
| 14,975
| 2.75
| 3
|
[
"MIT"
] |
permissive
|
use super::*;
use rsa::pkcs8::FromPrivateKey;
use sha2::{ Digest };
use num_traits::{ Num };
#[wasm_bindgen]
#[derive(Debug, Clone)]
pub struct RSAPrivateKeyPair {
n: String,
d: String,
e: String,
private_instance: Option<RsaPrivateKey>
}
#[wasm_bindgen]
impl RSAPrivateKeyPair {
#[wasm_bindgen(constructor)]
pub fn new() -> Self {
RSAPrivateKeyPair {
n: "".to_string(),
e: "".to_string(),
d: "".to_string(),
private_instance: None
}
}
pub fn generate(&mut self, bits: usize, random_seed: &str) {
utils::set_panic_hook();
let mut seed_array: [u8; 32] = [0; 32];
let decode_seed = hex::decode(random_seed).unwrap();
seed_array.copy_from_slice(&decode_seed.as_slice());
let mut rng: StdRng = SeedableRng::from_seed(seed_array);
let keys = RsaPrivateKey::new(&mut rng, bits).unwrap();
self.n = keys.n().to_str_radix(16);
self.d = keys.d().to_str_radix(16);
self.e = keys.e().to_str_radix(16);
self.private_instance = Some(keys);
}
pub fn generate_from(&mut self, n: &str, d: &str, e: &str, primes: &str) {
utils::set_panic_hook();
let parse_primes = primes.split("_").collect::<Vec<&str>>();
let mut primes_vec = vec![];
for prime in parse_primes {
match BigUint::from_str_radix(&prime, 10) {
Ok(result) => primes_vec.push(result),
Err(_) => panic!("error with convert to biguint {}", prime)
}
}
let keys = RsaPrivateKey::from_components(
BigUint::from_str_radix(n, 16).expect("invalid n"),
BigUint::from_str_radix(e, 16).expect("invalid e"),
BigUint::from_str_radix(d, 16).expect("invalid d"),
primes_vec
);
self.n = keys.n().to_str_radix(16);
self.d = keys.d().to_str_radix(16);
self.e = keys.e().to_str_radix(16);
self.private_instance = Some(keys);
}
pub fn sign_message(&self, message: &str) -> String {
utils::set_panic_hook();
let digest = Sha256::digest(message.as_bytes()).to_vec();
match &self.private_instance {
Some(instance) => {
let sign = match instance.sign(
PaddingScheme::new_pkcs1v15_sign(Some(Hash::SHA2_256)),
&digest
) {
Ok(res) => res,
Err(e) => panic!("sign error {}", e)
};
hex::encode(&sign)
},
None => panic!("Instance not created")
}
}
pub fn decrypt(&self, ciphermessage: &str) -> String {
utils::set_panic_hook();
let decode_message = hex::decode(&ciphermessage).expect("invalid decode message");
match &self.private_instance {
Some(instance) => {
let decrypt_message = match instance.decrypt(
PaddingScheme::new_pkcs1v15_encrypt(),
&decode_message
) {
Ok(res) => res,
Err(e) => panic!("decrypt error {}", e)
};
String::from_utf8(decrypt_message).expect("invalid parse decrypt message")
},
None => panic!("Instance not created")
}
}
pub fn get_e(&self) -> String {
self.e.to_string()
}
pub fn get_d(&self) -> String {
self.d.to_string()
}
pub fn get_n(&self) -> String {
self.n.to_string()
}
pub fn get_primes(&self) -> String {
utils::set_panic_hook();
match &self.private_instance {
Some(instance) => {
let mut primes_string = Vec::new();
for prime in instance.primes() {
primes_string.push(prime.to_str_radix(10))
}
primes_string.join("_")
},
None => panic!("Instance not created")
}
}
pub fn to_pkcs8_pem(&self) -> String {
utils::set_panic_hook();
match &self.private_instance {
Some(keys) => {
let pem = keys.to_pkcs8_pem().expect("failed to generate private key pem format");
pem.to_string()
}
None => panic!("Instance not created")
}
}
pub fn from_pkcs8_pem(&mut self, data: &str) {
utils::set_panic_hook();
let keys = RsaPrivateKey::from_pkcs8_pem(data).expect("failed to parse private key");
self.n = keys.n().to_str_radix(16);
self.d = keys.d().to_str_radix(16);
self.e = keys.e().to_str_radix(16);
self.private_instance = Some(keys);
}
}
#[cfg(test)]
mod test {
use super::*;
mod generate {
use super::*;
#[test]
fn generate_private_keys() {
let seed = "c993abb954f4ad796efa851ce4276f12250633ec4a8da1d1c8f37a82b633c1b7";
let mut instance = RSAPrivateKeyPair::new();
instance.generate(1024, seed);
assert_ne!(instance.get_d(), "".to_string());
assert_ne!(instance.get_e(), "".to_string());
assert_ne!(instance.get_n(), "".to_string());
}
#[test]
#[should_panic]
fn generate_private_keys_with_empty_seed() {
let mut instance = RSAPrivateKeyPair::new();
instance.generate(1024, "");
}
#[test]
#[should_panic]
fn generate_private_keys_with_zero_bits() {
let seed = "c993abb954f4ad796efa851ce4276f12250633ec4a8da1d1c8f37a82b633c1b7";
let mut instance = RSAPrivateKeyPair::new();
instance.generate(0, seed);
}
}
mod generate_from {
use super::*;
#[test]
fn generate_rsa_private_from() {
let seed = "c993abb954f4ad796efa851ce4276f12250633ec4a8da1d1c8f37a82b633c1b7";
let mut first_instance = RSAPrivateKeyPair::new();
first_instance.generate(1024, seed);
let mut second_instance = RSAPrivateKeyPair::new();
second_instance.generate_from(
&first_instance.get_n(),
&first_instance.get_d(),
&first_instance.get_e(),
&first_instance.get_primes()
);
assert_eq!(first_instance.get_n(), second_instance.get_n());
assert_eq!(first_instance.get_d(), second_instance.get_d());
assert_eq!(first_instance.get_e(), second_instance.get_e());
assert_eq!(first_instance.get_primes(), second_instance.get_primes());
}
#[test]
#[should_panic]
fn generate_rsa_private_from_without_n() {
let seed = "c993abb954f4ad796efa851ce4276f12250633ec4a8da1d1c8f37a82b633c1b7";
let mut first_instance = RSAPrivateKeyPair::new();
first_instance.generate(1024, seed);
let mut second_instance = RSAPrivateKeyPair::new();
second_instance.generate_from(
"",
&first_instance.get_d(),
&first_instance.get_e(),
&first_instance.get_primes()
);
}
#[test]
#[should_panic]
fn generate_rsa_private_from_without_d() {
let seed = "c993abb954f4ad796efa851ce4276f12250633ec4a8da1d1c8f37a82b633c1b7";
let mut first_instance = RSAPrivateKeyPair::new();
first_instance.generate(1024, seed);
let mut second_instance = RSAPrivateKeyPair::new();
second_instance.generate_from(
&first_instance.get_n(),
"",
&first_instance.get_e(),
&first_instance.get_primes()
);
}
#[test]
#[should_panic]
fn generate_rsa_private_from_without_e() {
let seed = "c993abb954f4ad796efa851ce4276f12250633ec4a8da1d1c8f37a82b633c1b7";
let mut first_instance = RSAPrivateKeyPair::new();
first_instance.generate(1024, seed);
let mut second_instance = RSAPrivateKeyPair::new();
second_instance.generate_from(
&first_instance.get_n(),
&first_instance.get_d(),
"",
&first_instance.get_primes()
);
}
#[test]
#[should_panic]
fn generate_rsa_private_from_without_primes() {
let seed = "c993abb954f4ad796efa851ce4276f12250633ec4a8da1d1c8f37a82b633c1b7";
let mut first_instance = RSAPrivateKeyPair::new();
first_instance.generate(1024, seed);
let mut second_instance = RSAPrivateKeyPair::new();
second_instance.generate_from(
&first_instance.get_n(),
&first_instance.get_d(),
&first_instance.get_e(),
""
);
}
#[test]
fn convert_pem_to_keys_and_back() {
let expected_pem = "-----BEGIN PRIVATE KEY-----
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDD/UjzFPIp85KE
Ga4rhPYY0/8MszqrNHcyoogVXyg5MTXCee6nQPOk88HLsDM2KW7JBtvc2LDbzPVm
P6ZxqRsj03T3VrC4YOari460Jn9J6L4ueKvUagkxxF2XyaB7yuoblFmuTsZA98Zj
wAgfPA4G2PaeaxtdzWWXV4ehmGoXslKFzNnMSBLu/a+GROrWTT/5vg1jybXrppeD
cTeBBE+vbcv9k/Al7j6eIwCi0ObZYoEEET+3Et5hGv6w7qrH+Ds0MBhesSMmVLSm
vkEMaJxUcWGnIQazgghFjnFvnQkF57zJsMl/sTjm7QkA9IIxejPGvfgARbP1aAAv
UMtjpoULAgMBAAECggEABYwix3adUCCr0f9kFalCyfseKf7ct0HZ6d392hUCb3P8
IJAQ+Dz3aIDZyGkpWewcTaZbDMo5X09S1t0QWgE+Wmo+0k1q3R0pCkv98w1v5uim
kWwq+O0za2wydfxoBXj93V/6ldt28xnQTLx/vlqVzw3PFTbU5HfO21TH6wQEZL1D
rhEshddoU9a9qrqzsVFNLUiGHAvMR7YijagLl0t2LMSfeIt5qS4Rj7fCyXGzNNSx
01h31IfVSUT1FdWTf+fRAYF20nupqejzLjRc5srNoTrQnK7otDFYFxiwb/E2/Dte
I6kIr5SgscOBoQizBPL/yINgWjWHYUrMRyX+EN2sqQKBgQDOtX4Zs4QDNFT7otjL
D1JNIY6bcic0P86XMq6LNSV5o6JmxNDMlPD/EjVAicjOxn1LYbnzIQyuzOVrNXm0
+QA8dsJMyQzzNO7o6t9lLtrG+CXBKP7wmVBb8mMWve0VKNeLZyOpbOamGC1P7mPp
JVoRh+8DAVzKPXlEaKXXLasZHwKBgQDyuWs8b/6wv1d8WGZoXYuCkL1l/ywNidZP
AeBys4FXdqN6luOuCIoMpu7sOzCT7exu5pz3toB74bwVGRsSlcp3LJirb8LN4U3o
jkD3Tp8Gn7f7pUE43ZphU8B25ebAMBgCC5V+77HVIlo8GmLFz0M5XAslWtZ6GMmr
XF3HhERalQKBgEejfN15aqIVq/I94PaXC8XxgFP9PvsLthSOmxFhzOgYPvtw8JBG
ejNcYxpH5lFLVzcd2m0ZoiSenFAIi3Kd7WgHHJWyBAvx527Pn7aYg3f7nlIQXDKU
X9ZN7et+zUDNE86bYy+fr1wW+vU9wGCX8lwrCTm4aikpHvMHdZpamHavAoGADYSq
JkmOg8WEV9aMjY94L6NkCQQ3LeHZX7kZCQpaT8a5wCAbOhwbpCy/7cQ2Jmb/3gVW
BK3TZhLiaMJnMZfKGO0Q66tjzBeaQTN7BssILFRE6O0BPuuIp5cEhxqyyU1kaOjA
QLuUyewJ3oMRsTaj5dPsgv4WJ+KtiK+yQWRqcikCgYAwRzXzsrGK2HpkER3sEXok
hydDHbuqKLuT2Cqe6wyBpJPq5MyMu/T7ANmAPtJK4nvQF5RQoGdTne6/lvvwNMf2
ullviEZz1ehunkmoU25CgAKLXXCMmw/T8GyX6UUIqofyFGHasj/vjA8ZIpdLyKVP
khSri8NDQTao0i43teKIMA==
-----END PRIVATE KEY-----
";
let mut instance = RSAPrivateKeyPair::new();
instance.from_pkcs8_pem(expected_pem);
let actual_pem = instance.to_pkcs8_pem();
assert_eq!(expected_pem, actual_pem)
}
#[test]
fn generate_pem_from_new_keys() {
let seed = "c993abb954f4ad796efa851ce4276f12250633ec4a8da1d1c8f37a82b633c1b7";
let mut private_instance = RSAPrivateKeyPair::new();
private_instance.generate(1024, seed);
let private_pem = private_instance.to_pkcs8_pem();
assert_ne!(private_pem, "".to_string());
}
#[test]
#[should_panic]
fn failed_generate_pem_instance_not_created() {
RSAPrivateKeyPair::new().to_pkcs8_pem();
}
#[test]
#[should_panic]
fn failed_create_instance_from_pem() {
let invalid_pem = "invalid_pem";
let mut instance = RSAPrivateKeyPair::new();
instance.from_pkcs8_pem(invalid_pem);
}
}
mod sign {
use super::*;
#[test]
fn sign_message() {
let message = "Hello";
let seed = "c993abb954f4ad796efa851ce4276f12250633ec4a8da1d1c8f37a82b633c1b7";
let mut instance = RSAPrivateKeyPair::new();
instance.generate(1024, seed);
assert_ne!(instance.sign_message(message), "".to_string());
}
#[test]
fn sign_message_with_long_data() {
let message = "{ id: 'c993abb954f4ad796efa851ce4276f12250633ec4a8da1d1c8f37a82b633c1b7, id2: c993abb954f4ad796efa851ce4276f12250633ec4a8da1d1c8f37a82b633c1b7, id3: c993abb954f4ad796efa851ce4276f12250633ec4a8da1d1c8f37a82b633c1b7, id4: c993abb954f4ad796efa851ce4276f12250633ec4a8da1d1c8f37a82b633c1b7' }";
let seed = "c993abb954f4ad796efa851ce4276f12250633ec4a8da1d1c8f37a82b633c1b7";
let mut instance = RSAPrivateKeyPair::new();
instance.generate(1024, seed);
let signature = instance.sign_message(message);
assert_ne!(signature, "".to_string());
}
#[test]
#[should_panic]
fn sign_message_without_keys() {
let message = "Hello";
let instance = RSAPrivateKeyPair::new();
instance.sign_message(message);
}
#[test]
fn sign_message_with_generate_keys_from_data() {
let message = "hello";
let seed = "c993abb954f4ad796efa851ce4276f12250633ec4a8da1d1c8f37a82b633c1b7";
let mut private_instance = RSAPrivateKeyPair::new();
private_instance.generate(1024, seed);
let n = private_instance.get_n();
let e = private_instance.get_e();
let d = private_instance.get_d();
let primes = private_instance.get_primes();
private_instance = RSAPrivateKeyPair::new();
private_instance.generate_from(&n, &d, &e, &primes);
let signature = private_instance.sign_message(message);
assert_ne!(signature, "".to_string())
}
}
mod decrypt {
use super::*;
#[test]
fn decrypt_message() {
let message = "hello";
let seed = "c993abb954f4ad796efa851ce4276f12250633ec4a8da1d1c8f37a82b633c1b7";
let mut public_instance = public_keys::RSAPublicKeyPair::new();
let mut private_instance = RSAPrivateKeyPair::new();
private_instance.generate(1024, seed);
public_instance.create(&private_instance.get_n(), &private_instance.get_e());
let encrypted_message = public_instance.encrypt(message, seed);
let decrypted_message = private_instance.decrypt(&encrypted_message);
assert_eq!(decrypted_message, message);
}
#[test]
#[should_panic]
fn decrypt_message_with_invalid_message() {
let seed = "c993abb954f4ad796efa851ce4276f12250633ec4a8da1d1c8f37a82b633c1b7";
let mut private_instance = RSAPrivateKeyPair::new();
private_instance.generate(1024, seed);
private_instance.decrypt("");
}
#[test]
#[should_panic]
fn decrypt_message_without_keys() {
let message = "hello";
let seed = "c993abb954f4ad796efa851ce4276f12250633ec4a8da1d1c8f37a82b633c1b7";
let mut public_instance = public_keys::RSAPublicKeyPair::new();
let mut private_instance = RSAPrivateKeyPair::new();
private_instance.generate(1024, seed);
public_instance.create(&private_instance.get_n(), &private_instance.get_e());
let encrypted_message = public_instance.encrypt(message, seed);
private_instance = RSAPrivateKeyPair::new();
private_instance.decrypt(&encrypted_message);
}
#[test]
fn decrypt_message_with_generate_keys_from_data() {
let message = "hello";
let seed = "c993abb954f4ad796efa851ce4276f12250633ec4a8da1d1c8f37a82b633c1b7";
let mut public_instance = public_keys::RSAPublicKeyPair::new();
let mut private_instance = RSAPrivateKeyPair::new();
private_instance.generate(1024, seed);
let n = private_instance.get_n();
let e = private_instance.get_e();
let d = private_instance.get_d();
let primes = private_instance.get_primes();
public_instance.create(&n, &e);
let encrypted_message = public_instance.encrypt(message, seed);
private_instance = RSAPrivateKeyPair::new();
private_instance.generate_from(&n, &d, &e, &primes);
private_instance.decrypt(&encrypted_message);
}
}
}
| true
|
c174399487f7884c888dcaae96b947a8b2c75d0a
|
Rust
|
vangroan/vnote-cli
|
/src/main.rs
|
UTF-8
| 5,088
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
extern crate chrono;
#[macro_use]
extern crate clap;
extern crate colored;
extern crate dirs;
extern crate levenshtein;
extern crate regex;
extern crate serde;
extern crate serde_yaml;
#[macro_use]
extern crate error_chain;
mod book;
mod config;
mod errors;
mod util;
use book::{
Note, NotebookFileStorage, NotebookSearch, NotebookStore, PossibleTopic, DEFAULT_BOOK_NAME,
};
use clap::{App, Arg, SubCommand};
use colored::*;
use std::collections::HashMap;
fn main() {
// Older Windows CMD does not support coloured output
#[cfg(windows)]
{
if ansi_term::enable_ansi_support().is_err() {
colored::control::set_override(false);
}
}
let matches = App::new("VNote")
.version(crate_version!())
.author("Willem Victor <wimpievictor@gmail.com>")
.about("A command-line tool for taking micro notes")
.subcommand(
SubCommand::with_name("add")
.about("adds a note to book")
.arg(
Arg::with_name("TOPIC")
.required(true)
.help("name of note topic"),
)
.arg(
Arg::with_name("NOTE")
.required(true)
.help("text content of note"),
),
)
.subcommand(
SubCommand::with_name("find")
.about("searches for a note using a regular expression")
.arg(
Arg::with_name("PATTERN")
.required(true)
.help("regular expression for search"),
)
.arg(
Arg::with_name("topic")
.short("t")
.long("topic")
.takes_value(true)
.help("narrows search to a specific topic"),
),
)
.get_matches();
if let Some(matches) = matches.subcommand_matches("add") {
let topic = matches.value_of("TOPIC").unwrap();
let note = matches.value_of("NOTE").unwrap();
println!(" {} adding [{}] {}", "#".yellow(), topic, note);
// First we ensure that we can create a note
let note = Note::new(note.to_string());
let id = note.id();
// Then we save it to disk
let store = NotebookFileStorage::default();
if let Err(err) = store.setup() {
eprintln!(" {} failed to initiate file storage: {:?}", "!".red(), err);
}
// TODO: get notebook name from command line argument
store
.add_note(topic, note, None)
.unwrap_or_else(|err| panic!(" {} failed to save notebook: {}", "!".red(), err));
println!(" {} added {}", "✓".green(), id);
}
if let Some(matches) = matches.subcommand_matches("find") {
let pattern = matches.value_of("PATTERN").unwrap();
let maybe_topic = matches.value_of("topic");
println!(" {} searching...", "#".yellow());
let store = NotebookFileStorage::default();
// let search = NotebookSearch::new();
// TODO: get notebook name from command line argument
let book = store
.load_book(DEFAULT_BOOK_NAME)
.unwrap_or_else(|err| panic!(" {} failed to load notebook: {}", "!".red(), err));
let matched_topic = {
if let Some(topic) = maybe_topic {
match NotebookSearch::new().match_topic(topic, &book) {
PossibleTopic::Exact => Some(topic),
PossibleTopic::CloseMatch { topic, .. } => Some(topic),
PossibleTopic::Nothing => {
println!(" {} topic '{}' not found", "!".red(), topic);
return;
}
}
} else {
None
}
};
match NotebookSearch::new().scan_notes(pattern, matched_topic, &book) {
Ok(results) => {
if results.0.is_empty() {
println!(" {} no results found", "✓".green());
} else {
println!(" {} results found", "✓".green());
// For display, group according to topics
let mut topic_map: HashMap<&str, Vec<&Note>> = HashMap::new();
for (topic, note) in results.0.into_iter() {
topic_map.entry(topic).or_insert_with(|| vec![]).push(note);
}
// Iterate again to display
for (topic, notes) in topic_map {
println!(" {}", topic.green());
for note in notes {
// TODO: colour matched part of string
println!(" - {}", note.content());
}
}
}
}
Err(err) => eprintln!(" {} failed to search notebook: {:?}", "!".red(), err),
}
}
}
| true
|
bc906493238622ba0b5a079aa6875bd39fa959d7
|
Rust
|
Bixkog/dotastats
|
/src/analyzers/analyzers_utils.rs
|
UTF-8
| 730
| 2.75
| 3
|
[
"MIT"
] |
permissive
|
use crate::heroes_info::Hero;
use crate::heroes_info::HeroesInfo;
use crate::match_stats::Match;
use crate::match_stats::PlayerName;
#[macro_export]
macro_rules! skip_fail {
($res:expr) => {
match $res {
Ok(val) => val,
Err(_) => continue,
}
};
}
/// Finds heroes played by players.
pub fn get_heroes(
heroes_info: &HeroesInfo,
match_: &Match,
mut team: Vec<String>,
) -> Vec<(PlayerName, Hero)> {
let mut team_setup = vec![];
team.sort();
for player in team {
let player_hero_id = skip_fail!(match_.get_player_hero(&player));
let hero = heroes_info.get_hero(player_hero_id);
team_setup.push((player, hero));
}
team_setup
}
| true
|
2d1c2c6d3807a1b9b56673652c014813777c3e9e
|
Rust
|
yuulive/oy
|
/tests/root.rs
|
UTF-8
| 4,190
| 3.28125
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"MIT"
] |
permissive
|
#![feature(str_split_once)]
use core::fmt::Debug;
use oy::{Interactive, InteractiveError, InteractiveRoot, Methods};
#[derive(Interactive, Debug, Default)]
struct TestStruct {
a: bool,
}
#[Methods]
impl TestStruct {
fn try_ping(&self) -> core::result::Result<String, ()> {
Ok("pong".into())
}
fn answer(&self) {
println!("42");
}
fn add(&self, a: f32, b: f32) -> f32 {
a + b
}
fn frob(&self, a: usize, b: f32, c: i32) -> (usize, f32, i32) {
(a, b, c)
}
fn toggle(&mut self) {
self.a = !self.a;
}
}
#[derive(Interactive, Debug, Default)]
struct ParentStruct {
child: TestStruct,
}
#[derive(InteractiveRoot, Default, Debug)]
struct Root {
parent: ParentStruct,
}
#[test]
fn test_get_root_object() {
let mut root = Root::default();
assert_eq!(
root.eval_to_string("parent"),
"ParentStruct { child: TestStruct { a: false } }"
);
}
#[test]
fn test_get_child() {
let mut root = Root::default();
assert_eq!(
root.eval_to_string("parent.child"),
"TestStruct { a: false }"
);
}
#[test]
fn test_get_child_field() {
let mut root = Root::default();
assert_eq!(root.eval_to_string("parent.child.a"), "false");
}
#[test]
fn test_call_child_method() {
let mut root = Root::default();
assert_eq!(
root.eval_to_string("parent.child.try_ping()"),
"Ok(\"pong\")"
);
}
#[test]
fn test_call_with_float() {
let mut root = Root::default();
assert_eq!(root.eval_to_string("parent.child.add(4.20, 6.9)"), "11.1");
}
#[test]
fn test_call_with_different_arg_types() {
let mut root = Root::default();
assert_eq!(
root.eval_to_string("parent.child.frob(420, 6.9, -7)"),
"(420, 6.9, -7)"
);
}
#[test]
fn test_call_with_bad_args() {
use oy::ArgParseError;
let mut root = Root::default();
assert_eq!(
root.eval_to_string("parent.child.add(nope, 1)"),
format!(
"{}",
InteractiveError::ArgParseError {
method_name: "add",
error: ArgParseError::ParseFloatError("nope".parse::<f32>().unwrap_err())
}
)
);
}
#[test]
fn test_shared_reference_field() {
#[derive(InteractiveRoot)]
struct RefStruct<'a> {
child: &'a TestStruct,
}
let child = TestStruct::default();
let mut root = RefStruct { child: &child };
assert_eq!(root.eval_to_string("child.a"), "false");
}
#[test]
fn test_shared_reference_method() {
#[derive(InteractiveRoot)]
struct RefStruct<'a> {
child: &'a TestStruct,
}
let child = TestStruct::default();
let mut root = RefStruct { child: &child };
assert_eq!(root.eval_to_string("child.add(1, 2)"), "3.0");
}
#[test]
fn test_shared_reference_mut_method() {
#[derive(InteractiveRoot)]
struct RefStruct<'a> {
child: &'a TestStruct,
}
let child = TestStruct::default();
let mut root = RefStruct { child: &child };
assert_eq!(
root.eval_to_string("child.toggle()"),
format!(
"{}",
InteractiveError::MethodNotFound {
type_name: "TestStruct",
method_name: "toggle"
}
)
);
// TODO custom mutability error
}
#[test]
fn test_shared_dyn_reference_field() {
#[derive(InteractiveRoot)]
struct RefStruct<'a> {
child: &'a dyn Interactive,
}
let child = TestStruct::default();
let mut root = RefStruct { child: &child };
assert_eq!(root.eval_to_string("child.a"), "false");
}
#[test]
fn test_mut_dyn_reference_field() {
#[derive(InteractiveRoot)]
struct RefStruct<'a> {
child: &'a mut dyn Interactive,
}
let mut child = TestStruct::default();
let mut root = RefStruct { child: &mut child };
assert_eq!(root.eval_to_string("child.a"), "false");
}
#[test]
fn test_primitive_access() {
let mut root = Root::default();
assert_eq!(
root.eval_to_string("parent.child.a.b"),
format!(
"{}",
InteractiveError::InteractiveNotImplemented { type_name: "bool" }
)
);
}
| true
|
52617432337ed81d99906da16611711559ecf0a8
|
Rust
|
Azegor/wasm-interpreter
|
/src/parser/table_section.rs
|
UTF-8
| 702
| 2.828125
| 3
|
[] |
no_license
|
use parser::{Parser, ResizableLimits, Type};
#[derive(Debug)]
pub struct TableEntry {
pub typ: Type,
pub limits: ResizableLimits,
}
impl Parser {
fn read_table_type(&mut self) -> TableEntry {
let typ = Type::elem_type(self.read_varuint7());
let limits = self.read_resizable_limits();
TableEntry { typ, limits }
}
pub fn parse_table_section(&mut self, payload_len: u32) -> Vec<TableEntry> {
println!(" # Parsing table section");
let init_offset = self.get_current_offset();
let entries = self.read_vu32_times(Parser::read_table_type);
assert_eq!(self.get_read_len(init_offset), payload_len);
return entries;
}
}
| true
|
72b45eaa86860b46a2d55a170b36fa9932c36efd
|
Rust
|
CryZe/cargo-go
|
/src/open.rs
|
UTF-8
| 1,384
| 2.765625
| 3
|
[
"MIT",
"Apache-2.0"
] |
permissive
|
// The code is borrowed from and should be kept in sync with:
// https://github.com/rust-lang/cargo/blob/master/src/cargo/ops/cargo_doc.rs
use std::process::Command;
pub fn open(path: &str) -> Result<(), String> {
match run(path) {
Ok(_) => Ok(()),
Err(_) => raise!("cannot go to {:?}", path),
}
}
#[cfg(not(any(target_os = "windows", target_os = "macos")))]
fn run(path: &str) -> Result<&str, Vec<&str>> {
use std::env;
let mut methods = vec![];
if let Ok(name) = env::var("BROWSER") {
match Command::new(name).arg(path).status() {
Ok(_) => return Ok("$BROWSER"),
Err(_) => methods.push("$BROWSER"),
}
}
for method in ["xdg-open", "gnome-open", "kde-open"].iter() {
match Command::new(method).arg(path).status() {
Ok(_) => return Ok(method),
Err(_) => methods.push(method),
}
}
Err(methods)
}
#[cfg(target_os = "macos")]
fn run(path: &str) -> Result<&str, Vec<&str>> {
match Command::new("open").arg(path).status() {
Ok(_) => Ok("open"),
Err(_) => Err(vec!["open"]),
}
}
#[cfg(target_os = "windows")]
fn run(path: &str) -> Result<&str, Vec<&str>> {
match Command::new("cmd").arg("/C").arg("start").arg("").arg(path).status() {
Ok(_) => Ok("cmd /C start"),
Err(_) => Err(vec!["cmd /C start"]),
}
}
| true
|
e20c9d950885ceeb08a5a52c28800097a021ac72
|
Rust
|
simongibbons/advent_of_code2020
|
/src/day25.rs
|
UTF-8
| 1,652
| 3.25
| 3
|
[] |
no_license
|
use itertools::Itertools;
pub struct PublicKeys {
card: u64,
door: u64
}
#[aoc_generator(day25)]
pub fn parse_input(input: &str) -> PublicKeys {
let split = input.split("\n")
.map(|x| x.parse().unwrap())
.collect_vec();
PublicKeys {
card: split[0],
door: split[1]
}
}
fn iterate(input: u64, subject_number: u64) -> u64 {
(input * subject_number) % 20201227
}
fn transform_subject(subject_number: u64, loop_size: usize) -> u64 {
let mut result = 1;
for _ in 0..loop_size {
result = iterate(result, subject_number);
}
result
}
fn determine_private_key(public_key: u64) -> usize {
let mut transformed = 1;
for loop_size in 1.. {
transformed = iterate(transformed, 7);
if transformed == public_key {
return loop_size;
}
}
unreachable!();
}
fn generate_key(public_key_1: u64, private_key_2: usize) -> u64 {
transform_subject(public_key_1, private_key_2)
}
#[aoc(day25, part1)]
pub fn part1(keys: &PublicKeys) -> u64 {
let door_private_key = determine_private_key(keys.door);
let card_private_key = determine_private_key(keys.card);
let k1 = generate_key(keys.door, card_private_key);
let k2 = generate_key(keys.card, door_private_key);
assert_eq!(k1, k2);
k1
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_determine_public_key() {
assert_eq!(8, determine_private_key(5764801));
assert_eq!(5764801, transform_subject(7, 8));
assert_eq!(11, determine_private_key(17807724));
assert_eq!(17807724, transform_subject(7, 11));
}
}
| true
|
3787e70dd0641aef18e80cf351eeb3d6e6809581
|
Rust
|
bilsen/rust-website
|
/src/db/user.rs
|
UTF-8
| 672
| 2.65625
| 3
|
[] |
no_license
|
use crate::schema::users;
#[derive(Queryable, Serialize)]
pub struct User {
// User id
pub id: i32,
// Username
pub username: String,
// Email adress
pub email_adress: String,
// Hashed password
pub password_hash: String,
// User rating
pub rating: i32,
// User preferences (data which should not be queried)
pub preferences: serde_json::value::Value
}
// Struct for inserting user into table
#[derive(Insertable)]
#[table_name="users"]
pub struct InsertableUser {
pub username: String,
pub email_adress: String,
pub password_hash: String,
pub rating: i32,
pub preferences: serde_json::value::Value,
}
| true
|
999137dbf163056be2061084a41be709cde5ed49
|
Rust
|
OpenTrustGroup/fuchsia
|
/src/connectivity/bluetooth/tools/bt-snoop/src/packet_logs.rs
|
UTF-8
| 5,453
| 2.5625
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use {
fidl_fuchsia_bluetooth_snoop::SnoopPacket,
fuchsia_inspect::{self as inspect, Property},
itertools::Itertools,
std::{
collections::{
vec_deque::{Iter as VecDequeIter, VecDeque},
HashMap,
},
time::Duration,
},
};
use crate::{
bounded_queue::{BoundedQueue, CreatedAt, SizeOf},
DeviceId,
};
// Size for SnoopPacket must be implemented here because SnoopPacket is defined in generated code.
impl SizeOf for SnoopPacket {
fn size_of(&self) -> usize {
std::mem::size_of::<Self>() + self.payload.len()
}
}
// CreatedAt for SnoopPacket must be implemented here because SnoopPacket is defined in generated
// code.
impl CreatedAt for SnoopPacket {
fn created_at(&self) -> Duration {
Duration::new(self.timestamp.seconds, self.timestamp.subsec_nanos)
}
}
/// Alias for a queue of snoop packets.
pub(crate) type PacketLog = BoundedQueue<SnoopPacket>;
/// A container for packet logs for each snoop channel.
// Internal invariant: `device_logs.len()` must always equal `insertion_order.len()`.
// any method that modifies these fields must ensure the invariant holds after the
// method returns.
pub(crate) struct PacketLogs {
max_device_count: usize,
log_size_bytes: usize,
log_age: Duration,
device_logs: HashMap<DeviceId, PacketLog>,
insertion_order: VecDeque<DeviceId>,
// Inspect Data
inspect: inspect::Node,
logging_for_devices: inspect::StringProperty,
}
impl PacketLogs {
/// Create a new `PacketLogs` struct. `max_device_count` sets the number of hci devices the
/// logger will store packets for. `log_size_bytes` sets the size limit associated with each
/// device (see `BoundedQueue` documentation for more information). `log_age` sets the age limit
/// associated with each device (see `BoundedQueue` documentation for more information).
///
/// Note that the `log_size_bytes` and `log_age` values are set on a _per device_ basis.
///
/// Panics if `max_device_count` is 0.
pub fn new(
max_device_count: usize,
log_size_bytes: usize,
log_age: Duration,
inspect: inspect::Node,
) -> PacketLogs {
assert!(max_device_count != 0, "Cannot create a `PacketLog` with a max_device_count of 0");
let logging_for_devices = inspect.create_string("logging_active_for_devices", "");
PacketLogs {
max_device_count,
log_size_bytes,
log_age,
device_logs: HashMap::new(),
insertion_order: VecDeque::new(),
inspect,
logging_for_devices,
}
}
/// Add a log to record packets for a new device. Return the `DeviceId` of the oldest log if it
/// was removed to make room for the new device log.
/// If the device is already being recorded, this method does nothing.
pub fn add_device(&mut self, device: DeviceId) -> Option<DeviceId> {
if self.device_logs.contains_key(&device) {
return None;
}
// Add log and update insertion order metadata
self.insertion_order.push_back(device.clone());
let bounded_queue_metrics = self.inspect.create_child(&format!("device_{}", device));
self.device_logs.insert(
device.clone(),
BoundedQueue::new(self.log_size_bytes, self.log_age, bounded_queue_metrics),
);
// Remove old log and its insertion order metadata if there are too many logs
//
// TODO (belgum): This is a first pass at an algorithm to determine which log to drop in
// the case of too many logs. Alternatives that can be explored in the future include
// variations of LRU or LFU caching which may or may not account for empty device logs.
let removed =
if self.device_logs.len() > self.max_device_count { self.drop_oldest() } else { None };
let device_ids = self.device_ids().map(|id| format!("{:?}", id)).join(", ");
self.logging_for_devices.set(&device_ids);
removed
}
// This method requires that there are logs for at least 1 device.
fn drop_oldest(&mut self) -> Option<DeviceId> {
if let Some(oldest_key) = self.insertion_order.pop_front() {
// remove the bounded queue associated with the oldest DeviceId.
self.device_logs.remove(&oldest_key);
Some(oldest_key)
} else {
None
}
}
/// Get a mutable reference to a single log by `DeviceId`
pub fn get_log_mut(&mut self, device: &DeviceId) -> Option<&mut PacketLog> {
self.device_logs.get_mut(device)
}
/// Iterator over the device ids which `PacketLogs` is currently recording packets for.
pub fn device_ids<'a>(&'a self) -> VecDequeIter<'a, DeviceId> {
self.insertion_order.iter()
}
/// Log a packet for a given device. If the device is not being logged, the packet is
/// dropped.
pub fn log_packet(&mut self, device: &DeviceId, packet: SnoopPacket) {
// If the packet log has been removed, there's not much we can do with the packet.
if let Some(packet_log) = self.device_logs.get_mut(device) {
packet_log.insert(packet);
}
}
}
| true
|
2ca1e6b3bbb5d924cf8bda9909e548b88051937f
|
Rust
|
starcoinorg/starcoin
|
/vm/types/src/token/token_value.rs
|
UTF-8
| 3,773
| 3.109375
| 3
|
[
"Apache-2.0"
] |
permissive
|
// Copyright (c) The Starcoin Core Contributors
// SPDX-License-Identifier: Apache-2.0
use anyhow::{ensure, Result};
pub trait TokenUnit: Clone + Copy {
fn symbol(&self) -> &'static str;
fn symbol_lowercase(&self) -> &'static str;
fn scale(&self) -> u32;
fn scaling_factor(&self) -> u128 {
10u32.pow(self.scale()) as u128
}
fn scaling(&self, value: u128) -> u128 {
self.scaling_factor() * value
}
fn parse(&self, input: &str) -> Result<TokenValue<Self>> {
ensure!(!input.is_empty(), "Empty input not allowed for token unit");
let symbol = self.symbol();
let input = if let Some(stripped) = input.strip_suffix(symbol) {
stripped
} else {
input
};
let input = input.trim();
let parts: Vec<&str> = input.split('.').collect();
ensure!(parts.len() <= 2, "Invalid decimal value, too many '.'");
let h: u128 = parts[0].parse()?;
let l: u128 = if parts.len() == 2 {
let s = parts[1];
let s = s.trim_end_matches('0');
if s.is_empty() {
0u128
} else {
let scale = self.scale();
ensure!(
s.len() <= (scale as usize),
"Decimal part {} is overflow.",
s
);
let s = padding_zero(s, scale, false);
s.parse()?
}
} else {
0
};
TokenValue::new_with_parts(h, l, *self)
}
fn max(&self) -> u128 {
u128::max_value() / self.scaling_factor()
}
}
fn padding_zero(origin: &str, scale: u32, left: bool) -> String {
let mut result = origin.to_string();
let pad = "0".repeat((scale as usize) - origin.len());
if left {
result.insert_str(0, pad.as_str());
} else {
result.push_str(pad.as_str());
}
result
}
#[derive(Clone, Copy, Debug)]
pub struct TokenValue<U>
where
U: TokenUnit,
{
//value before decimal point
h: u128,
//value after decimal point
l: u128,
unit: U,
}
impl<U> std::fmt::Display for TokenValue<U>
where
U: TokenUnit,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let (p1, p2) = self.decimal();
if p2 == 0 {
write!(f, "{}{}", p1, self.unit.symbol())
} else {
let p2 = padding_zero(p2.to_string().as_str(), self.unit.scale(), true);
let p2 = p2.trim_end_matches('0');
write!(f, "{}.{}{}", p1, p2, self.unit.symbol())
}
}
}
impl<U> TokenValue<U>
where
U: TokenUnit,
{
pub fn new(value: u128, unit: U) -> Self {
Self {
h: value,
l: 0,
unit,
}
}
pub fn new_with_parts(h: u128, l: u128, unit: U) -> Result<Self> {
ensure!(
h < unit.max(),
"{} is too big than unit max value: {}",
h,
unit.max()
);
ensure!(
l < unit.scaling_factor(),
"Digits after the decimal point: {} contains digits more than scaling_factor: {}.",
l,
unit.scale()
);
Ok(Self { h, l, unit })
}
pub fn decimal(&self) -> (u128, u128) {
(self.h, self.l)
}
pub fn scaling(&self) -> u128 {
// h * scaling_factor + l
self.h
.checked_mul(self.unit.scaling_factor())
.and_then(|v| v.checked_add(self.l))
.expect("Scaling overflow.")
}
pub fn convert(self, unit: U) -> Self {
if self.unit.scale() == unit.scale() {
self
} else {
TokenValue::new(self.scaling(), unit)
}
}
}
| true
|
781fc4b38a475b67d469350a0dbc8d6423b1f298
|
Rust
|
Tomarchelone/mp3
|
/src/lib.rs
|
UTF-8
| 1,333
| 2.65625
| 3
|
[
"CC0-1.0",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"MIT"
] |
permissive
|
#![forbid(unsafe_code)]
#[macro_use]
extern crate smallvec;
pub mod frame;
pub mod header;
pub mod tables;
use std::io;
use std::str;
pub static ID3V1_LEN: usize = 128;
#[derive(Debug)]
pub enum Mp3Error {
// Unable to trim ID3 tag
ID3Error,
// Incorrect Header
HeaderError,
IoError(io::Error),
Utf8Error(str::Utf8Error),
}
impl From<io::Error> for Mp3Error {
fn from(e: io::Error) -> Mp3Error {
Mp3Error::IoError(e)
}
}
impl From<str::Utf8Error> for Mp3Error {
fn from(e: str::Utf8Error) -> Mp3Error {
Mp3Error::Utf8Error(e)
}
}
/// Strip ID3 tag from data and find first frame
pub fn strip_id3(data: &[u8]) -> Result<&[u8], Mp3Error> {
// Check if it is ID3v2
match &data[..3] {
b"ID3" => {
let id3_len = (data[6] as usize) * 128 * 128 * 128
+ (data[7] as usize) * 128 * 128
+ (data[8] as usize) * 128
+ (data[9] as usize);
return Ok(&data[10 + id3_len..]);
}
_ => {
let start_of_tag = data.len() - ID3V1_LEN;
// Check if it is ID3v1
match &data[start_of_tag..start_of_tag + 3] {
b"TAG" => return Ok(&data[..start_of_tag]),
_ => return Err(Mp3Error::ID3Error),
}
}
}
}
| true
|
99878d1de461573a3fc9a5f660b9b9c199aa8d36
|
Rust
|
stm32-rs/stm32l0xx-hal
|
/src/timer.rs
|
UTF-8
| 12,620
| 2.75
| 3
|
[
"BSD-3-Clause",
"0BSD",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
//! Timers
use crate::hal::timer::{CountDown, Periodic};
use crate::pac::{tim2, tim21, tim22, tim6, TIM2, TIM21, TIM22, TIM3, TIM6};
use crate::rcc::{Clocks, Enable, Rcc, Reset};
use cast::{u16, u32};
use cortex_m::peripheral::syst::SystClkSource;
use cortex_m::peripheral::SYST;
use embedded_time::rate::Hertz;
use void::Void;
pub trait TimerExt<TIM> {
fn timer<T>(self, timeout: T, rcc: &mut Rcc) -> Timer<TIM>
where
T: Into<Hertz>;
}
/// Hardware timers
pub struct Timer<TIM> {
clocks: Clocks,
tim: TIM,
}
impl Timer<SYST> {
/// Configures the SYST clock as a periodic count down timer
pub fn syst<T>(mut syst: SYST, timeout: T, rcc: &mut Rcc) -> Self
where
T: Into<Hertz>,
{
syst.set_clock_source(SystClkSource::Core);
let mut timer = Timer {
tim: syst,
clocks: rcc.clocks,
};
timer.start(timeout);
timer
}
/// Starts listening
pub fn listen(&mut self) {
self.tim.enable_interrupt()
}
/// Stops listening
pub fn unlisten(&mut self) {
self.tim.disable_interrupt()
}
}
impl CountDown for Timer<SYST> {
type Time = Hertz;
fn start<T>(&mut self, timeout: T)
where
T: Into<Hertz>,
{
let rvr = self.clocks.sys_clk().0 / timeout.into().0 - 1;
assert!(rvr < (1 << 24));
self.tim.set_reload(rvr);
self.tim.clear_current();
self.tim.enable_counter();
}
fn wait(&mut self) -> nb::Result<(), Void> {
if self.tim.has_wrapped() {
Ok(())
} else {
Err(nb::Error::WouldBlock)
}
}
}
impl TimerExt<SYST> for SYST {
fn timer<T>(self, timeout: T, rcc: &mut Rcc) -> Timer<SYST>
where
T: Into<Hertz>,
{
Timer::syst(self, timeout, rcc)
}
}
impl Periodic for Timer<SYST> {}
/// Trait for general purpose timer peripherals
pub trait GeneralPurposeTimer: Enable + Reset {
type MasterMode;
/// Selects the master mode for this timer
fn select_master_mode(&mut self, variant: Self::MasterMode);
}
impl<T: GeneralPurposeTimer> Timer<T> {
pub fn new(tim: T, rcc: &mut Rcc) -> Self {
T::enable(rcc);
T::reset(rcc);
Timer {
tim,
clocks: rcc.clocks,
}
}
}
macro_rules! timers {
($($TIM:ident: ($tim:ident, $timclk:ident, $mms:ty),)+) => {
$(
impl TimerExt<$TIM> for $TIM {
fn timer<T>(self, timeout: T, rcc: &mut Rcc) -> Timer<$TIM>
where
T: Into<Hertz>,
{
Timer::$tim(self, timeout, rcc)
}
}
impl Timer<$TIM> where $TIM: GeneralPurposeTimer {
/// Configures a TIM peripheral as a periodic count down timer
pub fn $tim<T>(tim: $TIM, timeout: T, rcc: &mut Rcc) -> Self
where
T: Into<Hertz>,
{
let mut timer = Timer::new(tim, rcc);
timer.start(timeout);
timer
}
/// Starts listening
pub fn listen(&mut self) {
self.tim.dier.write(|w| w.uie().set_bit());
}
/// Stops listening
pub fn unlisten(&mut self) {
self.tim.dier.write(|w| w.uie().clear_bit());
}
/// Clears interrupt flag
pub fn clear_irq(&mut self) {
self.tim.sr.write(|w| w.uif().clear_bit());
}
/// Releases the TIM peripheral
pub fn release(mut self) -> $TIM {
self.pause();
self.tim
}
/// Pause counting
pub fn pause(&mut self) {
self.tim.cr1.modify(|_, w| w.cen().clear_bit());
}
/// Resume counting
pub fn resume(&mut self) {
self.tim.cr1.modify(|_, w| w.cen().set_bit());
}
/// Reset counter
pub fn reset(&mut self) {
// pause
self.pause();
// reset counter
self.tim.cnt.reset();
// continue
self.resume();
}
/// Select master mode
pub fn select_master_mode(&mut self,
variant: <$TIM as GeneralPurposeTimer>::MasterMode,
) {
self.tim.select_master_mode(variant);
}
}
impl CountDown for Timer<$TIM> {
type Time = Hertz;
fn start<T>(&mut self, timeout: T)
where
T: Into<Hertz>,
{
// pause
self.pause();
// reset counter
self.tim.cnt.reset();
let freq = timeout.into().0;
let ticks = self.clocks.$timclk().0 / freq;
let psc = u16((ticks - 1) / (1 << 16)).unwrap();
self.tim.psc.write(|w| w.psc().bits(psc));
// This is only unsafe for some timers, so we need this to
// suppress the warnings.
#[allow(unused_unsafe)]
self.tim.arr.write(|w|
unsafe {
w.arr().bits(u16(ticks / u32(psc + 1)).unwrap())
}
);
// Load prescaler value and reset its counter.
// Setting URS makes sure no interrupt is generated.
self.tim.cr1.modify(|_, w| w.urs().set_bit());
self.tim.egr.write(|w| w.ug().set_bit());
self.resume();
}
fn wait(&mut self) -> nb::Result<(), Void> {
if self.tim.sr.read().uif().bit_is_clear() {
Err(nb::Error::WouldBlock)
} else {
self.tim.sr.modify(|_, w| w.uif().clear_bit());
Ok(())
}
}
}
impl Periodic for Timer<$TIM> {}
impl GeneralPurposeTimer for $TIM {
type MasterMode = $mms;
fn select_master_mode(&mut self, variant: Self::MasterMode) {
self.cr2.modify(|_, w| w.mms().variant(variant));
}
}
)+
}
}
/// Two linked 16 bit timers that form a 32 bit timer.
pub trait LinkedTimer {
/// Return the current 16 bit counter value of the MSB timer.
fn get_counter_msb(&self) -> u16;
/// Return the current 16 bit counter value of the LSB timer.
fn get_counter_lsb(&self) -> u16;
/// Return the current 32 bit counter value.
fn get_counter(&self) -> u32;
/// Reset the counter to 0.
fn reset(&mut self);
}
/// A pair of timers that can be linked.
///
/// The two timers are configured so that an overflow of the primary timer
/// triggers an update on the secondary timer. This way, two 16 bit timers can
/// be combined to a single 32 bit timer.
pub struct LinkedTimerPair<PRIMARY, SECONDARY> {
/// Timer in primary mode
tim_primary: PRIMARY,
/// Timer in secondary mode
tim_secondary: SECONDARY,
}
macro_rules! linked_timers {
($(
($PRIMARY:ident, $SECONDARY:ident): (
$new:ident,
$mms:ty, $sms:ty, $ts:expr
),
)+) => {
$(
impl LinkedTimerPair<$PRIMARY, $SECONDARY> {
/// Create and configure a new `LinkedTimerPair` with the
/// specified timers.
pub fn $new(tim_primary: $PRIMARY, tim_secondary: $SECONDARY, rcc: &mut Rcc) -> Self {
// Enable timers
<$PRIMARY>::enable(rcc);
<$SECONDARY>::enable(rcc);
// Reset timers
<$PRIMARY>::reset(rcc);
<$SECONDARY>::reset(rcc);
// Enable counter
tim_primary.cr1.modify(|_, w| w.cen().set_bit());
tim_secondary.cr1.modify(|_, w| w.cen().set_bit());
// In the MMS (Master Mode Selection) register, set the master mode so
// that a rising edge is output on the trigger output TRGO every time
// an update event is generated.
tim_primary.cr2.modify(|_, w| w.mms().variant(<$mms>::Update));
// In the SMCR (Slave Mode Control Register), select the
// appropriate internal trigger source (TS).
tim_secondary.smcr.modify(|_, w| w.ts().variant($ts));
// Set the SMS (Slave Mode Selection) register to "external clock mode 1",
// where the rising edges of the selected trigger (TRGI) clock the counter.
tim_secondary.smcr.modify(|_, w| w.sms().variant(<$sms>::ExtClockMode));
Self { tim_primary, tim_secondary }
}
/// Pause counting
fn pause(&mut self) {
self.tim_primary.cr1.modify(|_, w| w.cen().clear_bit());
self.tim_secondary.cr1.modify(|_, w| w.cen().clear_bit());
}
/// Resume counting
fn resume(&mut self) {
self.tim_secondary.cr1.modify(|_, w| w.cen().set_bit());
self.tim_primary.cr1.modify(|_, w| w.cen().set_bit());
}
}
impl LinkedTimer for LinkedTimerPair<$PRIMARY, $SECONDARY> {
/// Return the current 16 bit counter value of the primary timer (LSB).
fn get_counter_lsb(&self) -> u16 {
self.tim_primary.cnt.read().cnt().bits()
}
/// Return the current 16 bit counter value of the secondary timer (MSB).
fn get_counter_msb(&self) -> u16 {
self.tim_secondary.cnt.read().cnt().bits()
}
/// Return the current 32 bit counter value.
///
/// Note: Due to the potential for a race condition between
/// reading MSB and LSB, it's possible that the registers must
/// be re-read once. Therefore reading the counter value is not
/// constant time.
fn get_counter(&self) -> u32 {
loop {
let msb = self.tim_secondary.cnt.read().cnt().bits() as u32;
let lsb = self.tim_primary.cnt.read().cnt().bits() as u32;
// Because the timer is still running at high frequency
// between reading MSB and LSB, it's possible that LSB
// has already overflowed. Therefore we read MSB again
// to check that it hasn't changed.
let msb_again = self.tim_secondary.cnt.read().cnt().bits() as u32;
if msb == msb_again {
return (msb << 16) | lsb;
}
}
}
fn reset(&mut self) {
// Pause
self.pause();
// Reset counter
self.tim_primary.cnt.reset();
self.tim_secondary.cnt.reset();
// Continue
self.resume();
}
}
)+
}
}
timers! {
TIM2: (tim2, apb1_tim_clk, tim2::cr2::MMS_A),
TIM3: (tim3, apb1_tim_clk, tim2::cr2::MMS_A),
TIM6: (tim6, apb1_tim_clk, tim6::cr2::MMS_A),
TIM21: (tim21, apb2_tim_clk, tim21::cr2::MMS_A),
TIM22: (tim22, apb2_tim_clk, tim22::cr2::MMS_A),
}
linked_timers! {
// Internal trigger connection: RM0377 table 76
(TIM2, TIM3): (tim2_tim3, tim2::cr2::MMS_A, tim2::smcr::SMS_A, tim2::smcr::TS_A::Itr0),
// Internal trigger connection: RM0377 table 80
(TIM21, TIM22): (tim21_tim22, tim21::cr2::MMS_A, tim22::smcr::SMS_A, tim22::smcr::TS_A::Itr0),
// Note: Other combinations would be possible as well, e.g. (TIM21, TIM2) or (TIM2, TIM22).
// They can be implemented if needed.
}
| true
|
28604b98ec4b8fded7604b77a964425707ac0ec1
|
Rust
|
95th/ben
|
/examples/entry.rs
|
UTF-8
| 422
| 2.578125
| 3
|
[] |
no_license
|
use ben::decode::List;
use ben::{Encoder, Parser};
fn main() {
let mut v = vec![];
let mut list = v.add_list();
list.add(100);
list.add("hello");
let mut dict = list.add_dict();
dict.add("a", &b"b"[..]);
dict.add("x", "y");
dict.finish();
list.add(1);
list.finish();
let mut parser = Parser::new();
let n = parser.parse::<List>(&v).unwrap();
println!("{:#?}", n);
}
| true
|
dd346aac63f0a486307768fabb6545a6358c9e1b
|
Rust
|
minus3theta/contest
|
/atcoder/arc/068/e.rs
|
UTF-8
| 2,502
| 3.015625
| 3
|
[] |
no_license
|
#[allow(unused_imports)]
use std::io;
#[allow(unused_imports)]
use std::cmp;
#[allow(dead_code)]
fn getline() -> Vec<String> {
let mut s = String::new();
std::io::stdin().read_line(&mut s).ok().unwrap();
s.split(' ').map(|x| x.trim().to_string()).collect::<Vec<String>>()
}
#[allow(dead_code)]
fn get<T: std::str::FromStr>(s: &String) -> T {
s.parse().ok().unwrap()
}
struct Bit<T, F> {
n: usize,
dat: Vec<T>,
op: F,
unit: T,
}
impl<T: Clone, F: Fn(&mut T, &T)> Bit<T, F> {
#[allow(dead_code)]
fn new(n: usize, op: F, unit: T) -> Self {
Bit {
n: n,
dat: vec![unit.clone(); n + 1],
op: op,
unit: unit,
}
}
#[allow(dead_code)]
fn from_vec(mut v: Vec<T>, op: F, unit: T) -> Self {
let n = v.len();
let mut dat = vec![unit.clone()];
dat.append(&mut v);
for i in 1..n {
let j = i as i32;
let b = (j & -j) as usize;
let x = dat[i].clone();
op(&mut dat[i + b], &x);
}
Bit {
n: n,
dat: dat,
op: op,
unit: unit,
}
}
fn operate(&mut self, k: usize, a: &T) {
let mut k = k;
while k <= self.n {
(self.op)(&mut self.dat[k], &a);
let l = k as i32;
k += (l & -l) as usize;
}
}
fn accum(&self, k: usize) -> T {
let mut k = k;
let mut sum = self.unit.clone();
while k > 0 {
(self.op)(&mut sum, &self.dat[k]);
let l = k as i32;
k -= (l & -l) as usize;
}
sum
}
}
fn main() {
let nm = getline();
let n: i32 = get(&nm[0]);
let m: usize = get(&nm[1]);
let mut lrs: Vec<Vec<(i32,i32)>> = vec![vec![]; m + 1];
for _ in 0..n {
let lr = getline();
let l: i32 = get(&lr[0]);
let r: i32 = get(&lr[1]);
lrs[(r - l + 1) as usize].push((l, r + 1));
}
let mut total = 0;
let mut bit = Bit::new(m, |x, y| *x += *y, 0);
for d in 1..m+1 {
let mut ans = n;
ans -= total;
total += lrs[d].len() as i32;
for i in 1.. {
let x = i * d;
if x > m {
break;
}
ans += bit.accum(x);
}
for &(l, r) in &lrs[d] {
bit.operate(l as usize, &1);
bit.operate(r as usize, &-1);
}
println!("{}", ans);
}
}
| true
|
6442c248b2eca084b3de00447425ecda29eb622e
|
Rust
|
jtorrez/learning-rust
|
/slices/src/main.rs
|
UTF-8
| 801
| 4.09375
| 4
|
[] |
no_license
|
fn main() {
// create the variable my_string which is of String type
let my_string = String::from("hello world");
// API of first_word allows passing of all string slices
let word = first_word(&my_string[..]);
// variable of type &str, a string slice
let my_string_literal = "hello world";
// pass an explicit string slice of the string literal
let word = first_word(&my_string_literal[..]);
// type of string literals is implicitly &str, so this
// works too
let word = first_word(my_string_literal);
}
fn first_word(s: &str) -> &str {
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return &s[0..i];
}
}
&s[..] // returning here without explicit return keyword
}
| true
|
e9e625b3f892e1cb2f2d1f3c608b44c6135cca8b
|
Rust
|
ShirleyChung/rust
|
/hello2.rs
|
UTF-8
| 321
| 3.0625
| 3
|
[] |
no_license
|
mod hello2 {
fn is_true()->i32{ 100 }
pub fn select()->fn()->i32{
is_true
}
pub fn hello(x :i32)->i32 {
println!("{:} hello!", x);
32
}
}
fn main() {
let a:i32 = 10;
let b:i32 = a;
let c: &i32 = &b;
println!("let c = {:}", c);
hello2::hello(4);
println!("what is select? {}", hello2::select()());
}
| true
|
22489a3d97d97d873f469e2da270f5be2e8b2312
|
Rust
|
jamhall/pixie
|
/src/common/error.rs
|
UTF-8
| 1,163
| 3.171875
| 3
|
[] |
no_license
|
use std::error::Error;
use std::fmt;
#[derive(Debug)]
pub enum ApplicationError {
Configuration(String),
InvalidCommand(String),
Transport(String),
Display,
IoError(std::io::Error),
}
impl Error for ApplicationError {}
impl fmt::Display for ApplicationError {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
match self {
ApplicationError::Configuration(message) => write!(formatter, "{}", message),
ApplicationError::Display => write!(formatter, "Display error"),
ApplicationError::InvalidCommand(message) => write!(formatter, "Invalid command: {}", message),
ApplicationError::IoError(err) => {
writeln!(formatter, "IoError: {}", err)
}
ApplicationError::Transport(message) => write!(formatter, "{}", message)
}
}
}
impl From<clap::Error> for ApplicationError {
fn from(error: clap::Error) -> Self {
ApplicationError::Configuration(error.to_string())
}
}
impl From<std::io::Error> for ApplicationError {
fn from(err: std::io::Error) -> Self {
ApplicationError::IoError(err)
}
}
| true
|
77465dfbe3a33a8c270d9cf5f48ac1955fccc72b
|
Rust
|
Origen-SDK/o2
|
/rust/origen/src/core/model/registers/bit_collection.rs
|
UTF-8
| 30,019
| 2.6875
| 3
|
[
"MIT"
] |
permissive
|
use super::bit::Overlay as BitOverlay;
use super::{Bit, Field, Register};
use crate::core::model::registers::AccessType;
use crate::generator::PAT;
use crate::Transaction;
use crate::{Dut, Result, TEST};
use num_bigint::BigUint;
use regex::Regex;
use std::sync::MutexGuard;
const DONT_CARE_CHAR: &str = "X";
const OVERLAY_CHAR: &str = "V";
const STORE_CHAR: &str = "S";
const UNKNOWN_CHAR: &str = "?";
#[derive(Debug, Clone)]
pub struct BitCollection<'a> {
/// Optionally contains the ID of the reg that owns the bits
pub reg_id: Option<usize>,
/// Optionally contains the name of the field that owns the bits
pub field: Option<String>,
/// When true the BitCollection contains all bits of the register defined
/// by reg_id
pub whole_reg: bool,
/// When true the BitCollection contains all bits of the field defined
/// by field
pub whole_field: bool,
pub bits: Vec<&'a Bit>,
/// Iterator index and vars
pub i: usize,
pub shift_left: bool,
pub shift_logical: bool,
}
impl<'a> Default for BitCollection<'a> {
fn default() -> BitCollection<'a> {
BitCollection {
reg_id: None,
field: None,
whole_reg: false,
whole_field: false,
bits: Vec::new(),
i: 0,
shift_left: false,
shift_logical: false,
}
}
}
impl<'a> Iterator for BitCollection<'a> {
type Item = &'a Bit;
fn next(&mut self) -> Option<&'a Bit> {
if self.i < self.len() {
let bit;
if self.shift_left {
bit = self.bits[self.len() - self.i - 1];
} else {
bit = self.bits[self.i];
}
self.i += 1;
Some(bit)
} else {
None
}
}
}
impl<'a> BitCollection<'a> {
/// Creates a BitCollection from the given collection of bit IDs.
/// The resultant collection can not be associated back to a register or field.
/// Use the methods <reg>.bits() and <field>.bits() to create BitCollections with the necessary
/// metadata to associate with the parent object.
pub fn for_bit_ids(ids: &Vec<usize>, dut: &'a MutexGuard<'a, Dut>) -> BitCollection<'a> {
let mut bits: Vec<&Bit> = Vec::new();
for id in ids {
bits.push(dut.get_bit(*id).unwrap());
}
BitCollection {
reg_id: None,
field: None,
whole_reg: false,
whole_field: false,
bits: bits,
i: 0,
shift_left: false,
shift_logical: false,
}
}
/// Creates a BitCollection for the given register, normally this would not be called directly
/// and would instead be called via <reg>.bits()
pub fn for_register(reg: &Register, dut: &'a MutexGuard<'a, Dut>) -> BitCollection<'a> {
let mut bits: Vec<&Bit> = Vec::new();
for id in ®.bit_ids {
bits.push(dut.get_bit(*id).unwrap());
}
BitCollection {
reg_id: Some(reg.id),
field: None,
whole_reg: true,
whole_field: false,
bits: bits,
i: 0,
shift_left: false,
shift_logical: false,
}
}
/// Creates a BitCollection for the given register field, normally this would not be called directly
/// and would instead be called via <reg>.bits()
pub fn for_field(
ids: &Vec<usize>,
reg_id: usize,
name: &str,
dut: &'a MutexGuard<'a, Dut>,
) -> BitCollection<'a> {
let mut bits: Vec<&Bit> = Vec::new();
for id in ids {
bits.push(dut.get_bit(*id).unwrap());
}
BitCollection {
reg_id: Some(reg_id),
field: Some(name.to_string()),
whole_reg: false,
whole_field: true,
bits: bits,
i: 0,
shift_left: false,
shift_logical: false,
}
}
/// Sort the bits in the collection by their position property
pub fn sort_bits(&mut self) {
self.bits.sort_by_key(|bit| bit.position);
}
/// If the BitCollection contains > 1 bits, then this will return the lowest position
pub fn position(&self) -> usize {
self.bits[0].position
}
/// Returns the access attribute of the BitCollection. This will raise an error if
/// the collection is comprised of bits with a different access attribute value.
pub fn access(&self) -> Result<AccessType> {
let val = self.bits[0].access;
if !self.bits.iter().all(|&bit| bit.access == val) {
bail!("The bits in the collection have different access values",)
} else {
Ok(val)
}
}
pub fn set_data(&self, value: BigUint) {
let mut bytes = value.to_bytes_be();
let mut byte = bytes.pop().unwrap();
for (i, &bit) in self.bits.iter().enumerate() {
bit.set_data(byte >> i % 8);
if i % 8 == 7 {
match bytes.pop() {
Some(x) => byte = x,
None => byte = 0,
}
}
}
}
/// Returns the data value of the BitCollection. This will return an error if
/// any of the bits are undefined (X or Z).
pub fn data(&self) -> Result<BigUint> {
let mut bytes: Vec<u8> = Vec::new();
let mut byte: u8 = 0;
for (i, &bit) in self.bits.iter().enumerate() {
byte = byte | bit.data()? << i % 8;
if i % 8 == 7 {
bytes.push(byte);
byte = 0;
}
}
if self.bits.len() % 8 != 0 {
bytes.push(byte);
}
Ok(BigUint::from_bytes_le(&bytes))
}
/// Returns the overlay value of the BitCollection. This will return an error if
/// not all bits return the same value.
pub fn get_overlay(&self) -> Result<Option<BitOverlay>> {
let mut overlay: Option<BitOverlay> = None;
let mut first_overlay: usize = 0;
for (i, &bit) in self.bits.iter().enumerate() {
match bit.get_overlay() {
None => {}
Some(ref this_overlay) => match overlay {
None => {
overlay = Some(this_overlay.clone());
first_overlay = i;
}
Some(ref previous_overlay) => {
if this_overlay != previous_overlay {
bail!(
"The bits in the collection have different overlay values, found: '{}' at index {} and '{}' at index {}",
previous_overlay,
first_overlay,
this_overlay,
i
);
}
}
},
}
}
Ok(overlay)
}
/// Set the overlay value of the BitCollection.
pub fn set_overlay(
&self,
label: Option<String>,
symbol: Option<String>,
mask: Option<BigUint>,
persistent: bool,
) -> &BitCollection {
match mask {
Some(m) => {
let mut bytes = m.to_bytes_be();
let mut byte = bytes.pop().unwrap();
for (i, &bit) in self.bits.iter().enumerate() {
if (byte >> i % 8) & 1 == 1 {
bit.set_overlay(label.clone(), symbol.clone(), persistent);
}
if i % 8 == 7 {
match bytes.pop() {
Some(x) => byte = x,
None => byte = 0,
}
}
}
}
None => {
for &bit in self.bits.iter() {
bit.set_overlay(label.clone(), symbol.clone(), persistent);
}
}
}
self
}
pub fn clear_nonpersistent_overlay(&self) -> &BitCollection {
for &bit in self.bits.iter() {
bit.clear_nonpersistent_overlay();
}
self
}
pub fn clear_persistent_overlay(&self) -> &BitCollection {
for &bit in self.bits.iter() {
bit.clear_persistent_overlay();
}
self
}
/// Returns true if no contained bits are in X or Z state
pub fn has_known_value(&self) -> bool {
self.bits.iter().all(|bit| bit.has_known_value())
}
/// Returns a new BitCollection containing the subset of bits within the given range
pub fn range(&self, max: usize, min: usize) -> BitCollection<'a> {
let mut bits: Vec<&Bit> = Vec::new();
for i in min..max + 1 {
bits.push(self.bits[i]);
}
BitCollection {
reg_id: self.reg_id,
field: self.field.clone(),
whole_reg: self.whole_reg && bits.len() == self.bits.len(),
whole_field: self.whole_field && bits.len() == self.bits.len(),
bits: bits,
i: 0,
shift_left: false,
shift_logical: false,
}
}
/// Clears the verify flag on all bits in the collection
pub fn clear_verify_flag(&self) -> &BitCollection {
for &bit in self.bits.iter() {
bit.clear_verify_flag();
}
self
}
/// Returns true if any bits in the collection has their verify flag set
pub fn is_to_be_verified(&self) -> bool {
self.bits.iter().any(|bit| bit.is_to_be_verified())
}
/// Returns true if any bits in the collection has their capture flag set
pub fn is_to_be_captured(&self) -> bool {
self.bits.iter().any(|bit| bit.is_to_be_captured())
}
/// Returns true if any bits in the collection has an overlay set
pub fn has_overlay(&self) -> bool {
self.bits.iter().any(|bit| bit.has_overlay())
}
/// Returns true if any bits in the collection is writeable
pub fn is_writeable(&self) -> bool {
self.bits.iter().any(|bit| bit.is_writeable())
}
pub fn is_writable(&self) -> bool {
self.is_writeable()
}
/// Returns true if any bits in the collection is readable
pub fn is_readable(&self) -> bool {
self.bits.iter().any(|bit| bit.is_readable())
}
pub fn is_update_required(&self) -> bool {
self.bits.iter().any(|bit| bit.is_update_required())
}
/// Set the collection's device_state field to be the same as its current data state
pub fn update_device_state(&self) -> Result<&BitCollection> {
for &bit in self.bits.iter() {
bit.update_device_state()?;
}
Ok(self)
}
pub fn clear_flags(&self) -> &BitCollection {
for &bit in self.bits.iter() {
bit.clear_flags();
}
self
}
pub fn capture(&self) -> &BitCollection {
for &bit in self.bits.iter() {
bit.capture();
}
self
}
pub fn clear_capture(&self) -> &BitCollection {
for &bit in self.bits.iter() {
bit.clear_capture();
}
self
}
pub fn set_undefined(&self) -> &BitCollection {
for &bit in self.bits.iter() {
bit.set_undefined();
}
self
}
/// Resets the bits if the collection is for a whole bit field or register, otherwise
/// an error will be raised
pub fn reset(&self, name: &str, dut: &'a MutexGuard<'a, Dut>) -> Result<&'a BitCollection> {
if self.whole_reg || self.whole_field {
if self.whole_reg {
self.reg(dut)?.reset(name, dut);
} else {
self.field(dut)?.reset(name, dut);
}
Ok(self)
} else {
bail!(
"Reset cannot be called on an ad-hoc BitCollection, only on a Register or a named Bit Field"
)
}
}
/// Returns the data value of the given reset type. This will return None if
/// any of the bits in the collection do not have a value for the given reset type.
/// An error will be returned if the bits can't be resolved to a parent register.
pub fn reset_val(&self, name: &str, dut: &'a MutexGuard<'a, Dut>) -> Result<Option<BigUint>> {
let reg = self.reg(dut)?;
let mut bytes: Vec<u8> = Vec::new();
let mut byte: u8 = 0;
for (i, &bit) in self.bits.iter().enumerate() {
match reg.reset_val_for_bit(name, bit.position)? {
None => return Ok(None),
Some(x) => byte = byte | x << i % 8,
}
if i % 8 == 7 {
bytes.push(byte);
byte = 0;
}
}
if self.bits.len() % 8 != 0 {
bytes.push(byte);
}
Ok(Some(BigUint::from_bytes_le(&bytes)))
}
/// Returns true if the data value of any of the bits has been changed since
/// the last reset. It returns true even if the current data value matches the
/// default reset value and it will only be returned to false upon a reset operation.
pub fn is_modified_since_reset(&self) -> bool {
self.bits.iter().any(|bit| bit.is_modified_since_reset())
}
/// Returns true if the data value of all bits matches that of the given
/// reset type ("hard", by default).
/// If no data is defined for the given reset type then the result will be false.
pub fn is_in_reset_state(
&self,
name: Option<&str>,
dut: &'a MutexGuard<'a, Dut>,
) -> Result<bool> {
let reset_name = match name {
None => "hard",
Some(x) => x,
};
match self.reset_val(reset_name, dut)? {
None => Ok(false),
Some(x) => Ok(x == self.data()?),
}
}
/// Take a snapshot of the current state of all bits, the state can be rolled
/// back in future by supplying the same name to the rollback method
pub fn snapshot(&self, name: &str) -> Result<&BitCollection> {
for &bit in self.bits.iter() {
bit.snapshot(name);
}
Ok(self)
}
/// Returns true if the state of any bits has changed vs. the given snapshot
/// reference. An error will be raised if no snapshot with the given name is found.
pub fn is_changed(&self, name: &str) -> Result<bool> {
for &bit in self.bits.iter() {
if bit.is_changed(name)? {
return Ok(true);
};
}
Ok(false)
}
/// Rollback the state of all bits to the given snapshot.
/// An error will be raised if no snapshot with the given name is found.
pub fn rollback(&self, name: &str) -> Result<&BitCollection> {
for &bit in self.bits.iter() {
bit.rollback(name)?;
}
Ok(self)
}
/// Trigger a verify operation on the register
pub fn verify(
&self,
enable: Option<BigUint>,
preset: bool,
dut: &'a MutexGuard<Dut>,
) -> Result<Option<usize>> {
let trans = self.to_verify_transaction(enable, preset, dut);
if let Ok(t) = trans {
Ok(Some(TEST.push_and_open(node!(PAT::RegVerify, t))))
} else {
Ok(None)
}
}
pub fn to_verify_node(
&self,
enable: Option<BigUint>,
preset: bool,
dut: &'a MutexGuard<Dut>,
) -> Result<Option<origen_metal::ast::Node<PAT>>> {
let trans = self.to_verify_transaction(enable, preset, dut);
if let Ok(t) = trans {
Ok(Some(node!(PAT::RegVerify, t)))
} else {
Ok(None)
}
}
pub fn to_verify_transaction(
&self,
enable: Option<BigUint>,
preset: bool,
dut: &'a MutexGuard<Dut>,
) -> Result<Transaction> {
if !preset {
self.set_verify_flag(enable)?;
}
// Record the verify in the AST
if let Some(id) = self.reg_id {
let reg = self.reg(dut)?;
let bits = reg.bits(dut);
let mut t = Transaction::new_verify(bits.data()?, reg.size)?;
t.reg_id = Some(id);
t.address = Some(BigUint::from(reg.address(dut, None)?));
t.address_width = Some(reg.width(&dut)? as usize);
t.bit_enable = bits.verify_enables();
let captures = bits.capture_enables();
if captures != BigUint::from(0 as u8) {
t.set_capture_enables(Some(bits.capture_enables()))?;
}
bits.apply_overlay(&mut t)?;
Ok(t)
} else {
Err(error!(
"bit collection 'to_verify_transaction' is only supported for register-based bit collections"
))
}
}
/// Equivalent to calling verify() but without invoking a register transaction at the end,
/// i.e. it will set the verify flag on the bits and optionally apply an enable mask when
/// deciding what bit flags to set.
pub fn set_verify_flag(&self, enable: Option<BigUint>) -> Result<&BitCollection> {
if enable.is_some() {
let enable = enable.unwrap();
let mut bytes = enable.to_bytes_be();
let mut byte = bytes.pop().unwrap();
for (i, &bit) in self.bits.iter().enumerate() {
if (byte >> i % 8) & 1 == 1 {
bit.verify()?;
}
if i % 8 == 7 {
match bytes.pop() {
Some(x) => byte = x,
None => byte = 0,
}
}
}
} else {
for &bit in self.bits.iter() {
bit.verify()?;
}
}
Ok(self)
}
/// Trigger a write operation on the register
pub fn write(&self, dut: &'a MutexGuard<Dut>) -> Result<Option<usize>> {
let trans = self.to_write_transaction(dut);
if let Ok(t) = trans {
Ok(Some(TEST.push_and_open(node!(PAT::RegWrite, t))))
} else {
Ok(None)
}
}
pub fn to_write_node(
&self,
dut: &'a MutexGuard<Dut>,
) -> Result<Option<origen_metal::ast::Node<PAT>>> {
let trans = self.to_write_transaction(dut);
if let Ok(t) = trans {
Ok(Some(node!(PAT::RegWrite, t)))
} else {
Ok(None)
}
}
pub fn to_write_transaction(&self, dut: &'a MutexGuard<Dut>) -> Result<Transaction> {
// Record the write in the AST
if let Some(id) = self.reg_id {
let reg = self.reg(dut)?;
let bits = reg.bits(dut);
let mut t = Transaction::new_write(bits.data()?, reg.size)?;
t.reg_id = Some(id);
t.address = Some(BigUint::from(reg.address(dut, None)?));
t.address_width = Some(reg.width(&dut)? as usize);
t.bit_enable = Transaction::enable_of_width(reg.size)?;
bits.apply_overlay(&mut t)?;
Ok(t)
} else {
Err(error!(
"bit collection 'to_write_transaction' is only supported for register-based bit collections"
))
}
}
pub fn to_capture_transaction(&self, dut: &'a MutexGuard<Dut>) -> Result<Transaction> {
if let Some(id) = self.reg_id {
let reg = self.reg(dut)?;
let bits = reg.bits(dut);
let mut t = Transaction::new_capture(reg.size, Some(bits.capture_enables()))?;
t.reg_id = Some(id);
t.address = Some(BigUint::from(reg.address(dut, None)?));
t.address_width = Some(reg.width(&dut)? as usize);
bits.apply_overlay(&mut t)?;
Ok(t)
} else {
Err(error!(
"bit collection 'to_capture_transaction' is only supported for register-based bit collections"
))
}
}
/// Returns the Register object associated with the BitCollection. Note that this will
/// return the reg even if the BitCollection only contains a subset of the register's bits
pub fn reg(&self, dut: &'a MutexGuard<Dut>) -> Result<&'a Register> {
match self.reg_id {
Some(x) => dut.get_register(x),
None => {
bail!("Tried to reference the Register object from a BitCollection with no reg_id",)
}
}
}
/// Returns the bit Field object associated with the BitCollection. Note that this will
/// return the Field even if the BitCollection only contains a subset of the field's bits
pub fn field(&self, dut: &'a MutexGuard<Dut>) -> Result<&'a Field> {
match &self.field {
Some(x) => Ok(&self.reg(dut)?.fields[x]),
None => {
bail!("Tried to reference the Field object from a BitCollection with no field data",)
}
}
}
pub fn shift_left(&self, shift_in: u8) -> Result<u8> {
let mut v1 = shift_in & 0x1;
let mut v2: u8;
for &bit in self.bits.iter() {
v2 = bit.data()? & 0x1;
bit.set_data(v1);
v1 = v2;
}
Ok(v1)
}
pub fn shift_right(&self, shift_in: u8) -> Result<u8> {
let mut v1 = shift_in & 0x1;
let mut v2: u8;
for &bit in self.bits.iter().rev() {
v2 = bit.data()? & 0x1;
bit.set_data(v1);
v1 = v2;
}
Ok(v1)
}
pub fn shift_out_left(&self) -> BitCollection {
let mut bc = self.clone();
bc.i = 0;
bc.shift_left = true;
bc.shift_logical = false;
bc
}
pub fn shift_out_right(&self) -> BitCollection {
let mut bc = self.clone();
bc.i = 0;
bc.shift_left = false;
bc.shift_logical = false;
bc
}
pub fn len(&self) -> usize {
self.bits.len()
}
pub fn verify_enables(&self) -> BigUint {
let mut bytes: Vec<u8> = Vec::new();
let mut byte: u8 = 0;
for (i, &bit) in self.bits.iter().enumerate() {
byte = byte | bit.verify_enable_flag() << i % 8;
if i % 8 == 7 {
bytes.push(byte);
byte = 0;
}
}
if self.bits.len() % 8 != 0 {
bytes.push(byte);
}
BigUint::from_bytes_le(&bytes)
}
pub fn capture_enables(&self) -> BigUint {
let mut bytes: Vec<u8> = Vec::new();
let mut byte: u8 = 0;
for (i, &bit) in self.bits.iter().enumerate() {
byte = byte | bit.capture_enable_flag() << i % 8;
if i % 8 == 7 {
bytes.push(byte);
byte = 0;
}
}
if self.bits.len() % 8 != 0 {
bytes.push(byte);
}
BigUint::from_bytes_le(&bytes)
}
pub fn overlay_enables(&self) -> BigUint {
let mut bytes: Vec<u8> = Vec::new();
let mut byte: u8 = 0;
for (i, &bit) in self.bits.iter().enumerate() {
byte = byte | bit.overlay_enable_flag() << i % 8;
if i % 8 == 7 {
bytes.push(byte);
byte = 0;
}
}
if self.bits.len() % 8 != 0 {
bytes.push(byte);
}
BigUint::from_bytes_le(&bytes)
}
fn apply_overlay(&self, t: &mut Transaction) -> Result<()> {
let l = self.get_overlay()?;
let enables = self.overlay_enables();
let e;
if enables == BigUint::from(0 as u8) {
e = None;
} else {
e = Some(enables);
}
if l.is_some() || e.is_some() {
match l {
Some(ovl) => t.apply_overlay(ovl.label.clone(), ovl.symbol.clone(), e)?,
None => t.apply_overlay(None, None, e)?,
}
}
Ok(())
}
pub fn status_str(&mut self, operation: &str) -> Result<String> {
let mut ss = "".to_string();
if operation == "verify" || operation == "r" {
for bit in self.shift_out_left() {
if bit.is_to_be_captured() {
ss += STORE_CHAR;
} else if bit.is_to_be_verified() {
if bit.has_overlay() {
//&& options[:mark_overlays]
ss += OVERLAY_CHAR
} else {
if bit.has_known_value() {
if bit.data().unwrap() == 0 {
ss += "0";
} else {
ss += "1";
}
} else {
ss += UNKNOWN_CHAR;
}
}
} else {
ss += DONT_CARE_CHAR;
}
}
} else if operation == "write" || operation == "w" {
for bit in self.shift_out_left() {
if bit.has_overlay() {
//&& options[:mark_overlays]
ss += OVERLAY_CHAR;
} else {
if bit.has_known_value() {
if bit.data().unwrap() == 0 {
ss += "0";
} else {
ss += "1";
}
} else {
ss += UNKNOWN_CHAR;
}
}
}
} else {
bail!(
"Unknown operation argument '{}', must be \"verify\" or \"write\"",
operation
);
}
Ok(BitCollection::make_hex_like(
&ss,
(self.len() as f64 / 4.0).ceil() as usize,
))
}
// Converts a binary-like representation of a data value into a hex-like version.
// e.g. input => 010S0011SSSS0110 (where S, X or V represent store, don't care or overlay)
// output => [010s]3S6 (i.e. nibbles that are not all of the same type are expanded)
fn make_hex_like(regval: &str, size_in_nibbles: usize) -> String {
let mut outstr = "".to_string();
let mut re = "^(.?.?.?.)".to_string();
for _i in 0..size_in_nibbles - 1 {
re += "(....)";
}
re += "$";
let regex = Regex::new(&format!(r"{}", re)).unwrap();
let captures = regex.captures(regval).unwrap();
let mut nibbles: Vec<&str> = Vec::new();
for i in 0..size_in_nibbles {
// now grouped by nibble
nibbles.push(&captures[i + 1]);
}
let regex = Regex::new(&format!(
r"[{}{}{}{}]",
UNKNOWN_CHAR, DONT_CARE_CHAR, STORE_CHAR, OVERLAY_CHAR
))
.unwrap();
for nibble in nibbles {
// If contains any special chars...
if regex.is_match(nibble) {
let c1 = nibble.chars().next().unwrap();
// If all the same...
if nibble.chars().count() == 4 && nibble.chars().all(|c2| c1 == c2) {
outstr += &format!("{}", c1);
// Otherwise present this nibble in 'binary' format
} else {
outstr += &format!("[{}]", nibble.to_ascii_lowercase());
}
// Otherwise if all 1s and 0s...
} else {
let n: u32 = u32::from_str_radix(nibble, 2).unwrap();
outstr += &format!("{:X?}", n);
}
}
outstr
}
}
#[cfg(test)]
mod tests {
use crate::core::model::registers::{Bit, BitCollection};
use crate::{dut, Dut};
use num_bigint::ToBigUint;
use std::sync::MutexGuard;
fn make_bit_collection<'a>(size: usize, dut: &'a mut MutexGuard<Dut>) -> BitCollection<'a> {
let mut bit_ids: Vec<usize> = Vec::new();
for _i in 0..size {
bit_ids.push(dut.create_test_bit());
}
let mut bits: Vec<&Bit> = Vec::new();
for id in bit_ids {
bits.push(dut.get_bit(id).unwrap());
}
BitCollection {
reg_id: None,
field: None,
whole_reg: false,
whole_field: false,
bits: bits,
i: 0,
shift_left: false,
shift_logical: false,
}
}
#[test]
fn data_method_works() {
let mut dut = dut();
let bc = make_bit_collection(16, &mut dut);
assert_eq!(bc.data().unwrap(), 0.to_biguint().unwrap());
}
#[test]
fn set_data_method_works() {
let mut dut = dut();
let bc = make_bit_collection(16, &mut dut);
bc.set_data(0.to_biguint().unwrap());
assert_eq!(bc.data().unwrap(), 0.to_biguint().unwrap());
bc.set_data(0xFFFF.to_biguint().unwrap());
assert_eq!(bc.data().unwrap(), 0xFFFF.to_biguint().unwrap());
bc.set_data(0x1234.to_biguint().unwrap());
assert_eq!(bc.data().unwrap(), 0x1234.to_biguint().unwrap());
}
#[test]
fn range_method_works() {
let mut dut = dut();
let bc = make_bit_collection(16, &mut dut);
bc.set_data(0x1234.to_biguint().unwrap());
assert_eq!(bc.data().unwrap(), 0x1234.to_biguint().unwrap());
assert_eq!(bc.range(3, 0).data().unwrap(), 0x4.to_biguint().unwrap());
assert_eq!(bc.range(7, 4).data().unwrap(), 0x3.to_biguint().unwrap());
assert_eq!(bc.range(15, 8).data().unwrap(), 0x12.to_biguint().unwrap());
let bc = make_bit_collection(8, &mut dut);
bc.set_data(0x1F.to_biguint().unwrap());
assert_eq!(bc.range(4, 0).data().unwrap(), 0x1F.to_biguint().unwrap());
assert_eq!(bc.range(7, 4).data().unwrap(), 0x1.to_biguint().unwrap());
}
}
| true
|
5ae5f963ef0218091f1358e5750ae37ef3990779
|
Rust
|
18616378431/myCode
|
/rust/test6-5/src/main.rs
|
UTF-8
| 300
| 3.21875
| 3
|
[] |
no_license
|
//函数参数模式匹配
//ref修饰的函数参数为模式匹配的不可变引用,ref mut为可变引用
#[derive(Debug)]
struct S {
i : i32,
}
fn f(ref s : S) {
println!("{:p}", s);
}
fn main() {
let s = S {i : 42};
f(s);
// println!("{:?}", s);//s所有权发生转移
}
| true
|
14fa29cd63e627345ca28eb38442303f139b0195
|
Rust
|
GoXLR-on-Linux/goxlr-utility
|
/profile/src/components/preset_writer.rs
|
UTF-8
| 1,268
| 3.015625
| 3
|
[
"MIT",
"LicenseRef-scancode-other-permissive"
] |
permissive
|
use anyhow::Result;
use quick_xml::events::{BytesEnd, BytesStart, Event};
use quick_xml::Writer;
use std::collections::HashMap;
use std::io::Write;
pub struct PresetWriter {
name: String,
}
impl PresetWriter {
pub fn new(name: String) -> Self {
Self { name }
}
pub fn write_initial<W: Write>(&self, writer: &mut Writer<W>) -> Result<()> {
let formatted_name = self.name.replace(' ', "_");
let mut elem = BytesStart::new(formatted_name.as_str());
elem.push_attribute(("name", self.name.as_str()));
writer.write_event(Event::Start(elem))?;
Ok(())
}
pub fn write_tag<W: Write>(
&self,
writer: &mut Writer<W>,
name: &str,
attribute_map: HashMap<String, String>,
) -> Result<()> {
let mut elem = BytesStart::new(name);
for (key, value) in &attribute_map {
elem.push_attribute((key.as_str(), value.as_str()));
}
writer.write_event(Event::Empty(elem))?;
Ok(())
}
pub fn write_final<W: Write>(&self, writer: &mut Writer<W>) -> Result<()> {
let formatted_name = self.name.replace(' ', "_");
writer.write_event(Event::End(BytesEnd::new(formatted_name.as_str())))?;
Ok(())
}
}
| true
|
651113227413cf12655f5f69779ce7d452ac9810
|
Rust
|
jsnns/eyelang
|
/src/types/token.rs
|
UTF-8
| 2,124
| 3.453125
| 3
|
[] |
no_license
|
use crate::types::binary_operator::BinaryOperator;
#[derive(Clone, PartialEq)]
pub enum Token {
Symbol(String),
Type(String),
Str(String),
Number(i32),
Bool(bool),
Operator(BinaryOperator),
LParen,
RParen,
LBrace,
RBrace,
Comma,
Return,
Print,
If,
Else,
Do,
Times,
Throw,
Given,
Define,
Semicolon,
ToBe,
Run,
}
impl Token {
pub fn tuple(&self) -> (&Token, String) {
match self {
Token::Symbol(value) => (self, value.to_string()),
Token::Type(value) => (self, value.to_string()),
Token::Number(value) => (self, value.to_string()),
Token::Operator(value) => (self, value.to_string()),
Token::Bool(value) => (self, value.to_string()),
Token::Str(value) => (self, value.to_string()),
_ => (self, "".to_string()),
}
}
}
impl std::string::ToString for Token {
fn to_string(&self) -> String {
let str: &str = match self {
Token::Symbol(_) => "Symbol",
Token::Bool(_) => "Bool",
Token::Number(_) => "Number",
Token::Type(_) => "Type",
Token::Str(_) => "Str",
Token::Operator(..) => "Operator",
Token::Return => "Return",
Token::Comma => "Comma",
Token::LBrace => "{",
Token::RBrace => "}",
Token::LParen => "(",
Token::RParen => ")",
Token::Semicolon => ";",
Token::Print => "Print",
Token::If => "If",
Token::Else => "Else",
Token::Do => "Do",
Token::Throw => "Throw",
Token::Given => "Given",
Token::Define => "Define",
Token::ToBe => "ToBe",
Token::Run => "Run",
Token::Times => "Times",
};
str.to_string()
}
}
impl std::fmt::Debug for Token {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let value = self.tuple().1;
write!(f, "({}, {})", self.to_string(), value)
}
}
| true
|
2fd353bd1e3bd3091aa5f7605fc1a6c2815a9a2d
|
Rust
|
mdalbello/seqkit
|
/src/fasta_check.rs
|
UTF-8
| 1,641
| 3.1875
| 3
|
[
"MIT"
] |
permissive
|
use crate::common::{parse_args, FileReader};
use std::str;
use std::collections::VecDeque;
const USAGE: &str = "
Usage:
fasta check <fasta/fastq>
Description:
Checks that the input FASTA or FASTQ file is correctly formatted, and reports
the line number if any malformatted lines are found.
";
struct ReaderWithMemory {
file: FileReader,
lines_read: usize,
prev_lines: VecDeque<String>
}
impl ReaderWithMemory {
fn new(path: &str) -> ReaderWithMemory {
ReaderWithMemory {
file: FileReader::new(path),
prev_lines: VecDeque::new(),
lines_read: 0
}
}
fn read_line(&mut self, line: &mut String) -> bool {
if self.file.read_line(line) == false { return false; }
self.prev_lines.push_back(line.clone());
if self.prev_lines.len() > 10 {
self.prev_lines.pop_front();
}
self.lines_read += 1;
return true;
}
fn history(&self) -> String {
let mut history = String::new();
for line in &self.prev_lines {
history += &line; history += "\n";
}
history
}
}
pub fn main() {
let args = parse_args(USAGE);
let mut fasta = ReaderWithMemory::new(&args.get_str("<fasta/fastq>"));
let mut line = String::new();
while fasta.read_line(&mut line) {
if line.starts_with('>') {
fasta.read_line(&mut line);
} else if line.starts_with('@') {
fasta.read_line(&mut line);
fasta.read_line(&mut line);
if !line.starts_with('+') {
error!("Missing quality header prefix '+' on line {}:\n{}\n",
fasta.lines_read, fasta.history());
}
fasta.read_line(&mut line);
} else {
error!("Missing header prefix '>' or '@' on line {}:\n{}\n",
fasta.lines_read, fasta.history());
}
}
}
| true
|
6eb09b7bdf9c77d0e525bfb35a7c84652f3d3167
|
Rust
|
hsnavarro/retrogame-rust
|
/src/physics/physics_update.rs
|
UTF-8
| 5,871
| 2.90625
| 3
|
[
"MIT"
] |
permissive
|
use crate::algebra::Vec2f;
use crate::algebra::{closest_to_point_in_rect_border, is_point_inside_rect};
use crate::entities;
use crate::game_settings;
use std::vec::Vec;
fn detect_circle_rect_collision(circle_entity: &entities::CircleEntity,
rect_entity: &entities::RectEntity) -> Option<Vec2f> {
let circle_center = circle_entity.shape.center;
let circle_radius = circle_entity.shape.radius;
let closest_point = closest_to_point_in_rect_border(&rect_entity.shape, circle_center);
let is_center_inside_rect = is_point_inside_rect(&rect_entity.shape, circle_center);
let circle_center_penetration = (circle_center - closest_point).magnitude();
let mut collision_normal = (circle_center - closest_point).norm();
let mut circle_penetration = circle_radius - circle_center_penetration;
if is_center_inside_rect {
collision_normal *= -1.0;
circle_penetration = circle_radius + circle_radius;
}
if circle_penetration <= 0.0 { return None; }
Some(collision_normal * circle_penetration)
}
fn treat_circle_rect_collision(circle_entity: &mut entities::CircleEntity,
rect_entity:&entities::RectEntity) -> bool {
match detect_circle_rect_collision(circle_entity, rect_entity) {
Some(penetration_vector) => {
circle_entity.shape.move_shape(penetration_vector);
let collision_normal = penetration_vector.norm();
let old_direction = circle_entity.physics_properties.direction;
let perpendicular = old_direction.perpendicular(collision_normal);
let parallel = old_direction.projection(collision_normal);
let new_direction = perpendicular - parallel;
circle_entity.physics_properties.direction = new_direction;
true
}
None => false
}
}
enum ScreenCollisionType { HORIZONTAL, VERTICAL }
fn detect_screen_circle_collision(entity: &entities::CircleEntity) -> Option<ScreenCollisionType> {
let entity_center = &entity.shape.center;
let entity_radius = entity.shape.radius;
let width_limit = game_settings::SCREEN_WIDTH as f64 - entity_radius;
let height_limit = game_settings::SCREEN_HEIGHT as f64 - entity_radius;
if entity_center.x < entity_radius || entity_center.x > width_limit {
return Some(ScreenCollisionType::HORIZONTAL);
}
if entity_center.y < entity_radius || entity_center.y > height_limit {
return Some(ScreenCollisionType::VERTICAL);
}
None
}
fn treat_screen_circle_collision(entity: &mut entities::CircleEntity) {
let collision_detection = detect_screen_circle_collision(entity);
let entity_direction = &mut entity.physics_properties.direction;
match collision_detection {
Some(ScreenCollisionType::HORIZONTAL) => {
*entity_direction = Vec2f { x: -entity_direction.x, y: entity_direction.y };
},
Some(ScreenCollisionType::VERTICAL) => {
*entity_direction = Vec2f { x: entity_direction.x, y: -entity_direction.y };
},
None => {}
}
}
fn block_rect(entity: &mut entities::RectEntity) {
let width_limit = game_settings::SCREEN_WIDTH as f64 - entity.shape.width();
let height_limit = game_settings::SCREEN_HEIGHT as f64 - entity.shape.height();
let clamp = |x: &mut f64, min_value: f64, max_value: f64| {
if *x < min_value { *x = min_value; }
if *x > max_value { *x = max_value; }
};
let Vec2f { x: mut new_x, y: mut new_y } = entity.shape.position();
clamp(&mut new_x, 0.0, width_limit);
clamp(&mut new_y, 0.0, height_limit);
entity.shape.set_position(Vec2f { x: new_x, y: new_y });
}
fn delete_rect_entities(indexes_to_delete: &Vec<usize>,
rect_entities: &mut Vec<entities::RectEntity>) {
let num_of_deletions = indexes_to_delete.len();
if num_of_deletions == 0 { return; }
let num_of_rects = rect_entities.len();
assert!(num_of_deletions <= num_of_rects);
let mut last_index = num_of_rects - 1;
for i in indexes_to_delete.iter() {
rect_entities.swap(*i, last_index);
last_index -= 1;
}
rect_entities.truncate(num_of_rects - num_of_deletions);
}
fn update_simulation_frame(delta_time: f64,
rect_entities: &mut Vec<entities::RectEntity>,
circle_entities: &mut Vec<entities::CircleEntity>) {
for rect_entity in rect_entities.iter_mut() {
rect_entity.move_rect(delta_time);
block_rect(rect_entity);
}
for circle_entity in circle_entities.iter_mut() {
circle_entity.move_circle(delta_time);
treat_screen_circle_collision(circle_entity);
}
let mut indexes_to_delete = Vec::new();
for circle_entity in circle_entities.iter_mut() {
for (i, rect_entity) in rect_entities.iter_mut().enumerate() {
if treat_circle_rect_collision(circle_entity, rect_entity) && i != 0 {
indexes_to_delete.push(i);
}
}
}
delete_rect_entities(&indexes_to_delete, rect_entities);
}
pub fn update_game_frame(frame_time: f64,
rect_entities: &mut Vec<entities::RectEntity>,
circle_entities: &mut Vec<entities::CircleEntity>) {
let mut delta_time_left = frame_time;
let minimum = |x: f64, y: f64| if x < y { x } else { y };
while delta_time_left > 0.0 {
let delta_time = minimum(delta_time_left, game_settings::FIXED_DELTA_TIME);
update_simulation_frame(delta_time, rect_entities, circle_entities);
delta_time_left -= delta_time;
}
}
| true
|
5fa258b221f47a62297d6c7006c9a0c371651664
|
Rust
|
cscheid/loom
|
/src/hitable.rs
|
UTF-8
| 656
| 2.9375
| 3
|
[] |
no_license
|
use vector::Vec3;
use ray::Ray;
use material::Material;
use aabb::AABB;
pub struct HitRecord<'a> {
pub t: f64,
pub p: Vec3,
pub normal: Vec3,
pub material: &'a Material
}
impl<'a> HitRecord<'a> {
pub fn hit(t: f64, p: Vec3, normal: Vec3, material: &'a Material) -> HitRecord<'a> {
HitRecord {
t: t,
p: p,
normal: normal,
material: material
}
}
}
pub trait Hitable : Send + Sync {
fn hit<'a>(&'a self, r: &Ray, t_min: f64, t_max: f64) -> Option<HitRecord<'a>>;
fn bounding_box(&self) -> Option<AABB>;
fn importance_distribution(&self) -> Option<AABB>;
}
| true
|
4523d8a5d73d16a66c557ea0fe632e2f73270850
|
Rust
|
2teez/arraylist
|
/src/arl/tests.rs
|
UTF-8
| 3,202
| 3.34375
| 3
|
[
"MIT"
] |
permissive
|
use super::*;
#[test]
fn test_arraylist_new() {
let alist: ArrayList<u8> = ArrayList::new();
alist.push(2);
alist.push(4);
alist.push(6);
assert_eq!(
alist,
ArrayList {
vec: Rc::new(RefCell::new(vec![2, 4, 6])),
count: alist.count.clone()
}
);
}
#[test]
fn test_push_on_index() {
let al: ArrayList<&str> = ArrayList::new();
al.push("timo");
al.push("temi");
al.push_on_index(0, "John");
assert_eq!(
al,
ArrayList {
vec: Rc::new(RefCell::new(vec!["John", "timo", "temi"])),
count: al.count.clone()
}
);
}
#[test]
#[should_panic(expected = "Different values and counters")]
fn test_add_all() {
let initial_array = ArrayList::start_with(&[1.5, 3.34, 4.12]);
let others = vec![0.015, 9.34, 6.12, 99.45];
initial_array.add_all(&others);
assert_eq!(
initial_array,
ArrayList {
vec: Rc::new(RefCell::new(vec![1.1, 2.1, 4.2])),
count: Cell::new(ArrayListParams::new(3, 3, 3))
}
);
}
#[test]
fn test_clear() {
let al = ArrayList::start_with(&vec![1, 3, 5, 7]);
al.clear();
assert_eq!(
al,
ArrayList {
vec: Rc::new(RefCell::new(vec![])),
count: Cell::new(ArrayListParams::default())
}
);
}
#[test]
fn test_clone() {
let mut al = ArrayList::<String>::default();
al.add("lagos".to_string())
.add("ibadan".to_string())
.add("enugu".to_owned())
.add("abuja".to_owned())
.finish();
let copy = al.clone();
assert_eq!(copy, al);
}
#[test]
fn test_contains() {
let al = ArrayList::start_with(&['a', 'b', 'x', 'z']);
assert_eq!(al.contains(&'a'), true);
}
#[test]
fn test_pop() {
let mut al = ArrayList::default();
al.add(3).add(5).add(7).finish();
assert_eq!(al.pop(), Some(7))
}
#[test]
fn test_remove() {
let al = ArrayList::<u32>::new();
al.push(23);
al.push(25);
al.push(27);
al.remove(1);
assert_eq!(
al,
ArrayList {
vec: Rc::new(RefCell::new(vec![23, 27])),
count: al.count.clone()
}
);
}
#[test]
fn test_get_function() {
let al = ArrayList::start_with(&[2, 6, 9, 0, 1]);
assert_eq!(al.get(2), Some(9))
}
#[test]
#[should_panic(expected = "Out of bound index!")]
fn test_get_function_out_of_bound_index() {
let al = ArrayList::start_with(&[2, 6, 9, 0, 1]);
assert_eq!(al.get(6), Some(9))
}
#[test]
fn test_get_index_of() {
let al = ArrayList::start_with(&[2, 6, 9, 0, 1]);
assert_eq!(al.index_of(&0), Some(3));
}
#[test]
fn test_get_index() {
let al = arraylist!["Africa", "North America", "South America", "Asia", "Europe"];
assert_eq!(al.index_in(2), Some("South America"));
}
#[test]
fn test_add_all_at_start() {
let al = arraylist!["C", "cpp"];
al.add_all_at_start(&["rust", "asm"]);
assert_eq!(al.to_vec(), vec!["rust", "asm", "C", "cpp"]);
}
#[test]
fn test_add_all_any_location() {
let al = arraylist![1, 2, 3, 7, 8, 9];
al.add_all_at_index(3, &[4, 5, 6]);
assert_eq!(al.to_vec(), vec![1, 2, 3, 4, 5, 6, 7, 8, 9]);
}
| true
|
934bb971c8d9fb64497b31dc0a034532b58989fd
|
Rust
|
jpeterson1823/AdventOfCode
|
/2022/rust/day2/src/main.rs
|
UTF-8
| 2,498
| 3.296875
| 3
|
[] |
no_license
|
use std::fs;
static ROUND_WIN: i32 = 6i32;
static ROUND_DRAW: i32 = 3i32;
static ROUND_LOSS: i32 = 0i32;
static ROCK: i32 = 1i32;
static PAPER: i32 = 2i32;
static SCISSORS: i32 = 3i32;
fn main() {
// get playbook from input
let playbook = parse_input();
// play each round
let mut p1_total = 0;
for round in &playbook {
p1_total += part1_play_round(round);
}
let mut p2_total = 0;
for round in &playbook {
p2_total += part2_play_round(round);
}
println!("[Part1] {}", p1_total);
println!("[Part2] {}", p2_total);
}
fn parse_input() -> Vec<String> {
let input = fs::read_to_string("input.txt")
.expect("Failed to read input from file. Does 'input.txt' exist in root?");
input.split("\n").filter(|token| token.len() > 0).map(|s| String::from(s)).collect()
}
fn part1_play_round(round: &String) -> i32{
let opponent = round.chars().nth(0).unwrap();
let play = round.chars().nth(2).unwrap();
let converted_play = (play as u8 - 23u8) as char;
if opponent == converted_play {
match converted_play {
'A' => ROUND_DRAW + ROCK,
'B' => ROUND_DRAW + PAPER,
'C' => ROUND_DRAW + SCISSORS,
_ => unreachable!()
}
}
else {
match converted_play {
'A' => if opponent == 'B' {ROUND_LOSS+ROCK} else {ROUND_WIN+ROCK},
'B' => if opponent == 'C' {ROUND_LOSS+PAPER} else {ROUND_WIN+PAPER},
'C' => if opponent == 'A' {ROUND_LOSS+SCISSORS} else {ROUND_WIN+SCISSORS},
_ => unreachable!()
}
}
}
fn part2_play_round(round: &String) -> i32 {
let opponent = round.chars().nth(0).unwrap();
let play = round.chars().nth(2).unwrap();
match play {
'X' => {
if opponent == 'A' {ROUND_LOSS + SCISSORS}
else if opponent == 'B' {ROUND_LOSS + ROCK}
else if opponent == 'C' {ROUND_LOSS + PAPER}
else {unreachable!()}
},
'Y' => {
if opponent == 'A' {ROUND_DRAW + ROCK}
else if opponent == 'B' {ROUND_DRAW + PAPER}
else if opponent == 'C' {ROUND_DRAW + SCISSORS}
else {unreachable!()}
},
'Z' => {
if opponent == 'A' {ROUND_WIN + PAPER}
else if opponent == 'B' {ROUND_WIN + SCISSORS}
else if opponent == 'C' {ROUND_WIN + ROCK}
else {unreachable!()}
},
_ => unreachable!()
}
}
| true
|
af84e6c8b68154078d6fcbea23f98486c0f422ea
|
Rust
|
janispritzkau/rust-base-encode
|
/examples/base36.rs
|
UTF-8
| 343
| 2.8125
| 3
|
[] |
no_license
|
extern crate base_encode;
const CHARS: &[u8] = b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
fn main() {
let buf: Vec<u8> = (0..16).map(|_| rand::random()).collect();
let encoded = base_encode::to_string(&buf, 36, CHARS).unwrap();
assert_eq!(buf, base_encode::from_str(&encoded, 36, CHARS).unwrap());
println!("{}", encoded);
}
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.