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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
ad88d22f6be6acdcd8de1e99fa53375d197195ec
|
Rust
|
briangreenery/with-clean-env
|
/src/main.rs
|
UTF-8
| 3,446
| 2.96875
| 3
|
[
"Unlicense"
] |
permissive
|
extern crate winapi;
extern crate kernel32;
extern crate advapi32;
extern crate userenv;
use std::error::Error;
use std::ffi::OsString;
use std::io;
use std::io::Write;
use std::os::windows::ffi::OsStringExt;
use std::process::Command;
use kernel32::{CloseHandle, GetCurrentProcess};
use advapi32::OpenProcessToken;
use userenv::{CreateEnvironmentBlock, DestroyEnvironmentBlock};
unsafe fn next_null(wchars: *const u16, start: isize) -> isize {
let mut pos = start;
while *wchars.offset(pos) != 0 {
pos += 1;
}
pos
}
unsafe fn next_equals(wchars: *const u16, start: isize, end: isize) -> Option<isize> {
for i in start..end {
if *wchars.offset(i) == b'=' as u16 {
return Some(i);
}
}
None
}
unsafe fn to_os_str(wchars: *const u16, start: isize, end: isize) -> OsString {
let slice = std::slice::from_raw_parts(wchars.offset(start), (end - start) as usize);
OsString::from_wide(slice)
}
unsafe fn parse_environment(environment_block: *const winapi::c_void) -> Vec<(OsString, OsString)> {
let mut pairs = Vec::new();
let wchars = environment_block as *const u16;
let mut start = 0;
loop {
let end = next_null(wchars, start);
if let Some(equals) = next_equals(wchars, start, end) {
let name = to_os_str(wchars, start, equals);
let value = to_os_str(wchars, equals + 1, end);
pairs.push((name, value));
}
start = end + 1;
if *wchars.offset(start) == 0 {
break;
}
}
pairs
}
fn get_clean_env() -> Result<Vec<(OsString, OsString)>, io::Error> {
unsafe {
let mut token = std::ptr::null_mut();
if OpenProcessToken(GetCurrentProcess(), winapi::TOKEN_READ, &mut token) == 0 {
return Err(io::Error::last_os_error());
}
let mut environment_block = std::ptr::null_mut();
if CreateEnvironmentBlock(&mut environment_block, token, winapi::FALSE) == 0 {
CloseHandle(token);
return Err(io::Error::last_os_error());
}
let clean_env = parse_environment(environment_block);
DestroyEnvironmentBlock(environment_block);
CloseHandle(token);
Ok(clean_env)
}
}
fn print_usage() {
let text = "Usage: with-clean-env cmd [arg1 arg2 ...]
Summary:
Runs a command with a clean environment. In particular, the
command does not inherit the current process environment.
For example:
with-clean-env cmd /c echo hello";
writeln!(std::io::stderr(), "{}", text).unwrap();
}
fn die(msg: &str) -> ! {
writeln!(std::io::stderr(), "with-clean-env: {}", msg).unwrap();
std::process::exit(1);
}
fn main() {
let mut args = std::env::args_os();
if args.len() < 2 {
print_usage();
std::process::exit(2);
}
let mut command = Command::new(args.nth(1).unwrap());
for arg in args {
command.arg(arg);
}
let clean_env = match get_clean_env() {
Ok(pairs) => pairs,
Err(err) => die(err.description()),
};
for pair in &clean_env {
command.env(&pair.0, &pair.1);
}
match command.status() {
Ok(status) => {
if let Some(code) = status.code() {
std::process::exit(code);
}
die("could not read processs exit code");
}
Err(err) => die(err.description()),
}
}
| true
|
3db8605481b13b132bd983ab84707cfa179050ee
|
Rust
|
Merlotec/imperium
|
/src/input/mod.rs
|
UTF-8
| 4,299
| 3.296875
| 3
|
[] |
no_license
|
use crate::*;
#[derive(Copy, Clone)]
pub enum Trigger {
KeyTrigger(window::winit::VirtualKeyCode, window::winit::ElementState),
MouseButtonTrigger(window::winit::MouseButton, window::winit::ElementState),
}
#[derive(Copy, Clone)]
pub enum TriggerType {
Once,
Toggle,
}
#[derive(Clone)]
pub struct MovementState {
pub id: String,
pub trigger: Trigger,
pub trigger_type: TriggerType,
is_activated: bool,
is_triggered: bool,
}
impl MovementState {
pub fn new(id: String, trigger: Trigger, trigger_type: TriggerType) -> Self {
return Self { id, trigger, trigger_type, is_activated: false, is_triggered: false };
}
pub fn set_active(&mut self, b: bool) {
self.is_activated = b;
self.is_triggered = b;
}
pub fn tick(&mut self) {
if let TriggerType::Once = self.trigger_type {
if !self.is_activated {
self.is_triggered = false;
}
}
self.is_activated = false;
}
pub fn triggered(&self) -> bool {
return self.is_triggered;
}
}
pub struct MovementStateHandler {
pub states: Vec<MovementState>,
pub cursor_pos: Vector2f,
}
impl MovementStateHandler {
pub fn new() -> Self {
return Self { states: Vec::new(), cursor_pos: Vector2f::zero() };
}
pub fn add_state(&mut self, state: MovementState) {
self.states.push(state);
}
pub fn is_triggered(&self, id: String) -> Result<bool, &'static str> {
for state in self.states.iter() {
if state.id == id {
return Ok(state.triggered());
}
}
return Err("Failed to find state with the specified id.");
}
pub fn handle_events(&mut self, events: &Vec<window::Event>) {
for event in events.iter() {
if let window::winit::Event::WindowEvent { event, .. } = event {
match event {
window::winit::WindowEvent::KeyboardInput {
input:
window::winit::KeyboardInput {
virtual_keycode,
state,
..
},
..
} => {
for movement_state in self.states.iter_mut() {
if let Trigger::KeyTrigger(key_code, key_state) = movement_state.trigger {
if let Some(vkc) = virtual_keycode {
if *vkc == key_code {
if *state == key_state {
movement_state.set_active(true);
} else {
movement_state.set_active(false);
}
}
}
}
}
},
window::winit::WindowEvent::MouseInput {
state,
button,
..
} => {
for movement_state in self.states.iter_mut() {
if let Trigger::MouseButtonTrigger(mouse_button, mouse_state) = movement_state.trigger {
if *button == mouse_button {
if *state == mouse_state {
movement_state.set_active(true);
} else {
movement_state.set_active(false);
}
}
}
}
},
window::winit::WindowEvent::CursorMoved {
position,
..
} => {
self.cursor_pos = Vector2f::new(position.x as f32, position.y as f32);
},
_ => {}
}
}
}
for state in self.states.iter_mut() {
state.tick();
}
}
}
| true
|
734c22486a3b3fd618bac6ffe555b51b5eead3a9
|
Rust
|
randomPoison/gunship-rs
|
/src/old/resource/mod.rs
|
UTF-8
| 7,150
| 2.578125
| 3
|
[
"MIT"
] |
permissive
|
use component::{MeshManager, TransformManager};
use ecs::Entity;
use scene::Scene;
use std::cell::RefCell;
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
use std::rc::Rc;
use polygon::{GpuMesh};
use polygon::geometry::mesh::Mesh;
use polygon::material::*;
use wav::Wave;
pub mod async;
pub mod collada;
pub struct ResourceManager {
// renderer: Rc<Box<Renderer>>,
meshes: RefCell<HashMap<String, Mesh>>,
gpu_meshes: RefCell<HashMap<String, GpuMesh>>,
mesh_nodes: RefCell<HashMap<String, MeshNode>>,
_materials: RefCell<HashMap<String, Material>>,
audio_clips: RefCell<HashMap<String, Rc<Wave>>>,
resource_path: RefCell<PathBuf>,
}
impl ResourceManager {
pub fn new() -> ResourceManager {
ResourceManager {
// renderer: renderer,
meshes: RefCell::new(HashMap::new()),
gpu_meshes: RefCell::new(HashMap::new()),
mesh_nodes: RefCell::new(HashMap::new()),
_materials: RefCell::new(HashMap::new()),
audio_clips: RefCell::new(HashMap::new()),
resource_path: RefCell::new(PathBuf::new()),
}
}
pub fn load_resource_file<P: AsRef<Path>>(&self, path: P) -> Result<(), String> {
// let mut full_path = self.resource_path.borrow().clone();
// full_path.push(path);
// let metadata = match fs::metadata(&full_path) {
// Err(why) => return Err(format!(
// "Unable to read metadata for {}, either it doesn't exist or the user lacks permissions, {}",
// full_path.display(),
// &why)),
// Ok(metadata) => metadata,
// };
//
// if !metadata.is_file() {
// return Err(format!(
// "{} could not be loaded because it is not a file",
// full_path.display()));
// }
//
// collada::load_resources(full_path, self).unwrap(); // TODO: Don't panic?
//
// Ok(())
unimplemented!()
}
/// Sets the path to the resources directory.
///
/// # Details
///
/// The resource manager is configured to look in the specified directory when loading
/// resources such as meshes and materials.
pub fn set_resource_path<P: AsRef<Path>>(&self, path: P) {
let mut resource_path = self.resource_path.borrow_mut();
*resource_path = PathBuf::new();
resource_path.push(path);
}
pub fn get_gpu_mesh(&self, uri: &str) -> Option<GpuMesh> {
// Use cached mesh data if possible.
self.get_cached_mesh(uri)
.or_else(|| {
self.gen_gpu_mesh(uri)
})
}
pub fn get_audio_clip(&self, path_text: &str) -> Rc<Wave> {
let mut audio_clips = self.audio_clips.borrow_mut();
if !audio_clips.contains_key(path_text) {
let wave = Wave::from_file(path_text).unwrap();
audio_clips.insert(path_text.into(), Rc::new(wave));
}
audio_clips.get(path_text).unwrap().clone()
}
pub fn instantiate_model(&self, resource: &str, scene: &Scene) -> Result<Entity, String> {
if resource.contains(".") {
println!("WARNING: ResourceManager::instantiate_model() doesn't yet support fully qualified URIs, only root assets may be instantiated.");
unimplemented!();
}
let mesh_nodes = self.mesh_nodes.borrow();
let root = try!(
mesh_nodes
.get(resource)
.ok_or_else(|| format!("No mesh node is identified by the uri {}", resource)));
self.instantiate_node(scene, root)
}
fn instantiate_node(&self, scene: &Scene, node: &MeshNode) -> Result<Entity, String> {
let entity = scene.create_entity();
let transform = {
let transform_manager = unsafe { scene.get_manager_mut::<TransformManager>() }; // FIXME: No mutable borrows!
let transform = transform_manager.assign(entity);
for mesh_id in &node.mesh_ids {
let gpu_mesh = match self.get_gpu_mesh(&*mesh_id) {
Some(gpu_mesh) => gpu_mesh,
None => {
println!("WARNING: Unable to load gpu mesh for uri {}", mesh_id);
continue;
}
};
let mesh_manager = unsafe { scene.get_manager_mut::<MeshManager>() }; // FIXME: No mutable borrows!
mesh_manager.give_mesh(entity, gpu_mesh);
}
transform
};
// TODO: Apply the node's transform to the entity transform.
// Instantiate each of the children and set the current node as their parent.
for node in &node.children {
let child = try!(self.instantiate_node(scene, node));
transform.add_child(child);
}
Ok(entity)
}
pub fn get_material<P: AsRef<Path>>(
&self,
_path: P
) -> Result<&Material, MaterialError> {
unimplemented!();
}
pub fn add_mesh<U: Into<String> + AsRef<str>>(&self, uri: U, mesh: Mesh) {
let mut meshes = self.meshes.borrow_mut();
if meshes.contains_key(uri.as_ref()) {
println!("WARNING: There is already a mesh node with uri {}, it will be overriden in the resource manager by the new node", uri.as_ref());
}
meshes.insert(uri.into(), mesh);
}
pub fn add_mesh_node(&self, uri: String, node: MeshNode) {
let mut nodes = self.mesh_nodes.borrow_mut();
if nodes.contains_key(&uri) {
println!("WARNING: There is already a mesh node with uri {}, it will be overriden in the resource manager by the new node", uri);
}
nodes.insert(uri.clone(), node);
}
fn has_cached_mesh(&self, uri: &str) -> bool {
self.gpu_meshes.borrow().contains_key(uri)
}
fn get_cached_mesh(&self, uri: &str) -> Option<GpuMesh> {
self.gpu_meshes
.borrow()
.get(uri)
.map(|mesh| *mesh)
}
fn gen_gpu_mesh(&self, uri: &str) -> Option<GpuMesh> {
// TODO: Don't do this check in release builds.
if self.has_cached_mesh(uri) {
println!("WARNING: Attempting to create a new mesh for {} when the uri is already in the meshes map", uri);
}
// let meshes = self.meshes.borrow();
// let mesh = match meshes.get(uri) {
// Some(mesh) => mesh,
// None => return None,
// };
//
// let gpu_mesh = self.renderer.register_mesh(&mesh);
// self.gpu_meshes
// .borrow_mut()
// .insert(uri.into(), gpu_mesh);
//
// Some(gpu_mesh)
unimplemented!();
}
}
// TODO: Also include the node's local transform.
#[derive(Debug, Clone)]
pub struct MeshNode {
pub mesh_ids: Vec<String>,
pub children: Vec<MeshNode>,
}
impl MeshNode {
pub fn new() -> MeshNode {
MeshNode {
mesh_ids: Vec::new(),
children: Vec::new(),
}
}
}
#[derive(Debug)]
pub struct MaterialError;
| true
|
61a8873a3f5e2685101e8877ef26ef989b8e89cc
|
Rust
|
mkpankov/jwt-prototype
|
/src/main.rs
|
UTF-8
| 3,811
| 2.71875
| 3
|
[] |
no_license
|
use biscuit::jwa::{
ContentEncryptionAlgorithm, EncryptionOptions, KeyManagementAlgorithm, SignatureAlgorithm,
};
use biscuit::jwe;
use biscuit::jwk::JWK;
use biscuit::jws::{self, Secret};
use biscuit::{ClaimsSet, Empty, RegisteredClaims, SingleOrMultiple, JWE, JWT};
use serde::{Deserialize, Serialize};
use std::str::FromStr;
// Define our own private claims
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
struct PrivateClaims {
company: String,
department: String,
}
fn main() {
#[allow(unused_assignments)]
// Craft our JWS
let expected_claims = ClaimsSet::<PrivateClaims> {
registered: RegisteredClaims {
issuer: Some(FromStr::from_str("https://www.acme.com").unwrap()),
subject: Some(FromStr::from_str("John Doe").unwrap()),
audience: Some(SingleOrMultiple::Single(
FromStr::from_str("htts://acme-customer.com").unwrap(),
)),
not_before: Some(1234.into()),
..Default::default()
},
private: PrivateClaims {
department: "Toilet Cleaning".to_string(),
company: "ACME".to_string(),
},
};
let expected_jwt = JWT::new_decoded(
From::from(jws::RegisteredHeader {
algorithm: SignatureAlgorithm::HS256,
..Default::default()
}),
expected_claims.clone(),
);
let signing_secret = Secret::Bytes("secret".to_string().into_bytes());
let jws = expected_jwt.into_encoded(&signing_secret).unwrap();
// Encrypt the token
// You would usually have your own AES key for this, but we will use a zeroed key as an example
let key: JWK<Empty> = JWK::new_octet_key(&vec![0; 256 / 8], Default::default());
// We need to create an `EncryptionOptions` with a nonce for AES GCM encryption.
// You must take care NOT to reuse the nonce. You can simply treat the nonce as a 96 bit
// counter that is incremented after every use
let mut nonce_counter = num::BigUint::from_bytes_le(&vec![0; 96 / 8]);
// Make sure it's no more than 96 bits!
assert!(nonce_counter.bits() <= 96);
let mut nonce_bytes = nonce_counter.to_bytes_le();
// We need to ensure it is exactly 96 bits
nonce_bytes.resize(96 / 8, 0);
let options = EncryptionOptions::AES_GCM { nonce: nonce_bytes };
// Construct the JWE
let jwe = JWE::new_decrypted(
From::from(jwe::RegisteredHeader {
cek_algorithm: KeyManagementAlgorithm::A256GCMKW,
enc_algorithm: ContentEncryptionAlgorithm::A256GCM,
media_type: Some("JOSE".to_string()),
content_type: Some("JOSE".to_string()),
..Default::default()
}),
jws.clone(),
);
// Encrypt
let encrypted_jwe = jwe.encrypt(&key, &options).unwrap();
let token = encrypted_jwe.unwrap_encrypted().to_string();
// Now, send `token` to your clients
println!("Token: {}", token);
// ... some time later, we get token back!
let token: JWE<PrivateClaims, Empty, Empty> = JWE::new_encrypted(&token);
// Decrypt
let decrypted_jwe = token
.into_decrypted(
&key,
KeyManagementAlgorithm::A256GCMKW,
ContentEncryptionAlgorithm::A256GCM,
)
.unwrap();
let decrypted_jws = decrypted_jwe.payload().unwrap();
assert_eq!(jws, *decrypted_jws);
println!("Decrypted JWS: {:?}", decrypted_jws);
let jws = decrypted_jws
.decode(&signing_secret, SignatureAlgorithm::HS256)
.unwrap();
assert_eq!(*jws.payload().unwrap(), expected_claims);
jws.validate(Default::default()).unwrap();
println!("Claims: {:?}", *jws.payload().unwrap());
// Don't forget to increment the nonce!
nonce_counter = nonce_counter + 1u8;
}
| true
|
f3fa1f166ea981ec5e61b1128b35483dc61a70e4
|
Rust
|
Bugin10/rust_ray_tracer_book_2
|
/.history/src/ray_20210814191722.rs
|
UTF-8
| 332
| 2.984375
| 3
|
[] |
no_license
|
use ultraviolet::*;
#[derive(Clone, Copy, Debug)]
pub struct Ray {
pub origin: Vec3x8,
pub direction: Vec3x8
}
impl Ray {
pub fn new(origin: Vec3x8, direction: Vec3x8) -> Ray {
Ray { origin, direction }
}
pub fn at_parameter(&self, t: f32) -> Vec3x8 {
self.origin + t * self.direction
}
}
| true
|
caac03a6ee2d0f89d89a3d7d84c515e5d2c5f7c4
|
Rust
|
Zoomulator/rust-sorted
|
/tests/usage.rs
|
UTF-8
| 6,853
| 3.5625
| 4
|
[
"MIT"
] |
permissive
|
#[macro_use]
extern crate sorted;
use sorted::*;
order_by_key! { Key0AscOrder:
fn (K: Ord + Copy, T)(entry: (K,T)) -> K { entry.0 }
}
order_by_key! { KeySecondOrder:
fn (K: Ord + Copy, T)(entry: (T,K)) -> K { entry.1 }
}
#[test]
fn sorted_array() {
let arr = [7, 2, 9, 6];
// Sort the array, resulting in a Sorted<[T;n], AscendingOrder>.
let v = AscendingOrder::by_sorting(arr);
// Retrieve a reference to the inner type with .as_inner.
assert_eq!(v.as_inner(), &[2, 6, 7, 9]);
}
#[test]
fn ascending_order() {
let arr = AscendingOrder::by_sorting([3, 4, 1, 2]);
assert_eq!(arr.as_inner(), &[1, 2, 3, 4]);
}
#[test]
fn descending_order() {
let arr = DescendingOrder::by_sorting([1, 3, 4, 2]);
assert_eq!(arr.as_inner(), &[4, 3, 2, 1]);
}
#[test]
fn sorted_slice() {
// You can also refer to a slice that should be sorted.
// This leaves the ownership outside of the Sorted<> type.
let mut arr = [3, 2, 4, 1];
let s = AscendingOrder::by_sorting(&mut arr[..]);
assert_eq!(s.as_inner(), &[1, 2, 3, 4]);
}
#[test]
fn sorted_vec() {
let v = AscendingOrder::by_sorting(vec![4, 3, 1, 2]);
assert_eq!(v.as_slice(), &[1, 2, 3, 4]);
}
#[test]
fn sort_by_first() {
// It's easy to sort by a tuple key. Specifiy which key and in what order
// it should be sorted.
let s = vec![(5, 3), (2, 7), (3, 4)];
let v = KeyOrder::<keys::Key0, AscendingOrder>::by_sorting(s);
assert_eq!(&[(2, 7), (3, 4), (5, 3)], v.as_slice());
}
#[test]
fn sort_by_third() {
let s = vec![(5, 3, 9), (2, 7, 2), (3, 4, 4)];
let v = KeyOrder::<keys::Key2, DescendingOrder>::by_sorting(s);
assert_eq!(&[(5, 3, 9), (3, 4, 4), (2, 7, 2)], v.as_slice());
}
#[test]
fn sort_with_property_key_type() {
#[derive(Debug, Clone, Copy, PartialEq)]
struct Record {
stuff: i32,
id: u32,
};
impl Record {
pub fn new(n: u32) -> Self {
Record { stuff: 0, id: n }
}
}
// Sorting via an arbitrary property takes a bit more work.
// First define a tag type to identify what property we want to sort by.
#[derive(Debug, Clone, Copy)]
struct IdKey;
// Then implement how to get that key from our Record type.
impl Key<Record> for IdKey {
type Key = u32;
fn key(r: &Record) -> Self::Key {
r.id
}
}
// You can now sort the Records by a property in any order.
let v = KeyOrder::<IdKey, AscendingOrder>::by_sorting(vec![
Record::new(2),
Record::new(3),
Record::new(1),
]);
assert_eq!(
&v.as_slice(),
&[Record::new(1), Record::new(2), Record::new(3)]
);
}
#[test]
fn sort_by_property_string() {
use std::cmp::Ordering;
// Using strings as keys has some lifetime issues with the previous key
// pattern. It's however possible, just not as flexible.
#[derive(Debug, Clone, PartialEq)]
struct Person {
name: String,
x: i32,
};
impl Person {
pub fn new(n: &str) -> Self {
Self {
name: n.to_string(),
x: 0,
}
}
}
// We'll implement our own SortOrder type. Starting with a tag type.
#[derive(Debug, Clone, Copy)]
struct OrderByName;
// Then implement the SortOrder trait, per struct supporting it.
impl SortOrder<Person> for OrderByName {
fn cmp(a: &Person, b: &Person) -> Ordering {
a.name.cmp(&b.name)
}
}
// It will only provide one ordering for what you define, so if you need to
// support multiple ways of ordering by name it will result in a bit of
// boilerplate.
let v = OrderByName::by_sorting(vec![
Person::new("Bob"),
Person::new("Cecil"),
Person::new("Alice"),
]);
assert_eq!(
v.as_slice(),
&[
Person::new("Alice"),
Person::new("Bob"),
Person::new("Cecil")
]
);
}
#[test]
fn sorted_slice_from_sorted_vec() {
// The as_ref works like Option::as_ref; it returns a Sorted type with the
// inner type being a reference to the original. If the inner type implements
// the correct AsRef, it'll work.
fn take_sorted_slice<'a>(slice: Sorted<&'a [i32], AscendingOrder>) {
assert_eq!(&[1, 2, 4, 9, 33][..], *slice);
}
let vec = AscendingOrder::by_sorting(vec![4, 9, 2, 33, 1]);
take_sorted_slice(vec.as_ref());
}
#[test]
fn sorted_vec_ref() {
fn take_sorted_vec<'a>(refvec: Sorted<&'a Vec<i32>, AscendingOrder>) {
assert_eq!(&[1, 2, 3, 4], refvec.as_slice())
}
let vec = AscendingOrder::by_sorting(vec![3, 2, 4, 1]);
take_sorted_vec(vec.as_ref());
}
#[test]
#[cfg(feature = "unstable")]
fn sorted_vec_from_sorted_slice() {
type SortedVec<T, O> = Sorted<Vec<T>, O>;
let mut arr = [5, 3, 7, 9];
let slice = AscendingOrder::by_sorting(&mut arr[..]);
// This is currently unstable as it doesn't seem possible to guarantee sortedness.
let vec = SortedVec::from(slice);
assert_eq!([3, 5, 7, 9], vec.as_slice());
}
#[test]
fn take_sorted_iterator() {
// Sorted types can generate SortedIterators.
fn take_sorted<I>(sorted: I)
where
I: IntoIterator<Item = i32>,
I::IntoIter: SortedIterator<Ordering = AscendingOrder>,
{
let v: Vec<_> = sorted.into_iter().collect();
assert_eq!(vec![2, 3, 8, 10], v);
}
let vec = AscendingOrder::by_sorting(vec![3, 8, 2, 10]);
take_sorted(vec);
}
#[test]
fn take_sorted_ref_iterator() {
// By-ref iterators can only be created via Sorted::iter() right now.
// I.e there is no IntoIterator for &Sorted<>.
fn take_sorted_ref<'a, I>(sorted: I)
where
I: IntoIterator<Item = &'a i32>,
I::IntoIter: SortedIterator,
{
let v: Vec<_> = sorted.into_iter().cloned().collect();
assert_eq!([1, 2, 3, 4], v.as_slice());
}
let vec = AscendingOrder::by_sorting(vec![3, 4, 1, 2]);
take_sorted_ref(vec.iter());
}
#[test]
fn sorted_insert() {
// The Sorted type only provides mutable operations that keep the collection
// sorted.
let mut vec = AscendingOrder::by_sorting(vec![4, 8, 2, 0]);
vec.insert(6);
assert_eq!([0, 2, 4, 6, 8], vec.as_slice());
}
#[test]
fn sorted_vec_from_sorted_iterator() {
// You can create Sorted collections from Sorted iterators.
type SortedVec<T, O> = Sorted<Vec<T>, O>;
let v0 = AscendingOrder::by_sorting(vec![3, 1, 4, 2]);
let it = v0.into_iter();
let v1 = SortedVec::from_iter(it);
assert_eq!(&[1, 2, 3, 4], v1.as_slice());
}
#[test]
fn building_from_empty_vec() {
let mut v: Sorted<Vec<i32>, AscendingOrder> = Default::default();
v.insert(3);
v.insert(1);
v.insert(2);
assert_eq!(&[1, 2, 3], v.as_slice());
}
| true
|
b2702f68e56d537f7a0fe6fedb3dd6b086bd2d45
|
Rust
|
zaksky7/Rust-project
|
/src/year2016/day22.rs
|
UTF-8
| 2,077
| 2.78125
| 3
|
[] |
no_license
|
use ahash::AHashMap;
use regex::Regex;
use std::cmp::max;
use crate::utils::*;
#[derive(Clone)]
struct Node {
coord: Coord<i32>,
used: i64,
avail: i64,
}
fn parse_nodes(input: &str) -> Vec<Node> {
let re =
Regex::new(r"/dev/grid/node-x(\d+)-y(\d+)\s+(\d+)T\s+(\d+)T\s+(\d+)T\s+(\d+)%").unwrap();
input
.lines()
.skip(2)
.map(|line| {
let cap = re.captures(line).unwrap();
Node {
coord: Coord::new(cap[1].parse().unwrap(), cap[2].parse().unwrap()),
used: cap[4].parse().unwrap(),
avail: cap[5].parse().unwrap(),
}
})
.collect()
}
pub fn part1(input: &str) -> usize {
let nodes = parse_nodes(input);
(0..nodes.len())
.map(|i| {
(i + 1..nodes.len())
.filter(|&j| {
nodes[i].used > 0 && nodes[i].used < nodes[j].avail
|| nodes[j].used > 0 && nodes[j].used < nodes[i].avail
})
.count()
})
.sum()
}
fn neighbors(
grid: &AHashMap<Coord<i32>, Node>,
st: &(Coord<i32>, Coord<i32>),
) -> Vec<(Coord<i32>, Coord<i32>)> {
vec![
Coord::new(0, 1),
Coord::new(0, -1),
Coord::new(1, 0),
Coord::new(-1, 0),
]
.into_iter()
.filter_map(move |d| {
let o2 = st.0 + d;
(grid.contains_key(&o2) && grid[&o2].used <= 100)
.then(|| (o2, if o2 == st.1 { st.0 } else { st.1 }))
})
.collect()
}
pub fn part2(input: &str) -> Option<usize> {
let nodes = parse_nodes(input);
let mut grid = AHashMap::new();
let mut opn = Coord::new(0, 0);
let mut mx = Coord::new(0, 0);
for node in nodes {
grid.insert(node.coord, node.clone());
if node.used == 0 {
opn = node.coord;
}
mx = max(mx, node.coord);
}
let mut x = bfs((opn, Coord::new(mx.x, 0)), |st| neighbors(&grid, st))
.filter_map(|(d, v)| (v.1 == Coord::new(0, 0)).then(|| d));
x.next()
}
| true
|
29dd1c7057ff3e07d1967bb70577ee0281d462e1
|
Rust
|
blitzmann/euler-rust
|
/src/p005.rs
|
UTF-8
| 2,373
| 3.921875
| 4
|
[] |
no_license
|
pub fn solve(max: u64) -> u64 {
improved_version(max)
}
pub fn improved_version(max: u64) -> u64 {
let mut multiple: u64 = 1;
let mut number: u64 = multiple;
let mut min: u64 = 1;
'main: loop {
// our main loop. This will check each number from 1 to x to see if it's divisible by 1..=max
let mut break_for = false;
'inner: for x in min..=max {
// check each int from 1..=max to see if it can evenly divide our number
if number % x != 0 {
// if this number cannot be evenly divided, stop looking
break_for = true;
break 'inner;
} else {
multiple = number;
min = x + 1;
}
}
if !break_for {
break 'main;
}
number += multiple;
}
number
}
// Original iteration based on my previous solve in Python:
// https://github.com/blitzmann/euler/blob/master/problem5.py
pub fn original_iteration(max: u64) -> u64 {
/*
There's a trick to this one. We already know that 2520 is the lowest number
evenly divided by 1-10. We use this fact for two purposes:
- Since our result must be evenly divided by 1-10 (and 11-20), the result must
be a multiple of 2520 (otherwise it would not satisfy 1-10 condition).
- Since our tests are multiples of 2520, we do not need to test 1-10 as they are
inherently valid
Both of these facts greatly speed up the process when compared to brute-forcing
it.
*/
let mut multiple = 2520;
let mut i = multiple;
'main: loop {
let mut break_for = false;
'inner: for x in 10..=max {
if i % x != 0 {
break_for = true;
break 'inner;
}
}
if !break_for {
break 'main;
}
i += multiple;
}
i
}
#[cfg(test)]
mod tests {
extern crate test;
#[test]
fn euler_test() {
assert_eq!(super::solve(10), 2520);
}
#[test]
fn answer_test() {
assert_eq!(super::solve(20), 232_792_560);
}
#[bench]
fn bench(b: &mut test::Bencher) {
b.iter(|| super::solve(20));
}
#[bench]
fn bench_original(b: &mut test::Bencher) {
b.iter(|| super::original_iteration(20));
}
}
| true
|
fc1f50100edac9dae5c2b5ea5e9c2478bbc01179
|
Rust
|
yinshuwei/trying
|
/rust/hello_cargo/src/demo/box_demo.rs
|
UTF-8
| 833
| 3.4375
| 3
|
[] |
no_license
|
enum List {
Cons(i32, Box<List>),
Nil,
}
impl List {
fn print(&self) {
if let List::Cons(i, c) = self {
println!("{}", i);
c.print();
}
}
}
struct MyList<'a> {
list: &'a List,
}
impl MyList<'_> {
fn new<'a>(list: &'a List) -> MyList<'a> {
MyList {
list: list,
}
}
}
impl Iterator for MyList<'_> {
type Item = i32;
fn next(&mut self) -> Option<Self::Item> {
if let List::Cons(i, c) = self.list {
self.list = c;
return Some(*i);
}
return None;
}
}
pub fn run() {
let list = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
list.print();
println!();
let my = MyList::new(&list);
for i in my.into_iter() {
println!("{}", i);
}
}
| true
|
a88022d65d82c476443207c518dd33b69fa90f18
|
Rust
|
cameronfyfe/ripple
|
/src/util.rs
|
UTF-8
| 551
| 2.765625
| 3
|
[] |
no_license
|
pub fn u16_from_bytes(b: [u8; 2]) -> u16 {
((b[1] as u16) << 8) +
((b[0] as u16) << 0)
}
pub fn u16_from_u8_slice(b: &[u8]) -> u16 {
u16_from_bytes([b[0], b[1]])
}
pub fn u32_from_bytes(b0: u8, b1: u8, b2: u8, b3: u8) -> u32 {
((b3 as u32) << 24) +
((b2 as u32) << 16) +
((b1 as u32) << 8) +
((b0 as u32) << 0)
}
pub fn u32_from_chars(c: [char; 4]) -> u32 {
u32_from_bytes(c[0] as u8, c[1] as u8, c[2] as u8, c[3] as u8)
}
pub fn u32_from_u8_slice(b: &[u8]) -> u32 {
u32_from_bytes(b[0], b[1], b[2], b[3])
}
| true
|
9dfd36d1a47e5ca0574521d52f9fdc08178fb0c3
|
Rust
|
eduardonunesp/river-jet-rs
|
/src/scene.rs
|
UTF-8
| 3,087
| 3.34375
| 3
|
[] |
no_license
|
use ggez;
/// Based on ggez goodies scene manager
/// A command to change to a new scene, either by pushing a new one,
/// popping one or replacing the current scene (pop and then push).
#[allow(dead_code)]
pub enum SceneSwitch<Ev> {
None,
Push(Box<dyn Scene<Ev>>),
Replace(Box<dyn Scene<Ev>>),
Pop,
}
pub trait Scene<Ev> {
fn update(&mut self, ctx: &mut ggez::Context) -> SceneSwitch<Ev>;
fn draw(&mut self, ctx: &mut ggez::Context) -> ggez::GameResult<()>;
fn input(&mut self, event: Ev, started: bool);
fn name(&self) -> &str;
fn draw_previous(&self) -> bool {
false
}
}
#[allow(dead_code)]
impl<Ev> SceneSwitch<Ev> {
pub fn replace<S>(scene: S) -> Self
where
S: Scene<Ev> + 'static,
{
SceneSwitch::Replace(Box::new(scene))
}
pub fn push<S>(scene: S) -> Self
where
S: Scene<Ev> + 'static,
{
SceneSwitch::Push(Box::new(scene))
}
pub fn pop() -> Self {
SceneSwitch::Pop
}
}
pub struct SceneStack<Ev> {
scenes: Vec<Box<dyn Scene<Ev>>>,
}
#[allow(dead_code)]
impl<Ev> SceneStack<Ev> {
pub fn new(_ctx: &mut ggez::Context) -> Self {
Self { scenes: Vec::new() }
}
pub fn push(&mut self, scene: Box<dyn Scene<Ev>>) {
self.scenes.push(scene)
}
pub fn pop(&mut self) -> Box<dyn Scene<Ev>> {
self
.scenes
.pop()
.expect("ERROR: Popped an empty scene stack.")
}
pub fn current(&self) -> &dyn Scene<Ev> {
&**self
.scenes
.last()
.expect("ERROR: Tried to get current scene of an empty scene stack.")
}
pub fn switch(&mut self, next_scene: SceneSwitch<Ev>) -> Option<Box<dyn Scene<Ev>>> {
match next_scene {
SceneSwitch::None => None,
SceneSwitch::Pop => {
let s = self.pop();
println!("POP scene {}", s.name());
Some(s)
}
SceneSwitch::Push(s) => {
println!("PUSH scene {}", s.name());
self.push(s);
None
}
SceneSwitch::Replace(s) => {
let old_scene = self.pop();
println!("REPLACE scene {}", s.name());
self.push(s);
Some(old_scene)
}
}
}
pub fn update(&mut self, ctx: &mut ggez::Context) {
let next_scene = {
let current_scene = &mut **self
.scenes
.last_mut()
.expect("Tried to update empty scene stack");
current_scene.update(ctx)
};
self.switch(next_scene);
}
fn draw_scenes(scenes: &mut [Box<dyn Scene<Ev>>], ctx: &mut ggez::Context) {
assert!(scenes.len() > 0);
if let Some((current, rest)) = scenes.split_last_mut() {
if current.draw_previous() {
SceneStack::draw_scenes(rest, ctx);
}
current
.draw(ctx)
.expect("I would hope drawing a scene never fails!");
}
}
pub fn draw(&mut self, ctx: &mut ggez::Context) {
SceneStack::draw_scenes(&mut self.scenes, ctx)
}
pub fn input(&mut self, event: Ev, started: bool) {
let current_scene = &mut **self
.scenes
.last_mut()
.expect("Tried to do input for empty scene stack");
current_scene.input(event, started);
}
}
| true
|
8f693f951ebbda771a256ae0f8128d5e23213b85
|
Rust
|
xiuxiu62/rust-workshop
|
/calculator/src/main.rs
|
UTF-8
| 1,643
| 3.515625
| 4
|
[] |
no_license
|
use std::io::{stdin, stdout, Write};
use std::panic::panic_any;
fn main() {
loop {
prompt();
match prompt_continue() {
true => continue,
false => return,
}
}
}
fn prompt_continue() -> bool {
let mut res = String::new();
print!("Continue? [y/n]: ");
read(&mut res);
match res.trim().chars().next().unwrap() {
'y' => true,
'n' => false,
_ => {
print!("Invalid answer ");
prompt_continue()
}
}
}
fn prompt() {
print!("Pick an operator [+-*/]: ");
let op: char = read_op();
print!("Pick the first number: ");
let n1 = read_num();
print!("Pick the second number: ");
let n2 = read_num();
match calculate(op, n1, n2) {
Ok(n) => print!("{} {} {} = {}\n", n1, op, n2, n),
Err(e) => panic_any(e),
}
}
fn calculate<'a>(op: char, n1: f32, n2: f32) -> Result<f32, &'a str> {
match op {
'+' => Ok(n1 + n2),
'-' => Ok(n1 - n2),
'*' => Ok(n1 * n2),
'/' => Ok(n1 / n2),
_ => Err("Not a valid operator"),
}
}
fn read_num() -> f32 {
let mut res = String::new();
read(&mut res);
res.trim().parse().unwrap()
}
fn read_op() -> char {
let mut res = String::new();
read(&mut res);
let res: char = res.trim().chars().next().unwrap();
if "+-*/".contains(res) {
res
} else {
print!("Invalid operator, try again [+-*/]: ");
read_op()
}
}
fn read(input: &mut String) {
stdout().flush().expect("failed to flush");
stdin().read_line(input).expect("failed to read");
}
| true
|
583df7f5dba8f9eb5f95e5c15bdd4589ecd09ca5
|
Rust
|
nagyf/rs-chess
|
/src/engine/board/piece/sliding/mod.rs
|
UTF-8
| 5,946
| 3.421875
| 3
|
[
"MIT"
] |
permissive
|
//! This module is used to calculate attack targets for sliding pieces (queen, rook, bishop).
//!
//! The module uses the `Hyperbola Quintessence` method to calculate the targets without lookups.
//!
//! For more information: [https://www.chessprogramming.org/Hyperbola_Quintessence](https://www.chessprogramming.org/Hyperbola_Quintessence)
use crate::engine::board::bitboard::BitBoard;
use crate::engine::board::piece::Piece;
use crate::engine::board::square::{constants, Square};
#[cfg(test)]
mod tests;
/// Returns the attack targets for the specific `piece` type on the specific `square`,
/// taking into account the `occupied` squares.
///
/// The function will only work for `Queen`, `Rook` and `Bishop`. In any other case it will panic!
pub fn get_piece_attacks(piece: Piece, square: Square, occupied: BitBoard) -> BitBoard {
match piece {
Piece::Rook => rook_attacks(square, occupied),
Piece::Bishop => bishop_attacks(square, occupied),
Piece::Queen => queen_attacks(square, occupied),
_ => panic!("Invalid piece")
}
}
/// Returns the attack targets of a `Rook` on the specific `square` considering the `occupied` squares.
pub fn rook_attacks(square: Square, occupied: BitBoard) -> BitBoard {
rank_attacks(square, occupied) | file_attacks(square, occupied)
}
/// Returns the attack targets of a `Queen` on the specific `square` considering the `occupied` squares.
pub fn queen_attacks(square: Square, occupied: BitBoard) -> BitBoard {
rook_attacks(square, occupied) | bishop_attacks(square, occupied)
}
/// Returns the attack targets of a `Bishop` on the specific `square` considering the `occupied` squares.
pub fn bishop_attacks(square: Square, occupied: BitBoard) -> BitBoard {
diagonal_attacks(square, occupied) | anti_diagonal_attacks(square, occupied)
}
fn file_mask(square: Square) -> BitBoard {
constants::FILE_1 << ((square.to_index() & 7) as usize)
}
fn diagonal_mask(square: Square) -> BitBoard {
let square_idx = square.to_index() as i64;
let maindia = BitBoard::from(0x8040201008040201);
let diag = 8 * (square_idx & 7) - (square_idx & 56);
let nort = (-diag & (diag >> 31)) as usize;
let sout = (diag & (-diag >> 31)) as usize;
(maindia >> sout) << nort
}
fn anti_diagonal_mask(square: Square) -> BitBoard {
let square_idx = square.to_index() as i64;
let maindia = BitBoard::from(0x0102040810204080);
let diag = 56 - 8 * (square_idx & 7) - (square_idx & 56);
let nort = (-diag & (diag >> 31)) as usize;
let sout = (diag & (-diag >> 31)) as usize;
(maindia >> sout) << nort
}
fn diagonal_attacks(square: Square, occupied: BitBoard) -> BitBoard {
let mut forward = occupied & diagonal_mask(square);
let mut reverse = forward.flip_vertical();
forward.0 = forward.0.wrapping_sub(square.as_bb().0);
reverse.0 = reverse.0.wrapping_sub(square.as_bb().flip_vertical().0);
forward ^= reverse.flip_vertical();
forward &= diagonal_mask(square);
forward
}
fn anti_diagonal_attacks(square: Square, occupied: BitBoard) -> BitBoard {
let mut forward = occupied & anti_diagonal_mask(square);
let mut reverse = forward.flip_vertical();
forward.0 = forward.0.wrapping_sub(square.as_bb().0);
reverse.0 = reverse.0.wrapping_sub(square.as_bb().flip_vertical().0);
forward ^= reverse.flip_vertical();
forward &= anti_diagonal_mask(square);
forward
}
fn file_attacks(square: Square, occupied: BitBoard) -> BitBoard {
let mut forward = occupied & file_mask(square);
let mut reverse = forward.flip_vertical();
forward.0 = forward.0.wrapping_sub(square.as_bb().0);
reverse.0 = reverse.0.wrapping_sub(square.as_bb().flip_vertical().0);
forward ^= reverse.flip_vertical();
forward &= file_mask(square);
forward
}
lazy_static! {
/// Pre-calculated rank attack target lookup table.
///
/// 2048 Bytes = 2KByte
static ref FIRST_RANK_ATTACKS: [[u8; 256]; 8] = init_first_rank_attacks();
}
/// Initializes the lookup table for rank attacks.
///
/// The resulting array will contain every possible combination of occupancies for all the 8 files
/// in a single rank.
fn init_first_rank_attacks() -> [[u8; 256]; 8] {
let mut result: [[u8; 256]; 8] = [[0; 256]; 8];
for file in 0..8 {
for occupancy in 0..256 {
result[file][occupancy] = single_rank_attacks(1u8 << file, occupancy as u8);
}
}
result
}
/// Calculates the attack targets for a single rank (thus u8 used instead of u64).
fn single_rank_attacks(file: u8, occ: u8) -> u8 {
left_rank_attacks(file, occ) | right_rank_attacks(file, occ)
}
/// Calculates the attack targets from the left of the specified file, considering the occupied squares.
///
/// TODO I'm sure this can be improved
fn left_rank_attacks(file: u8, occ: u8) -> u8 {
let mut result = 0;
let mut next = file << 1;
while next > 0x00 {
result ^= next;
if occ & next != 0x00 {
break;
}
next = next << 1;
}
result
}
/// Calculates the attack targets from the right of the specified file, considering the occupied squares.
///
/// TODO I'm sure this can be improved
fn right_rank_attacks(file: u8, occ: u8) -> u8 {
let mut result = 0;
let mut next = file >> 1;
while next > 0x00 {
result ^= next;
if occ & next != 0x00 {
break;
}
next = next >> 1;
}
result
}
fn rank_attacks(sq: Square, occ: BitBoard) -> BitBoard {
let file = sq.get_file().to_index() - 1;
let rankx8 = ((sq.get_rank().to_index() - 1) * 8) as usize; // rank * 8
// After shifting we only care about the first rank
let rank_occurences = (occ.0 >> rankx8) as u8;
// Search for the attack targets in the lookup table
let attacks = FIRST_RANK_ATTACKS[file as usize][rank_occurences as usize] as u64;
BitBoard(attacks << rankx8 as usize)
}
| true
|
9821dc20f4923ad31b202224a408c6f87ac22e39
|
Rust
|
mvidner/exercism-rust
|
/isbn-verifier/src/lib.rs
|
UTF-8
| 1,796
| 3.6875
| 4
|
[] |
no_license
|
/// Determines whether the supplied string is a valid ISBN number
pub fn is_valid_isbn(isbn: &str) -> bool {
let rv: Result<Vec<u8>, String> = parse_isbn(isbn);
let r: Result<(), String> = rv.and_then(check_valid_isbn_num);
match r {
Ok(()) => true,
Err(s) => {
println!("{}: {}", isbn, s);
false
}
}
}
fn parse_isbn(isbn: &str) -> Result<Vec<u8>, String> {
let rvec: Vec<Result<u8, String>> = isbn
.chars()
.filter(|&c| c != '-')
.map(|c| parse_isbn_digit(c))
.enumerate()
.map(|(i, r)| match r {
Ok(10) => {
if i != 9 {
Err(format!("X found at position {}", i))
} else {
Ok(10)
}
},
Ok(n) => Ok(n),
Err(e) => Err(e),
})
.collect::<Vec<_>>();
// Collection<Result> -> Result<Collection>
let result = rvec.iter().cloned().collect();
result
}
fn parse_isbn_digit(c: char) -> Result<u8, String> {
if c == 'X' {
Ok(10)
} else if c >= '0' && c <= '9' {
Ok((c as u8) - ('0' as u8))
} else {
Err(format!("'{}' is not an ISBN digit", c))
}
}
fn check_valid_isbn_num(x: Vec<u8>) -> Result<(), String> {
if x.len() != 10 {
return Err("Length (without dashes) is not 10".to_string());
}
let sum =
x[0] as u32 * 10 +
x[1] as u32 * 9 +
x[2] as u32 * 8 +
x[3] as u32 * 7 +
x[4] as u32 * 6 +
x[5] as u32 * 5 +
x[6] as u32 * 4 +
x[7] as u32 * 3 +
x[8] as u32 * 2 +
x[9] as u32;
if sum % 11 == 0 {
Ok(())
} else {
Err("Checksum does not match".to_string())
}
}
| true
|
4a6da8bce92a342477909357d02f9c88affdc1ff
|
Rust
|
ankurhimanshu14/novarche
|
/src/apis/rm_store/gate_entry.rs
|
UTF-8
| 14,775
| 2.640625
| 3
|
[
"Apache-2.0"
] |
permissive
|
pub mod gate_entry {
use chrono::NaiveDate;
use mysql::*;
use mysql::prelude::*;
use crate::apis::utils::parse::parse::parse_from_row;
use crate::apis::utils::gen_uuid::gen_uuid::generate_uuid;
#[derive(Debug, Clone)]
pub struct GateEntry {
pub grn: usize,
pub grn_date: NaiveDate,
pub gate_entry_id: String,
pub challan_no: usize,
pub challan_date: NaiveDate,
pub steel_code: String,
pub item_description: String,
pub party_code: String,
pub heat_no: String,
pub heat_code: Option<String>,
pub received_qty: f64
}
impl GateEntry {
/// Creates a new Gate Entry.
/// This assigns a Universally unique Identifier utilizing the Uuid crate version v4.
/// The generated uuid is converted to String value before initializing the struct.
/// The heat code field identified by heat_code is an optional value.
pub fn new(
grn: usize,
grn_date: NaiveDate,
challan_no: usize,
challan_date: NaiveDate,
steel_code: String,
item_description: String,
party_code: String,
heat_no: String,
heat_code: Option<String>,
received_qty: f64
) -> Self {
GateEntry {
gate_entry_id: generate_uuid(),
grn,
grn_date,
challan_no,
challan_date,
steel_code,
item_description,
party_code,
heat_no,
heat_code: match &heat_code.clone().unwrap().len() {
0 => None,
_ => Some(heat_code.clone().unwrap())
},
received_qty
}
}
/// Saves the new Gate Entry to the MySQL database
/// The gate entry table references the party and steel databases.
pub fn post(&self) -> Result<()> {
let url: &str = "mysql://root:@localhost:3306/mws_database";
let pool: Pool = Pool::new(url)?;
let mut conn = pool.get_conn()?;
let table = "CREATE TABLE IF NOT EXISTS gate_entry(
grn_id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
gate_entry_id VARCHAR(200) NOT NULL UNIQUE,
grn BIGINT NOT NULL,
grn_date DATETIME NOT NULL,
challan_no BIGINT NOT NULL,
challan_date DATETIME NOT NULL,
steel_code VARCHAR(20) NOT NULL,
item_description TEXT,
party_code VARCHAR(10) NOT NULL,
heat_no VARCHAR(20) NOT NULL,
heat_code VARCHAR(10),
received_qty FLOAT(20, 3) NOT NULL,
avail_qty FLOAT(20, 3) NOT NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
modified_at DATETIME ON UPDATE CURRENT_TIMESTAMP,
UNIQUE INDEX ch_heatno_itmcd (challan_no, heat_no, steel_code),
CONSTRAINT sr_fk_grn_prty FOREIGN KEY(party_code) REFERENCES party(party_code) ON UPDATE CASCADE ON DELETE CASCADE,
CONSTRAINT sr_fk_grn_itm FOREIGN KEY(steel_code) REFERENCES steels(steel_code) ON UPDATE CASCADE ON DELETE CASCADE
)ENGINE = InnoDB;";
conn.query_drop(table)?;
let insert = "INSERT INTO gate_entry(
gate_entry_id,
grn,
grn_date,
challan_no,
challan_date,
steel_code,
item_description,
party_code,
heat_no,
heat_code,
received_qty,
avail_qty
) VALUES (
:gate_entry_id,
:grn,
:grn_date,
:challan_no,
:challan_date,
:steel_code,
:item_description,
:party_code,
:heat_no,
:heat_code,
:received_qty,
:avail_qty
)";
conn.exec_drop(
insert,
params! {
"gate_entry_id" => self.gate_entry_id.clone(),
"grn" => self.grn.clone(),
"grn_date" => self.grn_date,
"challan_no" => self.challan_no.clone(),
"challan_date" => self.challan_date.clone(),
"steel_code" => self.steel_code.clone(),
"item_description" => self.item_description.clone(),
"party_code" => self.party_code.clone(),
"heat_no" => self.heat_no.clone(),
"heat_code" => self.heat_code.clone(),
"received_qty" => self.received_qty.clone(),
"avail_qty" => self.received_qty.clone()
}
)?;
Ok(())
}
/// Generates the Gate Entry List ordered by challan date.
pub fn get_gate_entry_list() -> Vec<GateEntry> {
let query = "SELECT gate_entry_id, grn, grn_date, challan_no, challan_date, steel_code, item_description, party_code, heat_no, heat_code, received_qty FROM gate_entry ORDER BY challan_date ASC;";
let url = "mysql://root:@localhost:3306/mws_database".to_string();
let pool = Pool::new(url).unwrap();
let mut conn = pool.get_conn().unwrap();
let mut v: Vec<GateEntry> = Vec::new();
let if_exist = "SELECT COUNT(*)
FROM information_schema.tables
WHERE table_schema = DATABASE()
AND table_name = 'gate_entry';";
let result = conn.query_map(
if_exist,
|count: usize| {
count
}
).unwrap();
match &result[0] {
0 => vec![()],
_ => {
conn.query_map(
query,
|(gate_entry_id, grn, grn_date, challan_no, challan_date, steel_code, item_description, party_code, heat_no, heat_code, received_qty)| {
let gr = GateEntry {
gate_entry_id, grn, grn_date, challan_no, challan_date, steel_code, item_description, party_code, heat_no, heat_code, received_qty
};
v.push(gr);
}
).unwrap()
}
};
v
}
pub fn export_to_csv() {
let query = "SELECT
grn,
grn_date,
challan_no,
challan_date,
steel_code,
item_description,
party_code,
heat_no,
heat_code,
received_qty
FROM gate_entry ORDER BY challan_date ASC
INTO OUTFILE 'C:/Program Files/MySQL/MySQL Workbench 8.0 CE/Uploads/data.csv'
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\r\n';";
let url = "mysql://root:@localhost:3306/mws_database".to_string();
let pool = Pool::new(url).unwrap();
let mut conn = pool.get_conn().unwrap();
conn.query_drop(query).unwrap();
}
pub fn get_heat_no_list() -> Result<Vec<String>> {
let url = "mysql://root:@localhost:3306/mws_database".to_string();
let pool = Pool::new(url)?;
let mut conn = pool.get_conn()?;
let query = "SELECT DISTINCT heat_no FROM gate_entry;";
let mut v: Vec<String> = Vec::new();
let if_exist = "SELECT COUNT(*)
FROM information_schema.tables
WHERE table_schema = DATABASE()
AND table_name = 'gate_entry';";
let result = conn.query_map(
if_exist,
|count: usize| {
count
}
).unwrap();
match &result[0] {
0 => vec![()],
_ => {
conn.query_map(
query,
|heat_no: String| {
v.push(heat_no.to_string())
}
).unwrap()
}
};
Ok(v)
}
pub fn assign_approvals(h: String, v: Vec<usize>) -> Result<()> {
let url: &str = "mysql://root:@localhost:3306/mws_database";
let pool: Pool = Pool::new(url)?;
let mut conn = pool.get_conn()?;
let temp_table = "CREATE TEMPORARY TABLE temp_approvals(
approval_id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
heat_no VARCHAR(20) NOT NULL,
part_no INT NOT NULL
)ENGINE = InnoDB;";
conn.query_drop(temp_table)?;
let insert = "INSERT INTO temp_approvals(
heat_no,
part_no
) VALUES (
:heat_no,
:part_no
);";
let table = "CREATE TABLE IF NOT EXISTS approved_components(
approval_id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
rm_id VARCHAR(100) NOT NULL,
heat_no VARCHAR(20) NOT NULL,
part_no INT NOT NULL,
avail_qty FLOAT(10, 3) NOT NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
modified_at DATETIME ON UPDATE CURRENT_TIMESTAMP,
UNIQUE INDEX heat_part (heat_no, part_no),
CONSTRAINT sr_fk_ap_grn FOREIGN KEY(rm_id) REFERENCES gate_entry(gate_entry_id) ON UPDATE CASCADE ON DELETE CASCADE
)ENGINE = InnoDB;";
let trig = "CREATE TRIGGER after_approved_components_insert
AFTER INSERT
ON temp_approvals FOR EACH ROW
INSERT INTO approved_components (rm_id, heat_no, part_no, avail_qty)
SELECT
g.gate_entry_id,
NEW.heat_no,
NEW.part_no,
g.received_qty
FROM gate_entry g
WHERE g.heat_no = NEW.heat_no;";
conn.query_drop(table)?;
let result = conn.query_map(
"SHOW TRIGGERS FROM mws_database;",
|t: Row| {
parse_from_row(&t)
}
).unwrap();
let mut trig_name: Vec<String> = Vec::new();
for v in result.clone() {
trig_name.push(v[0].clone());
}
match trig_name.contains(&"after_approved_components_insert".to_string()) {
true => {
for p in v {
conn.exec_drop(
insert,
params! {
"heat_no" => h.to_string(),
"part_no" => p
}
)?;
};
},
false => {
conn.query_drop(trig)?;
for p in v {
conn.exec_drop(
insert,
params! {
"heat_no" => h.to_string(),
"part_no" => p
}
)?;
};
}
}
Ok(())
}
pub fn get_approved_parts(h: String) -> Vec<usize> {
let query = format!("SELECT part_no FROM approved_components WHERE heat_no = '{}';", h);
let url = "mysql://root:@localhost:3306/mws_database".to_string();
let pool = Pool::new(url).unwrap();
let mut conn = pool.get_conn().unwrap();
let mut v: Vec<usize> = Vec::new();
let if_exist = "SELECT COUNT(*)
FROM information_schema.tables
WHERE table_schema = DATABASE()
AND table_name = 'approved_components';";
let result = conn.query_map(
if_exist,
|count: usize| {
count
}
).unwrap();
match &result[0] {
0 => vec![()],
_ => {
conn.query_map(
query,
|part_no: usize| {
v.push(part_no);
}
).unwrap()
}
};
v
}
pub fn get_approved_heats(p: usize) -> Result<Vec<String>> {
let url = "mysql://root:@localhost:3306/mws_database".to_string();
let pool = Pool::new(url)?;
let mut conn = pool.get_conn()?;
let query = format!("SELECT DISTINCT heat_no FROM approved_components WHERE part_no = {};", p);
let mut v: Vec<String> = Vec::new();
let if_exist = "SELECT COUNT(*)
FROM information_schema.tables
WHERE table_schema = DATABASE()
AND table_name = 'approved_components';";
let result = conn.query_map(
if_exist,
|count: usize| {
count
}
).unwrap();
match &result[0] {
0 => vec![()],
_ => {
conn.query_map(
query,
|heat_no: String| {
v.push(heat_no.to_string())
}
).unwrap()
}
};
Ok(v)
}
}
}
| true
|
c3cfec396750dcc397e6679b1be8a2bdde2065da
|
Rust
|
Tiv0w/chip8-emulator
|
/src/desktop/input.rs
|
UTF-8
| 1,734
| 3.25
| 3
|
[] |
no_license
|
use sdl2::event::Event;
use sdl2::keyboard::Keycode;
use sdl2::EventPump;
pub struct SdlInput {
event_pump: EventPump,
}
impl SdlInput {
pub fn new(sdl_context: &sdl2::Sdl) -> SdlInput {
SdlInput {
event_pump: sdl_context.event_pump().unwrap(),
}
}
pub fn read_input(&mut self) -> Option<Keycode> {
let event: Option<Event> = self.event_pump.poll_event();
match event {
Some(Event::Quit { .. }) => Some(Keycode::Escape),
Some(Event::KeyDown { keycode: code, .. }) => code,
_ => None,
}
}
pub fn translate_input(&self, key: Option<Keycode>) -> Option<u8> {
match key {
Some(keycode) => match keycode {
Keycode::Num1 | Keycode::Num7 => Some(0x1),
Keycode::Num2 | Keycode::Num8 => Some(0x2),
Keycode::Num3 | Keycode::Num9 => Some(0x3),
Keycode::Num4 | Keycode::Num0 => Some(0xC),
Keycode::Q | Keycode::U => Some(0x4),
Keycode::W | Keycode::I => Some(0x5),
Keycode::E | Keycode::O => Some(0x6),
Keycode::R | Keycode::P => Some(0xD),
Keycode::A | Keycode::J => Some(0x7),
Keycode::S | Keycode::K => Some(0x8),
Keycode::D | Keycode::L => Some(0x9),
Keycode::F | Keycode::Colon => Some(0xE),
Keycode::Z | Keycode::M => Some(0xA),
Keycode::X | Keycode::Less => Some(0x0),
Keycode::C | Keycode::Greater => Some(0xB),
Keycode::V | Keycode::Question => Some(0xF),
_ => None,
},
None => None,
}
}
}
| true
|
cbcc0dc18598e8d58ec48e8d3a7ac990598eb19e
|
Rust
|
svenstaro/minitraderoute
|
/src/main.rs
|
UTF-8
| 2,881
| 2.65625
| 3
|
[
"MIT"
] |
permissive
|
use std::{sync::mpsc::channel, thread};
use anyhow::{Context, Result};
use audio::AudioEvent;
use pixels::{Pixels, SurfaceTexture};
use rand::{Rng, RngCore};
use rand_xoshiro::rand_core::SeedableRng;
use rand_xoshiro::Xoroshiro128StarStar;
use raqote::*;
use rayon::prelude::*;
use shipyard::*;
use winit::{
dpi::{LogicalSize, PhysicalSize},
event::{Event, VirtualKeyCode, WindowEvent},
event_loop::{ControlFlow, EventLoop},
window::WindowBuilder,
};
use winit_input_helper::WinitInputHelper;
mod audio;
mod cli;
mod components;
mod systems;
mod world;
use cli::parse_cli;
use components::*;
use systems::*;
use world::*;
const WINDOW_WIDTH: u32 = 800;
const WINDOW_HEIGHT: u32 = 800;
const GAME_WIDTH: u32 = 100;
const GAME_HEIGTH: u32 = 100;
fn main() -> Result<()> {
//let mut rng = Xoroshiro128StarStar::seed_from_u64(1337);
parse_cli();
// Init audio channels and spawn the audio thread
let (_snd_send, snd_recv) = channel();
thread::spawn(move || {
audio::start(snd_recv);
});
// Initialize pretty much everything that's important for our game.
// Event loop: Catch redraw requests and user input
// Window input helper
// The actual window.
let event_loop = EventLoop::new();
let mut input = WinitInputHelper::new();
let window = {
let size = LogicalSize::new(WINDOW_WIDTH as f64, WINDOW_HEIGHT as f64);
WindowBuilder::new()
.with_title("Hello Raqote")
.with_inner_size(size)
.with_resizable(false)
.build(&event_loop)
.unwrap()
};
// Initialize the shipyard world
let world = setup_world();
// Initialize our canvas
let mut pixels = {
let window_size = window.inner_size();
let surface_texture = SurfaceTexture::new(window_size.width, window_size.height, &window);
Pixels::new(GAME_WIDTH, GAME_HEIGTH, surface_texture)?
};
event_loop.run(move |event, _, control_flow| {
if let Event::RedrawRequested(_) = event {
let frame = pixels.get_frame();
world.run_with_data(draw_system, frame);
if pixels
.render()
.map_err(|e| eprintln!("pixels.render() failed: {}", e))
.is_err()
{
*control_flow = ControlFlow::Exit;
return;
}
}
// Check if there's some user input in this event.
if input.update(&event) {
// Exit program escape
if input.key_pressed(VirtualKeyCode::Escape) || input.quit() {
*control_flow = ControlFlow::Exit;
return;
}
if let Some(size) = input.window_resized() {
pixels.resize(size.width, size.height);
}
window.request_redraw();
}
});
}
| true
|
0280401e7b2047370dc96b379f3f05bd4ab5e007
|
Rust
|
ummarikar/wzsh
|
/src/builtins/env.rs
|
UTF-8
| 2,393
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
use crate::builtins::Builtin;
use crate::shellhost::FunctionRegistry;
use cancel::Token;
use failure::Fallible;
use shell_vm::{Environment, IoEnvironment, Status, WaitableStatus};
use std::io::Write;
use std::path::PathBuf;
use std::sync::Arc;
use structopt::*;
#[derive(StructOpt)]
/// Set the export attribute for variables (note that this is always
/// set in the current version of wzsh)
pub struct ExportCommand {
names: Vec<String>,
/// Print exported variables in a syntax compatible with the shell
#[structopt(short = "p", conflicts_with = "names")]
print: bool,
}
impl Builtin for ExportCommand {
fn name() -> &'static str {
"export"
}
fn run(
&mut self,
environment: &mut Environment,
_current_directory: &mut PathBuf,
io_env: &IoEnvironment,
cancel: Arc<Token>,
_functions: &Arc<FunctionRegistry>,
) -> Fallible<WaitableStatus> {
if self.print {
for (k, v) in environment.iter() {
cancel.check_cancel()?;
match (k.to_str(), v.to_str()) {
(Some(k), Some(v)) => writeln!(io_env.stdout(), "export {}={}", k, v)?,
_ => writeln!(
io_env.stderr(),
"{:?}={:?} cannot be formatted as utf-8",
k,
v
)?,
}
}
} else {
for name in &self.names {
// parse `name=value` and assign
let split: Vec<&str> = name.splitn(2, '=').collect();
if split.len() == 2 {
environment.set(split[0], split[1]);
}
}
}
Ok(Status::Complete(0.into()).into())
}
}
#[derive(StructOpt)]
/// Unset a variable from the environment
pub struct UnsetCommand {
names: Vec<String>,
}
impl Builtin for UnsetCommand {
fn name() -> &'static str {
"unset"
}
fn run(
&mut self,
environment: &mut Environment,
_current_directory: &mut PathBuf,
_io_env: &IoEnvironment,
_cancel: Arc<Token>,
_functions: &Arc<FunctionRegistry>,
) -> Fallible<WaitableStatus> {
for name in &self.names {
environment.unset(name);
}
Ok(Status::Complete(0.into()).into())
}
}
| true
|
48db37c94a6267ce0efbd83a116ea590b6d010af
|
Rust
|
terakun/quoridor_judge
|
/src/main.rs
|
UTF-8
| 24,605
| 2.59375
| 3
|
[] |
no_license
|
extern crate bit_vec;
extern crate uuid;
extern crate ws;
mod base64;
mod websocket;
use uuid::Uuid;
use bit_vec::BitVec;
use base64::{append, bitvec_to_base64, from_u16, from_u8};
use ws::{CloseCode, Factory, Handler, Message, Sender};
use std::net::{TcpListener, TcpStream};
use std::thread;
use std::io::{Read, Write};
use std::io;
use std::env;
use std::fs;
use std::time::Duration;
use std::sync::mpsc;
const WALL_LIMIT: usize = 10;
const H: usize = 9;
const W: usize = 9;
const PLAYER_NUM: usize = 2;
const DPOS: [(i8, i8); 4] = [(-1, 0), (0, -1), (1, 0), (0, 1)];
const DYDX2MOVEDIR: [[u8; 3]; 3] = [[3, 4, 5], [2, 8, 6], [1, 0, 7]];
fn pos_to_u8((y, x): (usize, usize)) -> u8 {
((W - 1 - y) * W + x) as u8
}
fn wall_to_u8((y, x): (usize, usize)) -> u8 {
((W - 2 - y) * (W - 1) + x) as u8
}
fn in_area(y: usize, x: usize) -> bool {
y < H && x < W
}
fn in_wall_area(y: i8, x: i8) -> bool {
0 <= y && y < (H - 1) as i8 && 0 <= x && x < (W - 1) as i8
}
#[derive(Clone, Copy, PartialEq)]
enum Colour {
White,
Black,
}
#[derive(Debug, Clone, Copy, PartialEq)]
enum Dir {
Vertical,
Horizontal,
}
impl Dir {
fn parse(input: &String) -> Option<Self> {
match input.as_ref() {
"V" => Some(Dir::Vertical),
"H" => Some(Dir::Horizontal),
_ => None,
}
}
}
type Table = Vec<Vec<Option<(Dir, Colour)>>>;
#[derive(Clone)]
struct WallTable {
data: Table,
}
impl WallTable {
fn get(&self, y: i8, x: i8) -> Option<(Dir, Colour)> {
if in_wall_area(y, x) {
self.data[y as usize][x as usize]
} else {
None
}
}
fn erase(&mut self, y: i8, x: i8) {
self.data[y as usize][x as usize] = None;
}
fn set(&mut self, y: i8, x: i8, dir: Dir, c: Colour) {
self.data[y as usize][x as usize] = Some((dir, c));
}
fn new() -> Self {
WallTable {
data: vec![vec![None; W - 1]; H - 1],
}
}
// 壁のみを考慮した次の手の方向を生成
fn next_wallmoves(&self, y: i8, x: i8) -> Vec<(i8, i8)> {
let mut wallmoves = Vec::new();
for (dy, dx) in DPOS.iter() {
if self.exist_wall(y, x, *dy, *dx) {
continue;
}
let (y, x) = (y + *dy, x + *dx);
if in_area(y as usize, x as usize) {
wallmoves.push((*dy, *dx));
}
}
wallmoves
}
fn checkwalldir(&self, y: i8, x: i8, dir: Dir) -> bool {
if let Some((d, _)) = self.get(y, x) {
d == dir
} else {
false
}
}
fn exist_wall(&self, y: i8, x: i8, dy: i8, dx: i8) -> bool {
let (y1, x1, y2, x2, dir) = if dx != 0 {
if dx == 1 {
(y - 1, x, y, x, Dir::Vertical)
} else {
(y - 1, x - 1, y, x - 1, Dir::Vertical)
}
} else {
if dy == 1 {
(y, x, y, x - 1, Dir::Horizontal)
} else {
(y - 1, x, y - 1, x - 1, Dir::Horizontal)
}
};
self.checkwalldir(y1, x1, dir) || self.checkwalldir(y2, x2, dir)
}
fn dfs(&self, y: i8, x: i8, gy: i8, visited: &mut Vec<Vec<bool>>) -> bool {
if y == gy {
return true;
}
visited[y as usize][x as usize] = true;
let moves = self.next_wallmoves(y, x);
for (dy, dx) in moves {
let (ny, nx) = (y + dy, x + dx);
if !visited[ny as usize][nx as usize] {
if self.dfs(ny, nx, gy, visited) {
return true;
}
}
}
false
}
fn reachable(&self, y: i8, x: i8, gy: i8) -> bool {
let mut visited = vec![vec![false; W]; H];
self.dfs(y, x, gy, &mut visited)
}
}
struct Quoridor {
table: WallTable,
white: (usize, usize),
black: (usize, usize),
is_white_turn: bool,
last_move: Option<(usize, usize)>,
turn_num: u16,
white_wall_num: usize,
black_wall_num: usize,
record: Vec<Record>,
}
impl Quoridor {
fn new() -> Self {
Quoridor {
table: WallTable::new(),
white: (H - 1, W / 2),
black: (0, W / 2),
is_white_turn: true,
last_move: None,
turn_num: 1,
white_wall_num: WALL_LIMIT,
black_wall_num: WALL_LIMIT,
record: Vec::new(),
}
}
fn undo(&mut self) -> bool {
if self.record.len() < 1 {
return false;
}
let r = self.record.pop().unwrap();
match r {
Record::Piece(d) => {
let (dy, dx) = Record::to_dydx(d).expect(&format!("illegal record:{}", d));
if self.is_white_turn {
self.black.0 = (self.black.0 as i8 - dy) as usize;
self.black.1 = (self.black.1 as i8 - dx) as usize;
} else {
self.white.0 = (self.white.0 as i8 - dy) as usize;
self.white.1 = (self.white.1 as i8 - dx) as usize;
}
}
Record::Wall(y, x, _) => {
self.table.erase(y as i8, x as i8);
if self.is_white_turn {
self.black_wall_num += 1;
} else {
self.white_wall_num += 1;
}
}
}
self.turn_num -= 1;
self.last_move = match self.record.last() {
Some(Record::Wall(y, x, _)) => Some((*y, *x)),
Some(Record::Piece(_)) | None => None,
};
self.is_white_turn = !self.is_white_turn;
true
}
fn is_over(&self) -> Option<usize> {
if self.white.0 == 0 {
Some(0)
} else if self.black.0 == H - 1 {
Some(1)
} else {
None
}
}
fn settable(&self, y: usize, x: usize, dir: Dir) -> Result<(), String> {
if (self.is_white_turn && self.white_wall_num == 0)
|| (!self.is_white_turn && self.black_wall_num == 0)
{
return Err("You have no wall".to_string());
}
let (y, x) = (y as i8 - 1, x as i8);
if !in_wall_area(y, x) {
return Err("Put position is out of bounds".to_string());
}
if self.table.get(y, x) != None {
return Err("Wall has already built".to_string());
}
match dir {
Dir::Horizontal => {
if self.table.checkwalldir(y, x - 1, Dir::Horizontal)
|| self.table.checkwalldir(y, x + 1, Dir::Horizontal)
{
return Err("Wall has already built".to_string());
}
}
Dir::Vertical => {
if self.table.checkwalldir(y - 1, x, Dir::Vertical)
|| self.table.checkwalldir(y + 1, x, Dir::Vertical)
{
return Err("Wall has already built".to_string());
}
}
}
let mut new_table = self.table.clone();
if self.is_white_turn {
new_table.set(y, x, dir, Colour::White);
} else {
new_table.set(y, x, dir, Colour::Black);
};
if new_table.reachable(self.white.0 as i8, self.white.1 as i8, 0)
&& new_table.reachable(self.black.0 as i8, self.black.1 as i8, (H - 1) as i8)
{
Ok(())
} else {
Err("Unreachable".to_string())
}
}
fn next_moves(&self) -> Vec<(usize, usize)> {
let mut moves = Vec::new();
let (me, op) = if self.is_white_turn {
(
(self.white.0 as i8, self.white.1 as i8),
(self.black.0 as i8, self.black.1 as i8),
)
} else {
(
(self.black.0 as i8, self.black.1 as i8),
(self.white.0 as i8, self.white.1 as i8),
)
};
let wallmoves = self.table.next_wallmoves(me.0, me.1);
for (dy, dx) in wallmoves {
let (y, x) = (dy + me.0, dx + me.1);
if (y, x) == op {
if !in_area((y + dy) as usize, (x + dx) as usize)
|| self.table.exist_wall(y, x, dy, dx)
{
for (dy, dx) in DPOS.iter() {
if self.table.exist_wall(y, x, *dy, *dx) {
continue;
}
let (y2, x2) = (y + dy, x + dx);
if me == (y2, x2) {
continue;
}
if in_area(y2 as usize, x2 as usize) {
moves.push((y2 as usize, x2 as usize));
}
}
} else {
let (y2, x2) = (y + dy, x + dx);
if in_area(y2 as usize, x2 as usize) {
moves.push((y2 as usize, x2 as usize));
}
}
} else {
moves.push((y as usize, x as usize));
}
}
moves
}
fn movable(&self, y: usize, x: usize) -> Result<(), String> {
if !in_area(y, x) {
return Err("Position is out of bounds".to_string());
}
let moves = self.next_moves();
println!("{:?}", moves);
for m in moves {
if (y, x) == m {
return Ok(());
}
}
Err("illegal move".to_string())
}
fn display(&self) -> String {
let mut table: Vec<Vec<char>> = vec![vec![' '; 2 * W - 1]; 2 * H - 1];
for i in 0..H - 1 {
for j in 0..W - 1 {
match self.table.data[i][j] {
Some((Dir::Vertical, _)) => {
table[2 * i][2 * j + 1] = '|';
table[2 * (i + 1)][2 * j + 1] = '|';
}
Some((Dir::Horizontal, _)) => {
table[2 * i + 1][2 * j] = '-';
table[2 * i + 1][2 * (j + 1)] = '-';
}
_ => {}
}
}
}
for i in 0..H - 1 {
for j in 0..W - 1 {
table[2 * i + 1][2 * j + 1] = '*';
}
}
table[2 * self.white.0][2 * self.white.1] = 'W';
table[2 * self.black.0][2 * self.black.1] = 'B';
let mut s = String::new();
s += &(0..(2 * W + 1)).map(|_| "#").collect::<String>();
s += "\n";
for i in 0..2 * H - 1 {
let row: String = table[i].clone().into_iter().collect();
s += &format!("#{}#\n", row);
}
s += &(0..(2 * W + 1)).map(|_| "#").collect::<String>();
s += "\n";
s
}
fn play(&mut self, com: &Command) -> Result<(), String> {
match com {
Command::Put(y, x, dir) => match self.settable(*y + 1, *x, *dir) {
Ok(()) => {
if self.is_white_turn {
self.table.set(*y as i8, *x as i8, *dir, Colour::White);
self.white_wall_num -= 1;
} else {
self.table.set(*y as i8, *x as i8, *dir, Colour::Black);
self.black_wall_num -= 1;
}
self.record.push(Record::Wall(*y, *x, *dir));
self.last_move = Some((*y, *x));
}
Err(e) => {
return Err(e);
}
},
Command::Move(y, x) => match self.movable(*y, *x) {
Ok(()) => {
let (mut dy, mut dx) = if self.is_white_turn {
let (dy, dx) =
(self.white.0 as i8 - *y as i8, self.white.1 as i8 - *x as i8);
self.white = (*y, *x);
(dy, dx)
} else {
let (dy, dx) =
(self.black.0 as i8 - *y as i8, self.black.1 as i8 - *x as i8);
self.black = (*y, *x);
(dy, dx)
};
if dy.abs() == 2 {
dy /= 2;
}
if dx.abs() == 2 {
dx /= 2;
}
let movedir = DYDX2MOVEDIR[(dy + 1) as usize][(dx + 1) as usize];
println!("movedir:{}", movedir);
self.record.push(Record::Piece(movedir));
self.last_move = None;
}
Err(e) => {
return Err(e);
}
},
}
self.is_white_turn = !self.is_white_turn;
self.turn_num += 1;
Ok(())
}
}
#[derive(Debug, Clone, Copy)]
enum Command {
Move(usize, usize),
Put(usize, usize, Dir),
}
#[derive(Debug, Clone, Copy)]
enum Record {
Piece(u8),
Wall(usize, usize, Dir),
}
impl Record {
fn to_dydx(d: u8) -> Option<(i8, i8)> {
let dy = match d {
0 | 1 | 7 => -1,
2 | 6 => 0,
3 | 4 | 5 => 1,
_ => {
return None;
}
};
let dx = match d {
1 | 2 | 3 => 1,
0 | 4 => 0,
5 | 6 | 7 => -1,
_ => {
return None;
}
};
Some((dy, dx))
}
}
impl Command {
fn parse(input: &str) -> Option<Self> {
let input_vec: Vec<&str> = input.trim().split_whitespace().collect();
if input_vec.len() < 2 {
return None;
}
let x = input_vec[0].parse::<usize>().unwrap();
let y = input_vec[1].parse::<usize>().unwrap();
if input_vec.len() < 3 {
Some(Command::Move(y, x))
} else {
let dir = match Dir::parse(&input_vec[2].to_string()) {
Some(dir) => dir,
None => {
return None;
}
};
Some(Command::Put(y, x, dir))
}
}
}
struct Player {
ip: String,
name: String,
}
struct JudgeServer {
ip: String,
streams: Vec<TcpStream>,
players: Vec<Player>,
game: Quoridor,
broadcaster: Sender,
}
impl JudgeServer {
// README.md
fn socketformat(&self) -> String {
let mut output = String::new();
output += &format!(
"{} {} {} {} {} {}\n",
self.game.white.1,
self.game.white.0,
self.game.black.1,
self.game.black.0,
self.game.white_wall_num,
self.game.black_wall_num
);
for rows in &self.game.table.data {
for cell in rows {
output += &format!(
"{} ",
match cell {
Some((Dir::Horizontal, _)) => 1,
Some((Dir::Vertical, _)) => 2,
None => 0,
}
);
}
output += "\n";
}
output
}
// https://www.quoridorfansite.com/tools/qfb.html
fn viewformat(&self) -> String {
let mut bv = BitVec::new();
bv.push(true);
bv.push(false);
append(&mut bv, from_u8(pos_to_u8(self.game.white), 7));
append(&mut bv, from_u8(pos_to_u8(self.game.black), 7));
let mut white_h_walls = Vec::new();
let mut white_v_walls = Vec::new();
let mut black_h_walls = Vec::new();
let mut black_v_walls = Vec::new();
for (y, row) in self.game.table.data.iter().enumerate() {
for (x, wall) in row.iter().enumerate() {
match wall {
Some((Dir::Horizontal, Colour::White)) => {
white_h_walls.push((y, x));
}
Some((Dir::Vertical, Colour::White)) => {
white_v_walls.push((y, x));
}
Some((Dir::Horizontal, Colour::Black)) => {
black_h_walls.push((y, x));
}
Some((Dir::Vertical, Colour::Black)) => {
black_v_walls.push((y, x));
}
None => {}
}
}
}
append(&mut bv, from_u8(white_h_walls.len() as u8, 4));
for pos in white_h_walls {
append(&mut bv, from_u8(wall_to_u8(pos), 6));
}
append(&mut bv, from_u8(white_v_walls.len() as u8, 4));
for pos in white_v_walls {
append(&mut bv, from_u8(wall_to_u8(pos), 6));
}
append(&mut bv, from_u8(black_h_walls.len() as u8, 4));
for pos in black_h_walls {
append(&mut bv, from_u8(wall_to_u8(pos), 6));
}
append(&mut bv, from_u8(black_v_walls.len() as u8, 4));
for pos in black_v_walls {
append(&mut bv, from_u8(wall_to_u8(pos), 6));
}
bv.push(self.game.is_white_turn);
if let Some((y, x)) = self.game.last_move {
bv.push(true);
append(&mut bv, from_u8(wall_to_u8((y, x)), 6));
} else {
bv.push(false);
}
append(&mut bv, from_u16(self.game.turn_num, 10));
bitvec_to_base64(bv)
}
fn historyformat(&self) -> String {
let mut bv = BitVec::new();
bv.push(false);
bv.push(true);
append(&mut bv, from_u16(self.game.record.len() as u16, 10));
for com in &self.game.record {
match com {
Record::Piece(movedir) => {
bv.push(false);
append(&mut bv, from_u8(*movedir, 3));
}
Record::Wall(y, x, dir) => {
bv.push(true);
bv.push(*dir == Dir::Vertical);
append(&mut bv, from_u8(wall_to_u8((*y, *x)), 6));
}
}
}
bitvec_to_base64(bv)
}
fn start(&mut self) -> io::Result<()> {
println!("listening {}", self.ip);
println!("{}", self.game.display());
let lis = TcpListener::bind(&self.ip)?;
let mut num = 0;
let (tx, rx) = mpsc::channel();
while num < PLAYER_NUM {
let (mut stream, addr) = match lis.accept() {
Ok(result) => result,
Err(e) => {
println!("couldn't get client: {:?}", e);
break;
}
};
self.streams.push(stream.try_clone().unwrap());
self.players.push(Player {
ip: addr.to_string(),
name: String::new(),
});
self.broadcaster
.send(ws::Message::Text(format!("mesg:Player {} came", addr)))
.unwrap();
let tx = tx.clone();
let _ = thread::spawn(move || -> io::Result<()> {
let id = num;
println!("{} came", addr);
loop {
let mut b = [0; 128];
let n = stream.read(&mut b)?;
if n == 0 {
return Ok(());
} else {
let message: Vec<u8> = b.iter()
.take_while(|&c| *c != 13 && *c != 0)
.map(|c| *c)
.collect();
let message = String::from_utf8(message).unwrap();
let _ = tx.send((id, message));
}
}
});
num += 1;
}
println!("ready");
self.broadcaster
.send(ws::Message::Text(format!("mesg:Game Start")))
.unwrap();
for (id, mut stream) in self.streams.iter().enumerate() {
stream.write(&format!("{}\n", id).as_bytes())?;
}
let socketmsg = self.socketformat();
self.streams[0].write(&socketmsg.as_bytes())?;
loop {
thread::sleep(Duration::from_micros(100));
for (from_id, message) in rx.recv().iter() {
println!("{:?}", message);
let s: Vec<&str> = message.split(":").collect();
if s.len() == 2 {
match s[1] {
"undo" => {
self.game.undo();
self.game.undo();
let sendmsg = self.viewformat();
self.broadcaster
.send(ws::Message::Text(format!("mesg:undo")))
.unwrap();
self.broadcaster
.send(ws::Message::Text(format!("qfcode:{}", sendmsg)))
.unwrap();
continue;
}
other => {
self.broadcaster
.send(ws::Message::Text(format!(
"mesg:{}:{}",
self.players[*from_id].ip, other
)))
.unwrap();
continue;
}
}
}
let command = Command::parse(&message).expect("parse error");
if let Err(e) = self.game.play(&command) {
println!("{}", e);
break;
}
let result = self.game.display();
let socketmsg = self.socketformat();
let sendmsg = self.viewformat();
println!("{}", result);
println!("socket format:\n{}", socketmsg);
println!("browser format:\n{}", sendmsg);
self.broadcaster
.send(ws::Message::Text(format!("qfcode:{}", sendmsg)))
.unwrap();
{
let mut stream: &TcpStream =
&mut self.streams[(from_id + 1) as usize % PLAYER_NUM];
stream.write(&socketmsg.as_bytes())?;
}
if let Some(winner) = self.game.is_over() {
println!("Player {} win!", winner);
let winner_name = if winner == 0 {
"white".to_string()
} else {
"black".to_string()
};
self.broadcaster
.send(ws::Message::Text(format!(
"mesg:Player {} win!",
winner_name
)))
.unwrap();
thread::sleep(Duration::from_micros(1000));
// output history file
let game_uuid = Uuid::new_v4();
let filename = game_uuid.to_string();
let mut f = fs::File::create(filename).unwrap();
f.write_all(self.historyformat().as_bytes()).unwrap();
return Ok(());
}
}
}
}
}
fn main() {
let args: Vec<String> = env::args().collect();
let ip = if args.len() >= 2 {
args[1].clone()
} else {
"127.0.0.1".to_string()
};
let wsport = if args.len() >= 3 {
args[2].parse::<usize>().unwrap()
} else {
3012
};
let socketport = if args.len() >= 4 {
args[3].parse::<usize>().unwrap()
} else {
8080
};
let factory = websocket::MyFactory::new(&format!("{}:{}", ip, socketport));
let websocket = ws::WebSocket::new(factory).unwrap();
let broadcaster = websocket.broadcaster();
{
let ip = ip.clone();
std::thread::spawn(move || {
websocket.listen(&format!("{}:{}", ip, wsport)).unwrap();
});
}
let mut server = JudgeServer {
ip: format!("{}:{}", ip, socketport),
streams: Vec::new(),
players: Vec::new(),
game: Quoridor::new(),
broadcaster: broadcaster,
};
match server.start() {
Ok(_) => (),
Err(e) => println!("{:?}", e),
}
}
| true
|
b75836839b949518198afad9ce512982107c3f14
|
Rust
|
GopherSecurity/plonky
|
/src/bigint/bigint_inverse.rs
|
UTF-8
| 1,334
| 2.828125
| 3
|
[] |
no_license
|
#![allow(clippy::many_single_char_names)]
use std::cmp::Ordering::Less;
use crate::{add_no_overflow, cmp, div2, is_even, is_odd, sub, one_array};
pub(crate) fn nonzero_multiplicative_inverse<const N: usize>(a: [u64; N], order: [u64; N]) -> [u64; N] {
// Based on Algorithm 16 of "Efficient Software-Implementation of Finite Fields with
// Applications to Cryptography".
let zero = [0; N];
let one = one_array![u64; N];
let mut u = a;
let mut v = order;
let mut b = one;
let mut c = zero;
while u != one && v != one {
while is_even(u) {
u = div2(u);
if is_odd(b) {
b = add_no_overflow(b, order);
}
b = div2(b);
}
while is_even(v) {
v = div2(v);
if is_odd(c) {
c = add_no_overflow(c, order);
}
c = div2(c);
}
if cmp(u, v) == Less {
v = sub(v, u);
if cmp(c, b) == Less {
c = add_no_overflow(c, order);
}
c = sub(c, b);
} else {
u = sub(u, v);
if cmp(b, c) == Less {
b = add_no_overflow(b, order);
}
b = sub(b, c);
}
}
if u == one {
b
} else {
c
}
}
| true
|
f060e36ff7f13a429ddea1be18566329b22123a1
|
Rust
|
mrhota/icu4rs
|
/src/version.rs
|
UTF-8
| 1,411
| 2.765625
| 3
|
[
"Unlicense",
"MIT"
] |
permissive
|
use std::convert::TryFrom;
use std::io;
pub type PiecewiseVersion = (u8, u8, u8, u8);
#[allow(non_camel_case_types)]
#[derive(Clone, Copy, Debug, Ord, PartialOrd, Eq, PartialEq)]
pub enum Version {
Unicode1_0(PiecewiseVersion),
Unicode1_0_1(PiecewiseVersion),
Unicode1_1_0(PiecewiseVersion),
Unicode1_1_5(PiecewiseVersion),
Unicode2_0(PiecewiseVersion),
Unicode2_1_2(PiecewiseVersion),
Unicode2_1_5(PiecewiseVersion),
Unicode2_1_8(PiecewiseVersion),
Unicode2_1_9(PiecewiseVersion),
Unicode3_0(PiecewiseVersion),
Unicode3_0_1(PiecewiseVersion),
Unicode3_1_0(PiecewiseVersion),
Unicode3_1_1(PiecewiseVersion),
Unicode3_2(PiecewiseVersion),
Unicode4_0(PiecewiseVersion),
Unicode4_0_1(PiecewiseVersion),
Unicode4_1(PiecewiseVersion),
Unicode5_0(PiecewiseVersion),
Unicode5_1(PiecewiseVersion),
Unicode5_2(PiecewiseVersion),
Unicode6_0(PiecewiseVersion),
Unicode6_1(PiecewiseVersion),
Unicode6_2(PiecewiseVersion),
Unicode6_3(PiecewiseVersion),
Unicode7_0(PiecewiseVersion),
Unicode8_0(PiecewiseVersion),
Unicode9_0(PiecewiseVersion),
Unicode10_0(PiecewiseVersion),
}
// TODO make this more than a stub
impl TryFrom<PiecewiseVersion> for Version {
type Error = io::Error;
fn try_from(version: PiecewiseVersion) -> Result<Self, Self::Error> {
Ok(Version::Unicode10_0(version))
}
}
| true
|
9640ca12603ee9dfb290f0ddf171c7371f07baa5
|
Rust
|
TyOverby/spatial
|
/quad.rs
|
UTF-8
| 6,142
| 3.125
| 3
|
[] |
no_license
|
#![feature(struct_variant)]
use std::num::FromPrimitive;
use std::default::Default;
trait QTNumber: Num + Ord + FromPrimitive + Copy + Default {}
trait Point<N> {
fn x(&self)-> N;
fn y(&self)-> N;
}
struct Cardinal<T> {
nw: T,
ne: T,
sw: T,
se: T
}
impl <T> Cardinal<T> {
fn new( nw: T, ne: T, sw: T, se: T) -> Cardinal<T> {
Cardinal { nw: nw, ne: ne, sw: sw, se: se }
}
}
#[deriving(Show, Eq, Copy)]
struct AABB<N> {
x: N, y: N,
w: N
}
impl <N: QTNumber> AABB<N> {
fn new(x: N, y: N, w: N) -> AABB<N> {
AABB {x: x, y: y, w: w}
}
fn split(&self) -> Cardinal<AABB<N>> {
let two = FromPrimitive::from_uint(2).unwrap();
let wot = self.w / two;
let sw = AABB::new(self.x, self.y, wot);
let nw = AABB::new(self.x, self.y + wot, wot);
let se = AABB::new(self.x + wot, self.y, wot);
let ne = AABB::new(self.x + wot, self.y + wot, wot);
return Cardinal::new(nw, ne, sw, se);
}
}
impl <N: QTNumber, P: Point<N>> AABB<N> {
fn contains(&self, pt: &P) -> bool {
let px = pt.x();
let py = pt.y();
if px < self.x { return false }
if py < self.y { return false }
if px > self.x + self.w { return false }
if py > self.y + self.w { return false }
return true;
}
}
enum QuadTree<N, P> {
Leaf {
bounding: AABB<N>,
contents: Vec<P>,
cutoff: uint
}, // One value
Node {
bounding: AABB<N>, // Split into quadrants
children: Box<Cardinal<QuadTree<N, P>>>,
cutoff: uint
}
}
impl <N: QTNumber, P> QuadTree<N, P> {
fn leaf_empty(bounding: AABB<N>, cutoff: uint) -> QuadTree<N, P>{
Leaf {
bounding: bounding,
contents: Vec::with_capacity(cutoff),
cutoff: cutoff
}
}
fn leaf(bounding: AABB<N>, contents: Vec<P>, cutoff: uint) -> QuadTree<N, P> {
Leaf {
bounding: bounding,
contents: contents,
cutoff: cutoff
}
}
fn node(bounding: AABB<N>, children: Box<Cardinal<QuadTree<N, P>>>, cutoff: uint) -> QuadTree<N, P>{
Node {
bounding: bounding,
children: children,
cutoff: cutoff
}
}
pub fn new(bounding: AABB<N>, cutoff: uint) -> QuadTree<N, P> {
let split = bounding.split();
QuadTree::node(bounding, box Cardinal::new(
QuadTree::leaf_empty(split.nw, cutoff),
QuadTree::leaf_empty(split.ne, cutoff),
QuadTree::leaf_empty(split.sw, cutoff),
QuadTree::leaf_empty(split.se, cutoff)), cutoff)
}
}
impl <N: QTNumber, P: Point<N> + Clone> QuadTree<N, P> {
fn contains(&self, p: &P) -> bool {
match self {
&Leaf{ref bounding, ref contents, ref cutoff } => bounding.contains(p),
&Node{ref bounding, ref children, ref cutoff } => bounding.contains(p),
}
}
fn is_full(&self, p: &P) -> bool {
match self {
&Node { ref bounding, ref children, ref cutoff } => false,
&Leaf { ref bounding, ref contents, ref cutoff } => {
if contents.len() == *cutoff {
!contents.iter().any(|op| op.x() == p.x() && op.y() == p.y())
} else {
false
}
}
}
}
fn breakup(&mut self) -> QuadTree<N, P> {
match self {
&Node {ref bounding, ref children, ref cutoff } => fail!("internal error: breakup() on Node"),
&Leaf {ref bounding, ref mut contents, cutoff } => {
let bb = bounding.split();
let mut node = QuadTree::node(*bounding, box Cardinal::new(
QuadTree::leaf_empty(bb.nw, cutoff), QuadTree::leaf_empty(bb.ne, cutoff),
QuadTree::leaf_empty(bb.sw, cutoff), QuadTree::leaf_empty(bb.se, cutoff)), cutoff);
for point in contents.iter() {
node.insert(point.clone());
}
node
}
}
}
fn insert(&mut self, p: P) -> bool {
if !self.contains(&p) {
return false;
}
match self {
&Leaf{ ref bounding, ref mut contents, cutoff } => {
contents.push(p);
}
&Node{ ref bounding, ref mut children, cutoff } => {
let mut rep = &mut children.se;
if children.nw.contains(&p) {
rep = &mut children.nw;
} else if children.ne.contains(&p) {
rep = &mut children.ne;
} else if children.sw.contains(&p) {
rep = &mut children.sw;
}
assert!(rep.contains(&p), "{:?}, {:?}", rep, p);
if !rep.is_full(&p) {
rep.insert(p);
} else {
*rep = rep.breakup();
rep.insert(p);
}
}
};
return true;
}
}
fn main() {}
#[test]
fn testBasic() {
#[deriving(Show)]
impl QTNumber for f64 {}
#[deriving(Clone)]
struct Pt { x:f64, y: f64}
impl Point<f64> for Pt {
fn x(&self)->f64{ self.x }
fn y(&self)->f64{ self.y }
}
impl Pt {
fn new(x: f64, y: f64) -> Pt {
Pt { x: x, y: y }
}
}
let mut tree:QuadTree<f64, Pt> = QuadTree::new(AABB::new(0.0, 0.0, 100.0), 4);
tree.insert(Pt::new(0.0, 0.0));
tree.insert(Pt::new(1.0, 1.0));
tree.insert(Pt::new(2.0, 2.0));
tree.insert(Pt::new(3.0, 3.0));
tree.insert(Pt::new(4.0, 4.0));
tree.insert(Pt::new(5.0, 5.0));
tree.insert(Pt::new(5.0, 5.0));
tree.insert(Pt::new(5.0, 5.0));
tree.insert(Pt::new(5.0, 5.0));
tree.insert(Pt::new(5.0, 5.0));
tree.insert(Pt::new(5.0, 5.0));
tree.insert(Pt::new(5.0, 5.0));
tree.insert(Pt::new(5.0, 5.0));
tree.insert(Pt::new(5.0, 5.0));
println!("{:?}", tree);
assert!(false);
}
| true
|
09ab12fb7098fd63949bad4609c72142888eb4fe
|
Rust
|
enarx/enarx
|
/crates/shim-kvm/src/snp/cpuid_page.rs
|
UTF-8
| 3,198
| 2.828125
| 3
|
[
"Apache-2.0"
] |
permissive
|
// SPDX-License-Identifier: Apache-2.0
//! Structures and methods to handle the SEV-SNP CPUID page
use core::arch::x86_64::CpuidResult;
use crate::snp::snp_active;
use crate::_ENARX_CPUID;
/// See [`cpuid_count`](cpuid_count).
#[inline]
pub fn cpuid(leaf: u32) -> CpuidResult {
cpuid_count(leaf, 0)
}
/// Returns the result of the `cpuid` instruction for a given `leaf` (`EAX`)
/// and `sub_leaf` (`ECX`).
///
/// If in SEV-SNP mode this function will lookup the return values in the CPUID page.
///
/// In case of leaf 1, the osxsave feature bit will be set, if the xsave feature bit is set.
///
/// The highest-supported leaf value is returned by the first tuple argument of
/// [`__get_cpuid_max(0)`](fn.__get_cpuid_max.html). For leaves containung
/// sub-leaves, the second tuple argument returns the highest-supported
/// sub-leaf
/// value.
///
/// The [CPUID Wikipedia page][wiki_cpuid] contains how to query which
/// information using the `EAX` and `ECX` registers, and the interpretation of
/// the results returned in `EAX`, `EBX`, `ECX`, and `EDX`.
///
/// The references are:
/// - [Intel 64 and IA-32 Architectures Software Developer's Manual Volume 2:
/// Instruction Set Reference, A-Z][intel64_ref].
/// - [AMD64 Architecture Programmer's Manual, Volume 3: General-Purpose and
/// System Instructions][amd64_ref].
///
/// [wiki_cpuid]: https://en.wikipedia.org/wiki/CPUID
/// [intel64_ref]: http://www.intel.de/content/dam/www/public/us/en/documents/manuals/64-ia-32-architectures-software-developer-instruction-set-reference-manual-325383.pdf
/// [amd64_ref]: http://support.amd.com/TechDocs/24594.pdf
#[inline]
pub fn cpuid_count(leaf: u32, sub_leaf: u32) -> CpuidResult {
let mut res = if snp_active() {
let cpuid = &unsafe { _ENARX_CPUID };
cpuid
.get_functions()
.iter()
.find_map(|e| {
if e.eax_in == leaf && e.ecx_in == sub_leaf {
Some(CpuidResult {
eax: e.eax,
ebx: e.ebx,
ecx: e.ecx,
edx: e.edx,
})
} else {
None
}
})
.unwrap_or(CpuidResult {
eax: 0,
ebx: 0,
ecx: 0,
edx: 0,
})
} else {
unsafe { core::arch::x86_64::__cpuid_count(leaf, sub_leaf) }
};
if leaf == 1 && sub_leaf == 0 && (res.ecx & (1u32 << 26)) != 0 {
// set osxsave feature bit, if xsave feature bit is set
res.ecx |= 1u32 << 27;
}
res
}
/// Returns the highest-supported `leaf` (`EAX`) and sub-leaf (`ECX`) `cpuid`
/// values.
///
/// If `cpuid` is supported, and `leaf` is zero, then the first tuple argument
/// contains the highest `leaf` value that `cpuid` supports. For `leaf`s
/// containing sub-leafs, the second tuple argument contains the
/// highest-supported sub-leaf value.
///
/// See also [`cpuid`](cpuid) and
/// [`cpuid_count`](cpuid_count).
#[inline]
pub fn get_cpuid_max(leaf: u32) -> (u32, u32) {
let CpuidResult { eax, ebx, .. } = cpuid(leaf);
(eax, ebx)
}
| true
|
63b00d98d1ecea8e8bdccd329b8c9bc2ce89ece5
|
Rust
|
iquiw/gitcop
|
/src/main.rs
|
UTF-8
| 3,375
| 2.84375
| 3
|
[] |
no_license
|
use std::env;
use std::process::exit;
use clap::{crate_name, crate_version, Arg, ArgAction, Command};
use gitcop::cmd;
use gitcop::config;
use gitcop::print;
#[tokio::main]
async fn main() {
print::color_init();
let matches = Command::new(crate_name!())
.version(crate_version!())
.arg_required_else_help(true)
.subcommands([
Command::new("list")
.about("List repos")
.arg(
Arg::new("default")
.short('d')
.long("default")
.action(ArgAction::SetTrue)
.help("List default repositories only"),
)
.arg(
Arg::new("optional")
.short('o')
.long("optional")
.action(ArgAction::SetTrue)
.help("List optional repositories only"),
)
.arg(
Arg::new("unknown")
.short('u')
.long("unknown")
.action(ArgAction::SetTrue)
.help("List unknown directories"),
),
Command::new("pull").about("Pull in directories").arg(
Arg::new("DIR")
.required(true)
.action(ArgAction::Append)
.num_args(1..),
),
Command::new("sync")
.about("Sync repos")
.arg(Arg::new("REPO").action(ArgAction::Append).num_args(0..)),
])
.get_matches();
let cfg = match config::load_config(".gitcop.toml") {
Ok(cfg) => cfg,
Err(err) => {
eprintln!("Unable to load .gitcop.toml, {}", err);
exit(1)
}
};
if let Some(dir) = cfg.dir() {
if let Err(err) = env::set_current_dir(dir) {
eprintln!(
"Unable to change directory to \"{}\", {}",
dir.display(),
err
);
exit(1)
}
}
match matches.subcommand() {
Some(("list", sub_m)) => {
if sub_m.get_flag("unknown") {
cmd::list_unknown(&cfg)
} else {
let mut default = sub_m.get_flag("default");
let mut optional = sub_m.get_flag("optional");
if !default && !optional {
default = true;
optional = true;
}
cmd::list(&cfg, default, optional)
}
}
Some(("pull", sub_m)) => {
if let Some(dirs) = sub_m.get_many::<String>("DIR") {
cmd::pull(&cfg, dirs.map(|s| s.as_str())).await
} else {
Ok(())
}
}
Some(("sync", sub_m)) => {
if let Some(names) = sub_m.get_many::<String>("REPO") {
cmd::sync(&cfg, Some(&names.map(|s| s.as_str()).collect())).await
} else {
cmd::sync(&cfg, None).await
}
}
_ => Ok(()),
}
.unwrap_or_else(|err| {
eprintln!(
"gitcop: {} failed, Error: {}",
matches.subcommand_name().unwrap_or("unknown"),
err
);
})
}
| true
|
395379d7052454dd15b6d79912372aabe46e007c
|
Rust
|
mfkiwl/WGFEM-Rust
|
/dense_matrix.rs
|
UTF-8
| 7,180
| 2.90625
| 3
|
[
"MIT"
] |
permissive
|
use common::*;
use la;
use std::libc::{c_ulong};
use std::ptr;
use std::iter::{range_inclusive};
use std::cast::transmute;
use extra::c_vec::CVec;
/// Column major dense matrix type.
pub struct DenseMatrix {
priv data: CVec<R>,
priv num_rows: uint,
priv num_cols: uint,
priv capacity_cols: uint,
}
impl DenseMatrix {
pub fn from_fn(num_rows: uint, num_cols: uint, f: |row:uint, col:uint| -> R) -> DenseMatrix {
let n = num_rows * num_cols;
let mut data = unsafe { alloc_data(n) };
for i in range(0u, n) {
let c = i / num_rows;
let r = i % num_rows;
unsafe { unsafe_set(&mut data, i, f(r,c)); }
}
DenseMatrix {
data: data,
num_rows: num_rows,
num_cols: num_cols,
capacity_cols: num_cols,
}
}
// Create dense matrix of indicated size, with unitialized entries. This constructor should only be used if the
// part(s) of the matrix to be used are subsequently initialized, such as via the set() function.
pub fn of_size(num_rows: uint, num_cols: uint) -> DenseMatrix {
let n = num_rows * num_cols;
let data = unsafe { alloc_data(n) };
DenseMatrix {
data: data,
num_rows: num_rows,
num_cols: num_cols,
capacity_cols: num_cols,
}
}
pub fn from_elem(num_rows: uint, num_cols: uint, elem: R) -> DenseMatrix {
let n = num_rows * num_cols;
let mut data = unsafe { alloc_data(n) };
for i in range(0u, n) {
unsafe { unsafe_set(&mut data, i, elem); }
}
DenseMatrix {
data: data,
num_rows: num_rows,
num_cols: num_cols,
capacity_cols: num_cols,
}
}
pub fn from_elem_with_cols_capacity(num_rows: uint, num_cols: uint, elem: R, capacity_cols: uint) -> DenseMatrix {
if capacity_cols < num_cols { fail!("Capacity columns must be greater or equal to number of columns."); }
let cap = num_rows * capacity_cols;
let mut data = unsafe { alloc_data(cap) };
for i in range(0u, cap) {
unsafe { unsafe_set(&mut data, i, elem); }
}
DenseMatrix {
data: data,
num_rows: num_rows,
num_cols: num_cols,
capacity_cols: capacity_cols,
}
}
pub fn of_size_with_cols_capacity(num_rows: uint, num_cols: uint, capacity_cols: uint) -> DenseMatrix {
if capacity_cols < num_cols { fail!("Capacity columns must be greater or equal to number of columns."); }
let data = unsafe { alloc_data(num_rows * capacity_cols) };
DenseMatrix {
data: data,
num_rows: num_rows,
num_cols: num_cols,
capacity_cols: capacity_cols,
}
}
// NOTE: This constructor does not initialize the lower triangular values.
pub fn upper_triangle_from_fn(side_len: uint, f: |row:uint, col:uint| -> R) -> DenseMatrix {
let n = side_len * side_len;
let mut data = unsafe { alloc_data(n) };
for c in range(0, side_len) {
for r in range_inclusive(0, c) {
unsafe { unsafe_set(&mut data, c * side_len + r, f(r,c)); }
}
}
DenseMatrix {
data: data,
num_rows: side_len,
num_cols: side_len,
capacity_cols: side_len,
}
}
// NOTE: This constructor does not initialize the upper triangular values.
pub fn lower_triangle_from_fn(side_len: uint, f: |row:uint, col:uint| -> R) -> DenseMatrix {
let n = side_len * side_len;
let mut data = unsafe { alloc_data(n) };
for r in range(0, side_len) {
for c in range_inclusive(0, r) {
unsafe { unsafe_set(&mut data, c * side_len + r, f(r,c)); }
}
}
DenseMatrix {
data: data,
num_rows: side_len,
num_cols: side_len,
capacity_cols: side_len,
}
}
pub fn from_rows(num_rows: uint, num_cols: uint, elems: &[~[R]]) -> DenseMatrix {
DenseMatrix::from_fn(num_rows, num_cols, |r,c| elems[r][c])
}
#[inline(always)]
pub fn num_rows(&self) -> uint {
self.num_rows
}
#[inline(always)]
pub fn num_cols(&self) -> uint {
self.num_cols
}
#[inline(always)]
pub fn capacity_cols(&self) -> uint {
self.capacity_cols
}
#[inline]
pub fn get(&self, r: uint, c: uint) -> R {
if c >= self.num_cols || r >= self.num_rows { fail!("Row or column out of range."); }
unsafe { unsafe_get(&self.data, c * self.num_rows + r) }
}
#[inline]
pub fn set(&mut self, r: uint, c: uint, value: R) {
if c >= self.num_cols || r >= self.num_rows { fail!("Row or column out of range."); }
unsafe { unsafe_set(&mut self.data, c * self.num_rows + r, value); }
}
#[inline(never)]
pub fn copy_into(&self, m: &mut DenseMatrix) {
if self.num_rows != m.num_rows || self.num_cols > m.num_cols {
fail!("Matrix layouts not compatible for dense matrix copy-into operation.");
}
unsafe {
la::copy_matrix(transmute(self.data.get(0)), self.num_rows as c_ulong, self.num_cols as c_ulong, transmute(m.data.get(0)));
}
}
#[inline(never)]
pub fn copy_upper_triangle_into(&self, m: &mut DenseMatrix) {
if self.num_rows != m.num_rows || self.num_cols != m.num_cols {
fail!("Matrix layouts not compatible for dense matrix copy-into operation.");
}
unsafe {
la::copy_upper_triangle(transmute(self.data.get(0)), self.num_rows as c_ulong, self.num_cols as c_ulong, transmute(m.data.get(0)));
}
}
#[inline(never)]
pub fn fill_upper_triangle_from(&mut self, m: &DenseMatrix) {
if self.num_rows != m.num_rows || m.num_cols > self.num_cols {
fail!("Matrix layouts not compatible for dense matrix copy-into operation.");
}
unsafe {
la::copy_upper_triangle(transmute(m.data.get(0)), m.num_rows as c_ulong, m.num_cols as c_ulong, transmute(self.data.get(0)));
}
}
#[inline(never)]
pub fn fill_from_fn(&mut self, f: |row:uint, col:uint| -> R) {
for r in range(0, self.num_rows) {
for c in range(0, self.num_cols) {
unsafe { unsafe_set(&mut self.data, c * self.num_rows + r, f(r,c)); }
}
}
}
#[inline(always)]
pub unsafe fn col_maj_data_ptr(&self) -> *R {
transmute(self.data.get(0))
}
#[inline(always)]
pub unsafe fn mut_col_maj_data_ptr(&self) -> *mut R {
transmute(self.data.get(0))
}
pub fn set_num_cols(&mut self, num_cols: uint) {
if num_cols > self.capacity_cols {
fail!("Cannot increase number of columns beyond capacity.");
}
self.num_cols = num_cols;
}
pub fn print(&self) {
for i in range(0, self.num_rows) {
for j in range(0, self.num_cols) {
print!(" {:6.3f} ", self.get(i,j));
}
println!("");
}
}
} // DenseMatrix impl
#[inline(always)]
unsafe fn unsafe_set(v: &mut CVec<R>, i: uint, value: R) {
*ptr::mut_offset(transmute(v.get(0)), i as int) = value;
}
#[inline(always)]
unsafe fn unsafe_get(v: &CVec<R>, i: uint) -> R {
*ptr::mut_offset(transmute(v.get(0)), i as int)
}
#[inline(never)]
pub unsafe fn alloc_data(num_doubles: uint) -> CVec<R> {
let doubles = la::alloc_doubles(num_doubles as c_ulong);
CVec::new(doubles, num_doubles)
}
#[unsafe_destructor]
impl Drop for DenseMatrix {
#[inline(never)]
fn drop(&mut self) {
unsafe {
la::free_doubles(transmute(self.data.get(0)))
}
}
}
| true
|
9f8274c8ce345c4168aeb29f6ef0f7060702516c
|
Rust
|
bytecodealliance/wasmtime
|
/cranelift/codegen/src/ir/instructions.rs
|
UTF-8
| 36,667
| 3.078125
| 3
|
[
"LLVM-exception",
"Apache-2.0"
] |
permissive
|
//! Instruction formats and opcodes.
//!
//! The `instructions` module contains definitions for instruction formats, opcodes, and the
//! in-memory representation of IR instructions.
//!
//! A large part of this module is auto-generated from the instruction descriptions in the meta
//! directory.
use alloc::vec::Vec;
use core::fmt::{self, Display, Formatter};
use core::ops::{Deref, DerefMut};
use core::str::FromStr;
#[cfg(feature = "enable-serde")]
use serde::{Deserialize, Serialize};
use crate::bitset::BitSet;
use crate::entity;
use crate::ir::{
self,
condcodes::{FloatCC, IntCC},
trapcode::TrapCode,
types, Block, FuncRef, MemFlags, SigRef, StackSlot, Type, Value,
};
/// Some instructions use an external list of argument values because there is not enough space in
/// the 16-byte `InstructionData` struct. These value lists are stored in a memory pool in
/// `dfg.value_lists`.
pub type ValueList = entity::EntityList<Value>;
/// Memory pool for holding value lists. See `ValueList`.
pub type ValueListPool = entity::ListPool<Value>;
/// A pair of a Block and its arguments, stored in a single EntityList internally.
///
/// NOTE: We don't expose either value_to_block or block_to_value outside of this module because
/// this operation is not generally safe. However, as the two share the same underlying layout,
/// they can be stored in the same value pool.
///
/// BlockCall makes use of this shared layout by storing all of its contents (a block and its
/// argument) in a single EntityList. This is a bit better than introducing a new entity type for
/// the pair of a block name and the arguments entity list, as we don't pay any indirection penalty
/// to get to the argument values -- they're stored in-line with the block in the same list.
///
/// The BlockCall::new function guarantees this layout by requiring a block argument that's written
/// in as the first element of the EntityList. Any subsequent entries are always assumed to be real
/// Values.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
pub struct BlockCall {
/// The underlying storage for the BlockCall. The first element of the values EntityList is
/// guaranteed to always be a Block encoded as a Value via BlockCall::block_to_value.
/// Consequently, the values entity list is never empty.
values: entity::EntityList<Value>,
}
impl BlockCall {
// NOTE: the only uses of this function should be internal to BlockCall. See the block comment
// on BlockCall for more context.
fn value_to_block(val: Value) -> Block {
Block::from_u32(val.as_u32())
}
// NOTE: the only uses of this function should be internal to BlockCall. See the block comment
// on BlockCall for more context.
fn block_to_value(block: Block) -> Value {
Value::from_u32(block.as_u32())
}
/// Construct a BlockCall with the given block and arguments.
pub fn new(block: Block, args: &[Value], pool: &mut ValueListPool) -> Self {
let mut values = ValueList::default();
values.push(Self::block_to_value(block), pool);
values.extend(args.iter().copied(), pool);
Self { values }
}
/// Return the block for this BlockCall.
pub fn block(&self, pool: &ValueListPool) -> Block {
let val = self.values.first(pool).unwrap();
Self::value_to_block(val)
}
/// Replace the block for this BlockCall.
pub fn set_block(&mut self, block: Block, pool: &mut ValueListPool) {
*self.values.get_mut(0, pool).unwrap() = Self::block_to_value(block);
}
/// Append an argument to the block args.
pub fn append_argument(&mut self, arg: Value, pool: &mut ValueListPool) {
self.values.push(arg, pool);
}
/// Return a slice for the arguments of this block.
pub fn args_slice<'a>(&self, pool: &'a ValueListPool) -> &'a [Value] {
&self.values.as_slice(pool)[1..]
}
/// Return a slice for the arguments of this block.
pub fn args_slice_mut<'a>(&'a mut self, pool: &'a mut ValueListPool) -> &'a mut [Value] {
&mut self.values.as_mut_slice(pool)[1..]
}
/// Remove the argument at ix from the argument list.
pub fn remove(&mut self, ix: usize, pool: &mut ValueListPool) {
self.values.remove(1 + ix, pool)
}
/// Clear out the arguments list.
pub fn clear(&mut self, pool: &mut ValueListPool) {
self.values.truncate(1, pool)
}
/// Appends multiple elements to the arguments.
pub fn extend<I>(&mut self, elements: I, pool: &mut ValueListPool)
where
I: IntoIterator<Item = Value>,
{
self.values.extend(elements, pool)
}
/// Return a value that can display this block call.
pub fn display<'a>(&self, pool: &'a ValueListPool) -> DisplayBlockCall<'a> {
DisplayBlockCall { block: *self, pool }
}
/// Deep-clone the underlying list in the same pool. The returned
/// list will have identical contents but changes to this list
/// will not change its contents or vice-versa.
pub fn deep_clone(&self, pool: &mut ValueListPool) -> Self {
Self {
values: self.values.deep_clone(pool),
}
}
}
/// Wrapper for the context needed to display a [BlockCall] value.
pub struct DisplayBlockCall<'a> {
block: BlockCall,
pool: &'a ValueListPool,
}
impl<'a> Display for DisplayBlockCall<'a> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.block.block(&self.pool))?;
let args = self.block.args_slice(&self.pool);
if !args.is_empty() {
write!(f, "(")?;
for (ix, arg) in args.iter().enumerate() {
if ix > 0 {
write!(f, ", ")?;
}
write!(f, "{}", arg)?;
}
write!(f, ")")?;
}
Ok(())
}
}
// Include code generated by `cranelift-codegen/meta/src/gen_inst.rs`. This file contains:
//
// - The `pub enum InstructionFormat` enum with all the instruction formats.
// - The `pub enum InstructionData` enum with all the instruction data fields.
// - The `pub enum Opcode` definition with all known opcodes,
// - The `const OPCODE_FORMAT: [InstructionFormat; N]` table.
// - The private `fn opcode_name(Opcode) -> &'static str` function, and
// - The hash table `const OPCODE_HASH_TABLE: [Opcode; N]`.
//
// For value type constraints:
//
// - The `const OPCODE_CONSTRAINTS : [OpcodeConstraints; N]` table.
// - The `const TYPE_SETS : [ValueTypeSet; N]` table.
// - The `const OPERAND_CONSTRAINTS : [OperandConstraint; N]` table.
//
include!(concat!(env!("OUT_DIR"), "/opcodes.rs"));
impl Display for Opcode {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{}", opcode_name(*self))
}
}
impl Opcode {
/// Get the instruction format for this opcode.
pub fn format(self) -> InstructionFormat {
OPCODE_FORMAT[self as usize - 1]
}
/// Get the constraint descriptor for this opcode.
/// Panic if this is called on `NotAnOpcode`.
pub fn constraints(self) -> OpcodeConstraints {
OPCODE_CONSTRAINTS[self as usize - 1]
}
/// Returns true if the instruction is a resumable trap.
pub fn is_resumable_trap(&self) -> bool {
match self {
Opcode::ResumableTrap | Opcode::ResumableTrapnz => true,
_ => false,
}
}
}
// This trait really belongs in cranelift-reader where it is used by the `.clif` file parser, but since
// it critically depends on the `opcode_name()` function which is needed here anyway, it lives in
// this module. This also saves us from running the build script twice to generate code for the two
// separate crates.
impl FromStr for Opcode {
type Err = &'static str;
/// Parse an Opcode name from a string.
fn from_str(s: &str) -> Result<Self, &'static str> {
use crate::constant_hash::{probe, simple_hash, Table};
impl<'a> Table<&'a str> for [Option<Opcode>] {
fn len(&self) -> usize {
self.len()
}
fn key(&self, idx: usize) -> Option<&'a str> {
self[idx].map(opcode_name)
}
}
match probe::<&str, [Option<Self>]>(&OPCODE_HASH_TABLE, s, simple_hash(s)) {
Err(_) => Err("Unknown opcode"),
// We unwrap here because probe() should have ensured that the entry
// at this index is not None.
Ok(i) => Ok(OPCODE_HASH_TABLE[i].unwrap()),
}
}
}
/// A variable list of `Value` operands used for function call arguments and passing arguments to
/// basic blocks.
#[derive(Clone, Debug)]
pub struct VariableArgs(Vec<Value>);
impl VariableArgs {
/// Create an empty argument list.
pub fn new() -> Self {
Self(Vec::new())
}
/// Add an argument to the end.
pub fn push(&mut self, v: Value) {
self.0.push(v)
}
/// Check if the list is empty.
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
/// Convert this to a value list in `pool` with `fixed` prepended.
pub fn into_value_list(self, fixed: &[Value], pool: &mut ValueListPool) -> ValueList {
let mut vlist = ValueList::default();
vlist.extend(fixed.iter().cloned(), pool);
vlist.extend(self.0, pool);
vlist
}
}
// Coerce `VariableArgs` into a `&[Value]` slice.
impl Deref for VariableArgs {
type Target = [Value];
fn deref(&self) -> &[Value] {
&self.0
}
}
impl DerefMut for VariableArgs {
fn deref_mut(&mut self) -> &mut [Value] {
&mut self.0
}
}
impl Display for VariableArgs {
fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
for (i, val) in self.0.iter().enumerate() {
if i == 0 {
write!(fmt, "{}", val)?;
} else {
write!(fmt, ", {}", val)?;
}
}
Ok(())
}
}
impl Default for VariableArgs {
fn default() -> Self {
Self::new()
}
}
/// Analyzing an instruction.
///
/// Avoid large matches on instruction formats by using the methods defined here to examine
/// instructions.
impl InstructionData {
/// Get the destinations of this instruction, if it's a branch.
///
/// `br_table` returns the empty slice.
pub fn branch_destination<'a>(&'a self, jump_tables: &'a ir::JumpTables) -> &[BlockCall] {
match self {
Self::Jump {
ref destination, ..
} => std::slice::from_ref(destination),
Self::Brif { blocks, .. } => blocks.as_slice(),
Self::BranchTable { table, .. } => jump_tables.get(*table).unwrap().all_branches(),
_ => {
debug_assert!(!self.opcode().is_branch());
&[]
}
}
}
/// Get a mutable slice of the destinations of this instruction, if it's a branch.
///
/// `br_table` returns the empty slice.
pub fn branch_destination_mut<'a>(
&'a mut self,
jump_tables: &'a mut ir::JumpTables,
) -> &mut [BlockCall] {
match self {
Self::Jump {
ref mut destination,
..
} => std::slice::from_mut(destination),
Self::Brif { blocks, .. } => blocks.as_mut_slice(),
Self::BranchTable { table, .. } => {
jump_tables.get_mut(*table).unwrap().all_branches_mut()
}
_ => {
debug_assert!(!self.opcode().is_branch());
&mut []
}
}
}
/// If this is a trapping instruction, get its trap code. Otherwise, return
/// `None`.
pub fn trap_code(&self) -> Option<TrapCode> {
match *self {
Self::CondTrap { code, .. } | Self::Trap { code, .. } => Some(code),
_ => None,
}
}
/// If this is a control-flow instruction depending on an integer condition, gets its
/// condition. Otherwise, return `None`.
pub fn cond_code(&self) -> Option<IntCC> {
match self {
&InstructionData::IntCompare { cond, .. }
| &InstructionData::IntCompareImm { cond, .. } => Some(cond),
_ => None,
}
}
/// If this is a control-flow instruction depending on a floating-point condition, gets its
/// condition. Otherwise, return `None`.
pub fn fp_cond_code(&self) -> Option<FloatCC> {
match self {
&InstructionData::FloatCompare { cond, .. } => Some(cond),
_ => None,
}
}
/// If this is a trapping instruction, get an exclusive reference to its
/// trap code. Otherwise, return `None`.
pub fn trap_code_mut(&mut self) -> Option<&mut TrapCode> {
match self {
Self::CondTrap { code, .. } | Self::Trap { code, .. } => Some(code),
_ => None,
}
}
/// If this is an atomic read/modify/write instruction, return its subopcode.
pub fn atomic_rmw_op(&self) -> Option<ir::AtomicRmwOp> {
match self {
&InstructionData::AtomicRmw { op, .. } => Some(op),
_ => None,
}
}
/// If this is a load/store instruction, returns its immediate offset.
pub fn load_store_offset(&self) -> Option<i32> {
match self {
&InstructionData::Load { offset, .. }
| &InstructionData::StackLoad { offset, .. }
| &InstructionData::Store { offset, .. }
| &InstructionData::StackStore { offset, .. } => Some(offset.into()),
_ => None,
}
}
/// If this is a load/store instruction, return its memory flags.
pub fn memflags(&self) -> Option<MemFlags> {
match self {
&InstructionData::Load { flags, .. }
| &InstructionData::LoadNoOffset { flags, .. }
| &InstructionData::Store { flags, .. }
| &InstructionData::StoreNoOffset { flags, .. }
| &InstructionData::AtomicCas { flags, .. }
| &InstructionData::AtomicRmw { flags, .. } => Some(flags),
_ => None,
}
}
/// If this instruction references a stack slot, return it
pub fn stack_slot(&self) -> Option<StackSlot> {
match self {
&InstructionData::StackStore { stack_slot, .. }
| &InstructionData::StackLoad { stack_slot, .. } => Some(stack_slot),
_ => None,
}
}
/// Return information about a call instruction.
///
/// Any instruction that can call another function reveals its call signature here.
pub fn analyze_call<'a>(&'a self, pool: &'a ValueListPool) -> CallInfo<'a> {
match *self {
Self::Call {
func_ref, ref args, ..
} => CallInfo::Direct(func_ref, args.as_slice(pool)),
Self::CallIndirect {
sig_ref, ref args, ..
} => CallInfo::Indirect(sig_ref, &args.as_slice(pool)[1..]),
_ => {
debug_assert!(!self.opcode().is_call());
CallInfo::NotACall
}
}
}
#[inline]
pub(crate) fn sign_extend_immediates(&mut self, ctrl_typevar: Type) {
if ctrl_typevar.is_invalid() {
return;
}
let bit_width = ctrl_typevar.bits();
match self {
Self::BinaryImm64 {
opcode,
arg: _,
imm,
} => {
if *opcode == Opcode::SdivImm || *opcode == Opcode::SremImm {
imm.sign_extend_from_width(bit_width);
}
}
Self::IntCompareImm {
opcode,
arg: _,
cond,
imm,
} => {
debug_assert_eq!(*opcode, Opcode::IcmpImm);
if cond.unsigned() != *cond {
imm.sign_extend_from_width(bit_width);
}
}
_ => {}
}
}
}
/// Information about call instructions.
pub enum CallInfo<'a> {
/// This is not a call instruction.
NotACall,
/// This is a direct call to an external function declared in the preamble. See
/// `DataFlowGraph.ext_funcs`.
Direct(FuncRef, &'a [Value]),
/// This is an indirect call with the specified signature. See `DataFlowGraph.signatures`.
Indirect(SigRef, &'a [Value]),
}
/// Value type constraints for a given opcode.
///
/// The `InstructionFormat` determines the constraints on most operands, but `Value` operands and
/// results are not determined by the format. Every `Opcode` has an associated
/// `OpcodeConstraints` object that provides the missing details.
#[derive(Clone, Copy)]
pub struct OpcodeConstraints {
/// Flags for this opcode encoded as a bit field:
///
/// Bits 0-2:
/// Number of fixed result values. This does not include `variable_args` results as are
/// produced by call instructions.
///
/// Bit 3:
/// This opcode is polymorphic and the controlling type variable can be inferred from the
/// designated input operand. This is the `typevar_operand` index given to the
/// `InstructionFormat` meta language object. When this bit is not set, the controlling
/// type variable must be the first output value instead.
///
/// Bit 4:
/// This opcode is polymorphic and the controlling type variable does *not* appear as the
/// first result type.
///
/// Bits 5-7:
/// Number of fixed value arguments. The minimum required number of value operands.
flags: u8,
/// Permitted set of types for the controlling type variable as an index into `TYPE_SETS`.
typeset_offset: u8,
/// Offset into `OPERAND_CONSTRAINT` table of the descriptors for this opcode. The first
/// `num_fixed_results()` entries describe the result constraints, then follows constraints for
/// the fixed `Value` input operands. (`num_fixed_value_arguments()` of them).
constraint_offset: u16,
}
impl OpcodeConstraints {
/// Can the controlling type variable for this opcode be inferred from the designated value
/// input operand?
/// This also implies that this opcode is polymorphic.
pub fn use_typevar_operand(self) -> bool {
(self.flags & 0x8) != 0
}
/// Is it necessary to look at the designated value input operand in order to determine the
/// controlling type variable, or is it good enough to use the first return type?
///
/// Most polymorphic instructions produce a single result with the type of the controlling type
/// variable. A few polymorphic instructions either don't produce any results, or produce
/// results with a fixed type. These instructions return `true`.
pub fn requires_typevar_operand(self) -> bool {
(self.flags & 0x10) != 0
}
/// Get the number of *fixed* result values produced by this opcode.
/// This does not include `variable_args` produced by calls.
pub fn num_fixed_results(self) -> usize {
(self.flags & 0x7) as usize
}
/// Get the number of *fixed* input values required by this opcode.
///
/// This does not include `variable_args` arguments on call and branch instructions.
///
/// The number of fixed input values is usually implied by the instruction format, but
/// instruction formats that use a `ValueList` put both fixed and variable arguments in the
/// list. This method returns the *minimum* number of values required in the value list.
pub fn num_fixed_value_arguments(self) -> usize {
((self.flags >> 5) & 0x7) as usize
}
/// Get the offset into `TYPE_SETS` for the controlling type variable.
/// Returns `None` if the instruction is not polymorphic.
fn typeset_offset(self) -> Option<usize> {
let offset = usize::from(self.typeset_offset);
if offset < TYPE_SETS.len() {
Some(offset)
} else {
None
}
}
/// Get the offset into OPERAND_CONSTRAINTS where the descriptors for this opcode begin.
fn constraint_offset(self) -> usize {
self.constraint_offset as usize
}
/// Get the value type of result number `n`, having resolved the controlling type variable to
/// `ctrl_type`.
pub fn result_type(self, n: usize, ctrl_type: Type) -> Type {
debug_assert!(n < self.num_fixed_results(), "Invalid result index");
match OPERAND_CONSTRAINTS[self.constraint_offset() + n].resolve(ctrl_type) {
ResolvedConstraint::Bound(t) => t,
ResolvedConstraint::Free(ts) => panic!("Result constraints can't be free: {:?}", ts),
}
}
/// Get the value type of input value number `n`, having resolved the controlling type variable
/// to `ctrl_type`.
///
/// Unlike results, it is possible for some input values to vary freely within a specific
/// `ValueTypeSet`. This is represented with the `ArgumentConstraint::Free` variant.
pub fn value_argument_constraint(self, n: usize, ctrl_type: Type) -> ResolvedConstraint {
debug_assert!(
n < self.num_fixed_value_arguments(),
"Invalid value argument index"
);
let offset = self.constraint_offset() + self.num_fixed_results();
OPERAND_CONSTRAINTS[offset + n].resolve(ctrl_type)
}
/// Get the typeset of allowed types for the controlling type variable in a polymorphic
/// instruction.
pub fn ctrl_typeset(self) -> Option<ValueTypeSet> {
self.typeset_offset().map(|offset| TYPE_SETS[offset])
}
/// Is this instruction polymorphic?
pub fn is_polymorphic(self) -> bool {
self.ctrl_typeset().is_some()
}
}
type BitSet8 = BitSet<u8>;
type BitSet16 = BitSet<u16>;
/// A value type set describes the permitted set of types for a type variable.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct ValueTypeSet {
/// Allowed lane sizes
pub lanes: BitSet16,
/// Allowed int widths
pub ints: BitSet8,
/// Allowed float widths
pub floats: BitSet8,
/// Allowed ref widths
pub refs: BitSet8,
/// Allowed dynamic vectors minimum lane sizes
pub dynamic_lanes: BitSet16,
}
impl ValueTypeSet {
/// Is `scalar` part of the base type set?
///
/// Note that the base type set does not have to be included in the type set proper.
fn is_base_type(self, scalar: Type) -> bool {
let l2b = scalar.log2_lane_bits();
if scalar.is_int() {
self.ints.contains(l2b)
} else if scalar.is_float() {
self.floats.contains(l2b)
} else if scalar.is_ref() {
self.refs.contains(l2b)
} else {
false
}
}
/// Does `typ` belong to this set?
pub fn contains(self, typ: Type) -> bool {
if typ.is_dynamic_vector() {
let l2l = typ.log2_min_lane_count();
self.dynamic_lanes.contains(l2l) && self.is_base_type(typ.lane_type())
} else {
let l2l = typ.log2_lane_count();
self.lanes.contains(l2l) && self.is_base_type(typ.lane_type())
}
}
/// Get an example member of this type set.
///
/// This is used for error messages to avoid suggesting invalid types.
pub fn example(self) -> Type {
let t = if self.ints.max().unwrap_or(0) > 5 {
types::I32
} else if self.floats.max().unwrap_or(0) > 5 {
types::F32
} else {
types::I8
};
t.by(1 << self.lanes.min().unwrap()).unwrap()
}
}
/// Operand constraints. This describes the value type constraints on a single `Value` operand.
enum OperandConstraint {
/// This operand has a concrete value type.
Concrete(Type),
/// This operand can vary freely within the given type set.
/// The type set is identified by its index into the TYPE_SETS constant table.
Free(u8),
/// This operand is the same type as the controlling type variable.
Same,
/// This operand is `ctrlType.lane_of()`.
LaneOf,
/// This operand is `ctrlType.as_truthy()`.
AsTruthy,
/// This operand is `ctrlType.half_width()`.
HalfWidth,
/// This operand is `ctrlType.double_width()`.
DoubleWidth,
/// This operand is `ctrlType.split_lanes()`.
SplitLanes,
/// This operand is `ctrlType.merge_lanes()`.
MergeLanes,
/// This operands is `ctrlType.dynamic_to_vector()`.
DynamicToVector,
/// This operand is `ctrlType.narrower()`.
Narrower,
/// This operand is `ctrlType.wider()`.
Wider,
}
impl OperandConstraint {
/// Resolve this operand constraint into a concrete value type, given the value of the
/// controlling type variable.
pub fn resolve(&self, ctrl_type: Type) -> ResolvedConstraint {
use self::OperandConstraint::*;
use self::ResolvedConstraint::Bound;
match *self {
Concrete(t) => Bound(t),
Free(vts) => ResolvedConstraint::Free(TYPE_SETS[vts as usize]),
Same => Bound(ctrl_type),
LaneOf => Bound(ctrl_type.lane_of()),
AsTruthy => Bound(ctrl_type.as_truthy()),
HalfWidth => Bound(ctrl_type.half_width().expect("invalid type for half_width")),
DoubleWidth => Bound(
ctrl_type
.double_width()
.expect("invalid type for double_width"),
),
SplitLanes => {
if ctrl_type.is_dynamic_vector() {
Bound(
ctrl_type
.dynamic_to_vector()
.expect("invalid type for dynamic_to_vector")
.split_lanes()
.expect("invalid type for split_lanes")
.vector_to_dynamic()
.expect("invalid dynamic type"),
)
} else {
Bound(
ctrl_type
.split_lanes()
.expect("invalid type for split_lanes"),
)
}
}
MergeLanes => {
if ctrl_type.is_dynamic_vector() {
Bound(
ctrl_type
.dynamic_to_vector()
.expect("invalid type for dynamic_to_vector")
.merge_lanes()
.expect("invalid type for merge_lanes")
.vector_to_dynamic()
.expect("invalid dynamic type"),
)
} else {
Bound(
ctrl_type
.merge_lanes()
.expect("invalid type for merge_lanes"),
)
}
}
DynamicToVector => Bound(
ctrl_type
.dynamic_to_vector()
.expect("invalid type for dynamic_to_vector"),
),
Narrower => {
let ctrl_type_bits = ctrl_type.log2_lane_bits();
let mut tys = ValueTypeSet::default();
// We're testing scalar values, only.
tys.lanes = BitSet::from_range(0, 1);
if ctrl_type.is_int() {
// The upper bound in from_range is exclusive, and we want to exclude the
// control type to construct the interval of [I8, ctrl_type).
tys.ints = BitSet8::from_range(3, ctrl_type_bits as u8);
} else if ctrl_type.is_float() {
// The upper bound in from_range is exclusive, and we want to exclude the
// control type to construct the interval of [F32, ctrl_type).
tys.floats = BitSet8::from_range(5, ctrl_type_bits as u8);
} else {
panic!("The Narrower constraint only operates on floats or ints");
}
ResolvedConstraint::Free(tys)
}
Wider => {
let ctrl_type_bits = ctrl_type.log2_lane_bits();
let mut tys = ValueTypeSet::default();
// We're testing scalar values, only.
tys.lanes = BitSet::from_range(0, 1);
if ctrl_type.is_int() {
let lower_bound = ctrl_type_bits as u8 + 1;
// The largest integer type we can represent in `BitSet8` is I128, which is
// represented by bit 7 in the bit set. Adding one to exclude I128 from the
// lower bound would overflow as 2^8 doesn't fit in a u8, but this would
// already describe the empty set so instead we leave `ints` in its default
// empty state.
if lower_bound < BitSet8::bits() as u8 {
// The interval should include all types wider than `ctrl_type`, so we use
// `2^8` as the upper bound, and add one to the bits of `ctrl_type` to define
// the interval `(ctrl_type, I128]`.
tys.ints = BitSet8::from_range(lower_bound, 8);
}
} else if ctrl_type.is_float() {
// The interval should include all float types wider than `ctrl_type`, so we
// use `2^7` as the upper bound, and add one to the bits of `ctrl_type` to
// define the interval `(ctrl_type, F64]`.
tys.floats = BitSet8::from_range(ctrl_type_bits as u8 + 1, 7);
} else {
panic!("The Wider constraint only operates on floats or ints");
}
ResolvedConstraint::Free(tys)
}
}
}
}
/// The type constraint on a value argument once the controlling type variable is known.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum ResolvedConstraint {
/// The operand is bound to a known type.
Bound(Type),
/// The operand type can vary freely within the given set.
Free(ValueTypeSet),
}
#[cfg(test)]
mod tests {
use super::*;
use alloc::string::ToString;
#[test]
fn inst_data_is_copy() {
fn is_copy<T: Copy>() {}
is_copy::<InstructionData>();
}
#[test]
fn inst_data_size() {
// The size of `InstructionData` is performance sensitive, so make sure
// we don't regress it unintentionally.
assert_eq!(std::mem::size_of::<InstructionData>(), 16);
}
#[test]
fn opcodes() {
use core::mem;
let x = Opcode::Iadd;
let mut y = Opcode::Isub;
assert!(x != y);
y = Opcode::Iadd;
assert_eq!(x, y);
assert_eq!(x.format(), InstructionFormat::Binary);
assert_eq!(format!("{:?}", Opcode::IaddImm), "IaddImm");
assert_eq!(Opcode::IaddImm.to_string(), "iadd_imm");
// Check the matcher.
assert_eq!("iadd".parse::<Opcode>(), Ok(Opcode::Iadd));
assert_eq!("iadd_imm".parse::<Opcode>(), Ok(Opcode::IaddImm));
assert_eq!("iadd\0".parse::<Opcode>(), Err("Unknown opcode"));
assert_eq!("".parse::<Opcode>(), Err("Unknown opcode"));
assert_eq!("\0".parse::<Opcode>(), Err("Unknown opcode"));
// Opcode is a single byte, and because Option<Opcode> originally came to 2 bytes, early on
// Opcode included a variant NotAnOpcode to avoid the unnecessary bloat. Since then the Rust
// compiler has brought in NonZero optimization, meaning that an enum not using the 0 value
// can be optional for no size cost. We want to ensure Option<Opcode> remains small.
assert_eq!(mem::size_of::<Opcode>(), mem::size_of::<Option<Opcode>>());
}
#[test]
fn instruction_data() {
use core::mem;
// The size of the `InstructionData` enum is important for performance. It should not
// exceed 16 bytes. Use `Box<FooData>` out-of-line payloads for instruction formats that
// require more space than that. It would be fine with a data structure smaller than 16
// bytes, but what are the odds of that?
assert_eq!(mem::size_of::<InstructionData>(), 16);
}
#[test]
fn constraints() {
let a = Opcode::Iadd.constraints();
assert!(a.use_typevar_operand());
assert!(!a.requires_typevar_operand());
assert_eq!(a.num_fixed_results(), 1);
assert_eq!(a.num_fixed_value_arguments(), 2);
assert_eq!(a.result_type(0, types::I32), types::I32);
assert_eq!(a.result_type(0, types::I8), types::I8);
assert_eq!(
a.value_argument_constraint(0, types::I32),
ResolvedConstraint::Bound(types::I32)
);
assert_eq!(
a.value_argument_constraint(1, types::I32),
ResolvedConstraint::Bound(types::I32)
);
let b = Opcode::Bitcast.constraints();
assert!(!b.use_typevar_operand());
assert!(!b.requires_typevar_operand());
assert_eq!(b.num_fixed_results(), 1);
assert_eq!(b.num_fixed_value_arguments(), 1);
assert_eq!(b.result_type(0, types::I32), types::I32);
assert_eq!(b.result_type(0, types::I8), types::I8);
match b.value_argument_constraint(0, types::I32) {
ResolvedConstraint::Free(vts) => assert!(vts.contains(types::F32)),
_ => panic!("Unexpected constraint from value_argument_constraint"),
}
let c = Opcode::Call.constraints();
assert_eq!(c.num_fixed_results(), 0);
assert_eq!(c.num_fixed_value_arguments(), 0);
let i = Opcode::CallIndirect.constraints();
assert_eq!(i.num_fixed_results(), 0);
assert_eq!(i.num_fixed_value_arguments(), 1);
let cmp = Opcode::Icmp.constraints();
assert!(cmp.use_typevar_operand());
assert!(cmp.requires_typevar_operand());
assert_eq!(cmp.num_fixed_results(), 1);
assert_eq!(cmp.num_fixed_value_arguments(), 2);
assert_eq!(cmp.result_type(0, types::I64), types::I8);
}
#[test]
fn value_set() {
use crate::ir::types::*;
let vts = ValueTypeSet {
lanes: BitSet16::from_range(0, 8),
ints: BitSet8::from_range(4, 7),
floats: BitSet8::from_range(0, 0),
refs: BitSet8::from_range(5, 7),
dynamic_lanes: BitSet16::from_range(0, 4),
};
assert!(!vts.contains(I8));
assert!(vts.contains(I32));
assert!(vts.contains(I64));
assert!(vts.contains(I32X4));
assert!(vts.contains(I32X4XN));
assert!(!vts.contains(F32));
assert!(vts.contains(R32));
assert!(vts.contains(R64));
assert_eq!(vts.example().to_string(), "i32");
let vts = ValueTypeSet {
lanes: BitSet16::from_range(0, 8),
ints: BitSet8::from_range(0, 0),
floats: BitSet8::from_range(5, 7),
refs: BitSet8::from_range(0, 0),
dynamic_lanes: BitSet16::from_range(0, 8),
};
assert_eq!(vts.example().to_string(), "f32");
let vts = ValueTypeSet {
lanes: BitSet16::from_range(1, 8),
ints: BitSet8::from_range(0, 0),
floats: BitSet8::from_range(5, 7),
refs: BitSet8::from_range(0, 0),
dynamic_lanes: BitSet16::from_range(0, 8),
};
assert_eq!(vts.example().to_string(), "f32x2");
let vts = ValueTypeSet {
lanes: BitSet16::from_range(2, 8),
ints: BitSet8::from_range(3, 7),
floats: BitSet8::from_range(0, 0),
refs: BitSet8::from_range(0, 0),
dynamic_lanes: BitSet16::from_range(0, 8),
};
assert_eq!(vts.example().to_string(), "i32x4");
let vts = ValueTypeSet {
// TypeSet(lanes=(1, 256), ints=(8, 64))
lanes: BitSet16::from_range(0, 9),
ints: BitSet8::from_range(3, 7),
floats: BitSet8::from_range(0, 0),
refs: BitSet8::from_range(0, 0),
dynamic_lanes: BitSet16::from_range(0, 8),
};
assert!(vts.contains(I32));
assert!(vts.contains(I32X4));
assert!(!vts.contains(R32));
assert!(!vts.contains(R64));
}
}
| true
|
231b36d77fc78bbd99751f3fb36e4c70db61b7b0
|
Rust
|
janpauldahlke/fhir-rs
|
/src/model/DiagnosticReport.rs
|
UTF-8
| 30,248
| 2.640625
| 3
|
[
"MIT"
] |
permissive
|
#![allow(unused_imports, non_camel_case_types)]
use crate::model::Attachment::Attachment;
use crate::model::CodeableConcept::CodeableConcept;
use crate::model::DiagnosticReport_Media::DiagnosticReport_Media;
use crate::model::Element::Element;
use crate::model::Extension::Extension;
use crate::model::Identifier::Identifier;
use crate::model::Meta::Meta;
use crate::model::Narrative::Narrative;
use crate::model::Period::Period;
use crate::model::Reference::Reference;
use crate::model::ResourceList::ResourceList;
use serde_json::json;
use serde_json::value::Value;
use std::borrow::Cow;
/// The findings and interpretation of diagnostic tests performed on patients,
/// groups of patients, devices, and locations, and/or specimens derived from these.
/// The report includes clinical context such as requesting and provider
/// information, and some mix of atomic results, images, textual and coded
/// interpretations, and formatted representation of diagnostic reports.
#[derive(Debug)]
pub struct DiagnosticReport<'a> {
pub(crate) value: Cow<'a, Value>,
}
impl DiagnosticReport<'_> {
pub fn new(value: &Value) -> DiagnosticReport {
DiagnosticReport {
value: Cow::Borrowed(value),
}
}
pub fn to_json(&self) -> Value {
(*self.value).clone()
}
/// Extensions for conclusion
pub fn _conclusion(&self) -> Option<Element> {
if let Some(val) = self.value.get("_conclusion") {
return Some(Element {
value: Cow::Borrowed(val),
});
}
return None;
}
/// Extensions for effectiveDateTime
pub fn _effective_date_time(&self) -> Option<Element> {
if let Some(val) = self.value.get("_effectiveDateTime") {
return Some(Element {
value: Cow::Borrowed(val),
});
}
return None;
}
/// Extensions for implicitRules
pub fn _implicit_rules(&self) -> Option<Element> {
if let Some(val) = self.value.get("_implicitRules") {
return Some(Element {
value: Cow::Borrowed(val),
});
}
return None;
}
/// Extensions for issued
pub fn _issued(&self) -> Option<Element> {
if let Some(val) = self.value.get("_issued") {
return Some(Element {
value: Cow::Borrowed(val),
});
}
return None;
}
/// Extensions for language
pub fn _language(&self) -> Option<Element> {
if let Some(val) = self.value.get("_language") {
return Some(Element {
value: Cow::Borrowed(val),
});
}
return None;
}
/// Extensions for status
pub fn _status(&self) -> Option<Element> {
if let Some(val) = self.value.get("_status") {
return Some(Element {
value: Cow::Borrowed(val),
});
}
return None;
}
/// Details concerning a service requested.
pub fn based_on(&self) -> Option<Vec<Reference>> {
if let Some(Value::Array(val)) = self.value.get("basedOn") {
return Some(
val.into_iter()
.map(|e| Reference {
value: Cow::Borrowed(e),
})
.collect::<Vec<_>>(),
);
}
return None;
}
/// A code that classifies the clinical discipline, department or diagnostic service
/// that created the report (e.g. cardiology, biochemistry, hematology, MRI). This
/// is used for searching, sorting and display purposes.
pub fn category(&self) -> Option<Vec<CodeableConcept>> {
if let Some(Value::Array(val)) = self.value.get("category") {
return Some(
val.into_iter()
.map(|e| CodeableConcept {
value: Cow::Borrowed(e),
})
.collect::<Vec<_>>(),
);
}
return None;
}
/// A code or name that describes this diagnostic report.
pub fn code(&self) -> CodeableConcept {
CodeableConcept {
value: Cow::Borrowed(&self.value["code"]),
}
}
/// Concise and clinically contextualized summary conclusion
/// (interpretation/impression) of the diagnostic report.
pub fn conclusion(&self) -> Option<&str> {
if let Some(Value::String(string)) = self.value.get("conclusion") {
return Some(string);
}
return None;
}
/// One or more codes that represent the summary conclusion
/// (interpretation/impression) of the diagnostic report.
pub fn conclusion_code(&self) -> Option<Vec<CodeableConcept>> {
if let Some(Value::Array(val)) = self.value.get("conclusionCode") {
return Some(
val.into_iter()
.map(|e| CodeableConcept {
value: Cow::Borrowed(e),
})
.collect::<Vec<_>>(),
);
}
return None;
}
/// These resources do not have an independent existence apart from the resource
/// that contains them - they cannot be identified independently, and nor can they
/// have their own independent transaction scope.
pub fn contained(&self) -> Option<Vec<ResourceList>> {
if let Some(Value::Array(val)) = self.value.get("contained") {
return Some(
val.into_iter()
.map(|e| ResourceList {
value: Cow::Borrowed(e),
})
.collect::<Vec<_>>(),
);
}
return None;
}
/// The time or time-period the observed values are related to. When the subject of
/// the report is a patient, this is usually either the time of the procedure or of
/// specimen collection(s), but very often the source of the date/time is not known,
/// only the date/time itself.
pub fn effective_date_time(&self) -> Option<&str> {
if let Some(Value::String(string)) = self.value.get("effectiveDateTime") {
return Some(string);
}
return None;
}
/// The time or time-period the observed values are related to. When the subject of
/// the report is a patient, this is usually either the time of the procedure or of
/// specimen collection(s), but very often the source of the date/time is not known,
/// only the date/time itself.
pub fn effective_period(&self) -> Option<Period> {
if let Some(val) = self.value.get("effectivePeriod") {
return Some(Period {
value: Cow::Borrowed(val),
});
}
return None;
}
/// The healthcare event (e.g. a patient and healthcare provider interaction) which
/// this DiagnosticReport is about.
pub fn encounter(&self) -> Option<Reference> {
if let Some(val) = self.value.get("encounter") {
return Some(Reference {
value: Cow::Borrowed(val),
});
}
return None;
}
/// May be used to represent additional information that is not part of the basic
/// definition of the resource. To make the use of extensions safe and manageable,
/// there is a strict set of governance applied to the definition and use of
/// extensions. Though any implementer can define an extension, there is a set of
/// requirements that SHALL be met as part of the definition of the extension.
pub fn extension(&self) -> Option<Vec<Extension>> {
if let Some(Value::Array(val)) = self.value.get("extension") {
return Some(
val.into_iter()
.map(|e| Extension {
value: Cow::Borrowed(e),
})
.collect::<Vec<_>>(),
);
}
return None;
}
/// The logical id of the resource, as used in the URL for the resource. Once
/// assigned, this value never changes.
pub fn id(&self) -> Option<&str> {
if let Some(Value::String(string)) = self.value.get("id") {
return Some(string);
}
return None;
}
/// Identifiers assigned to this report by the performer or other systems.
pub fn identifier(&self) -> Option<Vec<Identifier>> {
if let Some(Value::Array(val)) = self.value.get("identifier") {
return Some(
val.into_iter()
.map(|e| Identifier {
value: Cow::Borrowed(e),
})
.collect::<Vec<_>>(),
);
}
return None;
}
/// One or more links to full details of any imaging performed during the diagnostic
/// investigation. Typically, this is imaging performed by DICOM enabled modalities,
/// but this is not required. A fully enabled PACS viewer can use this information
/// to provide views of the source images.
pub fn imaging_study(&self) -> Option<Vec<Reference>> {
if let Some(Value::Array(val)) = self.value.get("imagingStudy") {
return Some(
val.into_iter()
.map(|e| Reference {
value: Cow::Borrowed(e),
})
.collect::<Vec<_>>(),
);
}
return None;
}
/// A reference to a set of rules that were followed when the resource was
/// constructed, and which must be understood when processing the content. Often,
/// this is a reference to an implementation guide that defines the special rules
/// along with other profiles etc.
pub fn implicit_rules(&self) -> Option<&str> {
if let Some(Value::String(string)) = self.value.get("implicitRules") {
return Some(string);
}
return None;
}
/// The date and time that this version of the report was made available to
/// providers, typically after the report was reviewed and verified.
pub fn issued(&self) -> Option<&str> {
if let Some(Value::String(string)) = self.value.get("issued") {
return Some(string);
}
return None;
}
/// The base language in which the resource is written.
pub fn language(&self) -> Option<&str> {
if let Some(Value::String(string)) = self.value.get("language") {
return Some(string);
}
return None;
}
/// A list of key images associated with this report. The images are generally
/// created during the diagnostic process, and may be directly of the patient, or of
/// treated specimens (i.e. slides of interest).
pub fn media(&self) -> Option<Vec<DiagnosticReport_Media>> {
if let Some(Value::Array(val)) = self.value.get("media") {
return Some(
val.into_iter()
.map(|e| DiagnosticReport_Media {
value: Cow::Borrowed(e),
})
.collect::<Vec<_>>(),
);
}
return None;
}
/// The metadata about the resource. This is content that is maintained by the
/// infrastructure. Changes to the content might not always be associated with
/// version changes to the resource.
pub fn meta(&self) -> Option<Meta> {
if let Some(val) = self.value.get("meta") {
return Some(Meta {
value: Cow::Borrowed(val),
});
}
return None;
}
/// May be used to represent additional information that is not part of the basic
/// definition of the resource and that modifies the understanding of the element
/// that contains it and/or the understanding of the containing element's
/// descendants. Usually modifier elements provide negation or qualification. To
/// make the use of extensions safe and manageable, there is a strict set of
/// governance applied to the definition and use of extensions. Though any
/// implementer is allowed to define an extension, there is a set of requirements
/// that SHALL be met as part of the definition of the extension. Applications
/// processing a resource are required to check for modifier extensions. Modifier
/// extensions SHALL NOT change the meaning of any elements on Resource or
/// DomainResource (including cannot change the meaning of modifierExtension
/// itself).
pub fn modifier_extension(&self) -> Option<Vec<Extension>> {
if let Some(Value::Array(val)) = self.value.get("modifierExtension") {
return Some(
val.into_iter()
.map(|e| Extension {
value: Cow::Borrowed(e),
})
.collect::<Vec<_>>(),
);
}
return None;
}
/// The diagnostic service that is responsible for issuing the report.
pub fn performer(&self) -> Option<Vec<Reference>> {
if let Some(Value::Array(val)) = self.value.get("performer") {
return Some(
val.into_iter()
.map(|e| Reference {
value: Cow::Borrowed(e),
})
.collect::<Vec<_>>(),
);
}
return None;
}
/// Rich text representation of the entire result as issued by the diagnostic
/// service. Multiple formats are allowed but they SHALL be semantically equivalent.
pub fn presented_form(&self) -> Option<Vec<Attachment>> {
if let Some(Value::Array(val)) = self.value.get("presentedForm") {
return Some(
val.into_iter()
.map(|e| Attachment {
value: Cow::Borrowed(e),
})
.collect::<Vec<_>>(),
);
}
return None;
}
/// [Observations](observation.html) that are part of this diagnostic report.
pub fn result(&self) -> Option<Vec<Reference>> {
if let Some(Value::Array(val)) = self.value.get("result") {
return Some(
val.into_iter()
.map(|e| Reference {
value: Cow::Borrowed(e),
})
.collect::<Vec<_>>(),
);
}
return None;
}
/// The practitioner or organization that is responsible for the report's
/// conclusions and interpretations.
pub fn results_interpreter(&self) -> Option<Vec<Reference>> {
if let Some(Value::Array(val)) = self.value.get("resultsInterpreter") {
return Some(
val.into_iter()
.map(|e| Reference {
value: Cow::Borrowed(e),
})
.collect::<Vec<_>>(),
);
}
return None;
}
/// Details about the specimens on which this diagnostic report is based.
pub fn specimen(&self) -> Option<Vec<Reference>> {
if let Some(Value::Array(val)) = self.value.get("specimen") {
return Some(
val.into_iter()
.map(|e| Reference {
value: Cow::Borrowed(e),
})
.collect::<Vec<_>>(),
);
}
return None;
}
/// The status of the diagnostic report.
pub fn status(&self) -> Option<DiagnosticReportStatus> {
if let Some(Value::String(val)) = self.value.get("status") {
return Some(DiagnosticReportStatus::from_string(&val).unwrap());
}
return None;
}
/// The subject of the report. Usually, but not always, this is a patient. However,
/// diagnostic services also perform analyses on specimens collected from a variety
/// of other sources.
pub fn subject(&self) -> Option<Reference> {
if let Some(val) = self.value.get("subject") {
return Some(Reference {
value: Cow::Borrowed(val),
});
}
return None;
}
/// A human-readable narrative that contains a summary of the resource and can be
/// used to represent the content of the resource to a human. The narrative need not
/// encode all the structured data, but is required to contain sufficient detail to
/// make it "clinically safe" for a human to just read the narrative. Resource
/// definitions may define what content should be represented in the narrative to
/// ensure clinical safety.
pub fn text(&self) -> Option<Narrative> {
if let Some(val) = self.value.get("text") {
return Some(Narrative {
value: Cow::Borrowed(val),
});
}
return None;
}
pub fn validate(&self) -> bool {
if let Some(_val) = self._conclusion() {
if !_val.validate() {
return false;
}
}
if let Some(_val) = self._effective_date_time() {
if !_val.validate() {
return false;
}
}
if let Some(_val) = self._implicit_rules() {
if !_val.validate() {
return false;
}
}
if let Some(_val) = self._issued() {
if !_val.validate() {
return false;
}
}
if let Some(_val) = self._language() {
if !_val.validate() {
return false;
}
}
if let Some(_val) = self._status() {
if !_val.validate() {
return false;
}
}
if let Some(_val) = self.based_on() {
if !_val.into_iter().map(|e| e.validate()).all(|x| x == true) {
return false;
}
}
if let Some(_val) = self.category() {
if !_val.into_iter().map(|e| e.validate()).all(|x| x == true) {
return false;
}
}
if !self.code().validate() {
return false;
}
if let Some(_val) = self.conclusion() {}
if let Some(_val) = self.conclusion_code() {
if !_val.into_iter().map(|e| e.validate()).all(|x| x == true) {
return false;
}
}
if let Some(_val) = self.contained() {
if !_val.into_iter().map(|e| e.validate()).all(|x| x == true) {
return false;
}
}
if let Some(_val) = self.effective_date_time() {}
if let Some(_val) = self.effective_period() {
if !_val.validate() {
return false;
}
}
if let Some(_val) = self.encounter() {
if !_val.validate() {
return false;
}
}
if let Some(_val) = self.extension() {
if !_val.into_iter().map(|e| e.validate()).all(|x| x == true) {
return false;
}
}
if let Some(_val) = self.id() {}
if let Some(_val) = self.identifier() {
if !_val.into_iter().map(|e| e.validate()).all(|x| x == true) {
return false;
}
}
if let Some(_val) = self.imaging_study() {
if !_val.into_iter().map(|e| e.validate()).all(|x| x == true) {
return false;
}
}
if let Some(_val) = self.implicit_rules() {}
if let Some(_val) = self.issued() {}
if let Some(_val) = self.language() {}
if let Some(_val) = self.media() {
if !_val.into_iter().map(|e| e.validate()).all(|x| x == true) {
return false;
}
}
if let Some(_val) = self.meta() {
if !_val.validate() {
return false;
}
}
if let Some(_val) = self.modifier_extension() {
if !_val.into_iter().map(|e| e.validate()).all(|x| x == true) {
return false;
}
}
if let Some(_val) = self.performer() {
if !_val.into_iter().map(|e| e.validate()).all(|x| x == true) {
return false;
}
}
if let Some(_val) = self.presented_form() {
if !_val.into_iter().map(|e| e.validate()).all(|x| x == true) {
return false;
}
}
if let Some(_val) = self.result() {
if !_val.into_iter().map(|e| e.validate()).all(|x| x == true) {
return false;
}
}
if let Some(_val) = self.results_interpreter() {
if !_val.into_iter().map(|e| e.validate()).all(|x| x == true) {
return false;
}
}
if let Some(_val) = self.specimen() {
if !_val.into_iter().map(|e| e.validate()).all(|x| x == true) {
return false;
}
}
if let Some(_val) = self.status() {}
if let Some(_val) = self.subject() {
if !_val.validate() {
return false;
}
}
if let Some(_val) = self.text() {
if !_val.validate() {
return false;
}
}
return true;
}
}
#[derive(Debug)]
pub struct DiagnosticReportBuilder {
pub(crate) value: Value,
}
impl DiagnosticReportBuilder {
pub fn build(&self) -> DiagnosticReport {
DiagnosticReport {
value: Cow::Owned(self.value.clone()),
}
}
pub fn with(existing: DiagnosticReport) -> DiagnosticReportBuilder {
DiagnosticReportBuilder {
value: (*existing.value).clone(),
}
}
pub fn new(code: CodeableConcept) -> DiagnosticReportBuilder {
let mut __value: Value = json!({});
__value["code"] = json!(code.value);
return DiagnosticReportBuilder { value: __value };
}
pub fn _conclusion<'a>(&'a mut self, val: Element) -> &'a mut DiagnosticReportBuilder {
self.value["_conclusion"] = json!(val.value);
return self;
}
pub fn _effective_date_time<'a>(&'a mut self, val: Element) -> &'a mut DiagnosticReportBuilder {
self.value["_effectiveDateTime"] = json!(val.value);
return self;
}
pub fn _implicit_rules<'a>(&'a mut self, val: Element) -> &'a mut DiagnosticReportBuilder {
self.value["_implicitRules"] = json!(val.value);
return self;
}
pub fn _issued<'a>(&'a mut self, val: Element) -> &'a mut DiagnosticReportBuilder {
self.value["_issued"] = json!(val.value);
return self;
}
pub fn _language<'a>(&'a mut self, val: Element) -> &'a mut DiagnosticReportBuilder {
self.value["_language"] = json!(val.value);
return self;
}
pub fn _status<'a>(&'a mut self, val: Element) -> &'a mut DiagnosticReportBuilder {
self.value["_status"] = json!(val.value);
return self;
}
pub fn based_on<'a>(&'a mut self, val: Vec<Reference>) -> &'a mut DiagnosticReportBuilder {
self.value["basedOn"] = json!(val.into_iter().map(|e| e.value).collect::<Vec<_>>());
return self;
}
pub fn category<'a>(
&'a mut self,
val: Vec<CodeableConcept>,
) -> &'a mut DiagnosticReportBuilder {
self.value["category"] = json!(val.into_iter().map(|e| e.value).collect::<Vec<_>>());
return self;
}
pub fn conclusion<'a>(&'a mut self, val: &str) -> &'a mut DiagnosticReportBuilder {
self.value["conclusion"] = json!(val);
return self;
}
pub fn conclusion_code<'a>(
&'a mut self,
val: Vec<CodeableConcept>,
) -> &'a mut DiagnosticReportBuilder {
self.value["conclusionCode"] = json!(val.into_iter().map(|e| e.value).collect::<Vec<_>>());
return self;
}
pub fn contained<'a>(&'a mut self, val: Vec<ResourceList>) -> &'a mut DiagnosticReportBuilder {
self.value["contained"] = json!(val.into_iter().map(|e| e.value).collect::<Vec<_>>());
return self;
}
pub fn effective_date_time<'a>(&'a mut self, val: &str) -> &'a mut DiagnosticReportBuilder {
self.value["effectiveDateTime"] = json!(val);
return self;
}
pub fn effective_period<'a>(&'a mut self, val: Period) -> &'a mut DiagnosticReportBuilder {
self.value["effectivePeriod"] = json!(val.value);
return self;
}
pub fn encounter<'a>(&'a mut self, val: Reference) -> &'a mut DiagnosticReportBuilder {
self.value["encounter"] = json!(val.value);
return self;
}
pub fn extension<'a>(&'a mut self, val: Vec<Extension>) -> &'a mut DiagnosticReportBuilder {
self.value["extension"] = json!(val.into_iter().map(|e| e.value).collect::<Vec<_>>());
return self;
}
pub fn id<'a>(&'a mut self, val: &str) -> &'a mut DiagnosticReportBuilder {
self.value["id"] = json!(val);
return self;
}
pub fn identifier<'a>(&'a mut self, val: Vec<Identifier>) -> &'a mut DiagnosticReportBuilder {
self.value["identifier"] = json!(val.into_iter().map(|e| e.value).collect::<Vec<_>>());
return self;
}
pub fn imaging_study<'a>(&'a mut self, val: Vec<Reference>) -> &'a mut DiagnosticReportBuilder {
self.value["imagingStudy"] = json!(val.into_iter().map(|e| e.value).collect::<Vec<_>>());
return self;
}
pub fn implicit_rules<'a>(&'a mut self, val: &str) -> &'a mut DiagnosticReportBuilder {
self.value["implicitRules"] = json!(val);
return self;
}
pub fn issued<'a>(&'a mut self, val: &str) -> &'a mut DiagnosticReportBuilder {
self.value["issued"] = json!(val);
return self;
}
pub fn language<'a>(&'a mut self, val: &str) -> &'a mut DiagnosticReportBuilder {
self.value["language"] = json!(val);
return self;
}
pub fn media<'a>(
&'a mut self,
val: Vec<DiagnosticReport_Media>,
) -> &'a mut DiagnosticReportBuilder {
self.value["media"] = json!(val.into_iter().map(|e| e.value).collect::<Vec<_>>());
return self;
}
pub fn meta<'a>(&'a mut self, val: Meta) -> &'a mut DiagnosticReportBuilder {
self.value["meta"] = json!(val.value);
return self;
}
pub fn modifier_extension<'a>(
&'a mut self,
val: Vec<Extension>,
) -> &'a mut DiagnosticReportBuilder {
self.value["modifierExtension"] =
json!(val.into_iter().map(|e| e.value).collect::<Vec<_>>());
return self;
}
pub fn performer<'a>(&'a mut self, val: Vec<Reference>) -> &'a mut DiagnosticReportBuilder {
self.value["performer"] = json!(val.into_iter().map(|e| e.value).collect::<Vec<_>>());
return self;
}
pub fn presented_form<'a>(
&'a mut self,
val: Vec<Attachment>,
) -> &'a mut DiagnosticReportBuilder {
self.value["presentedForm"] = json!(val.into_iter().map(|e| e.value).collect::<Vec<_>>());
return self;
}
pub fn result<'a>(&'a mut self, val: Vec<Reference>) -> &'a mut DiagnosticReportBuilder {
self.value["result"] = json!(val.into_iter().map(|e| e.value).collect::<Vec<_>>());
return self;
}
pub fn results_interpreter<'a>(
&'a mut self,
val: Vec<Reference>,
) -> &'a mut DiagnosticReportBuilder {
self.value["resultsInterpreter"] =
json!(val.into_iter().map(|e| e.value).collect::<Vec<_>>());
return self;
}
pub fn specimen<'a>(&'a mut self, val: Vec<Reference>) -> &'a mut DiagnosticReportBuilder {
self.value["specimen"] = json!(val.into_iter().map(|e| e.value).collect::<Vec<_>>());
return self;
}
pub fn status<'a>(
&'a mut self,
val: DiagnosticReportStatus,
) -> &'a mut DiagnosticReportBuilder {
self.value["status"] = json!(val.to_string());
return self;
}
pub fn subject<'a>(&'a mut self, val: Reference) -> &'a mut DiagnosticReportBuilder {
self.value["subject"] = json!(val.value);
return self;
}
pub fn text<'a>(&'a mut self, val: Narrative) -> &'a mut DiagnosticReportBuilder {
self.value["text"] = json!(val.value);
return self;
}
}
#[derive(Debug)]
pub enum DiagnosticReportStatus {
Registered,
Partial,
Preliminary,
Final,
Amended,
Corrected,
Appended,
Cancelled,
EnteredInError,
Unknown,
}
impl DiagnosticReportStatus {
pub fn from_string(string: &str) -> Option<DiagnosticReportStatus> {
match string {
"registered" => Some(DiagnosticReportStatus::Registered),
"partial" => Some(DiagnosticReportStatus::Partial),
"preliminary" => Some(DiagnosticReportStatus::Preliminary),
"final" => Some(DiagnosticReportStatus::Final),
"amended" => Some(DiagnosticReportStatus::Amended),
"corrected" => Some(DiagnosticReportStatus::Corrected),
"appended" => Some(DiagnosticReportStatus::Appended),
"cancelled" => Some(DiagnosticReportStatus::Cancelled),
"entered-in-error" => Some(DiagnosticReportStatus::EnteredInError),
"unknown" => Some(DiagnosticReportStatus::Unknown),
_ => None,
}
}
pub fn to_string(&self) -> String {
match self {
DiagnosticReportStatus::Registered => "registered".to_string(),
DiagnosticReportStatus::Partial => "partial".to_string(),
DiagnosticReportStatus::Preliminary => "preliminary".to_string(),
DiagnosticReportStatus::Final => "final".to_string(),
DiagnosticReportStatus::Amended => "amended".to_string(),
DiagnosticReportStatus::Corrected => "corrected".to_string(),
DiagnosticReportStatus::Appended => "appended".to_string(),
DiagnosticReportStatus::Cancelled => "cancelled".to_string(),
DiagnosticReportStatus::EnteredInError => "entered-in-error".to_string(),
DiagnosticReportStatus::Unknown => "unknown".to_string(),
}
}
}
| true
|
1935a6a9de43b5c9db0957700b41dce0fe326d4e
|
Rust
|
dangerousplay/file-server
|
/client/src/main.rs
|
UTF-8
| 3,168
| 2.75
| 3
|
[] |
no_license
|
use cursive::views::{Dialog, TextView, ListView, SelectView, TextArea};
use tokio::net::{TcpStream, ToSocketAddrs};
use std::io;
use std::borrow::Cow;
use futures::stream::StreamExt;
use tokio_util::codec::{FramedRead, FramedWrite};
use tokio::net::tcp::{WriteHalf, ReadHalf, OwnedReadHalf, OwnedWriteHalf};
use core::protocol::protocol::{ProtocolResponseCodec, ProtocolOperationCodec, Operation, ProtocolError, Response};
use futures::SinkExt;
use cursive::view::Nameable;
use std::sync::{Mutex, Arc};
use tokio::sync::RwLock;
pub struct Client {
read: FramedRead<OwnedReadHalf, ProtocolResponseCodec>,
write: FramedWrite<OwnedWriteHalf, ProtocolOperationCodec>
}
impl Client {
pub async fn new<T: ToSocketAddrs>(addr: T) -> io::Result<Self> {
let socket = TcpStream::connect(addr).await?;
let (read, write) = socket.into_split();
let read = FramedRead::new(read, ProtocolResponseCodec);
let write = FramedWrite::new(write, ProtocolOperationCodec);
Ok(Self {
read,
write
})
}
pub async fn list_files(&mut self) -> Result<Vec<String>, ProtocolError> {
self.write.send(Operation::ListOperation).await?;
match self.read.next().await.unwrap()? {
Response::ListOperation {
files
} => Ok(files),
_ => unreachable!()
}
}
pub async fn download_file<F: Into<Cow<'static, str>>>(&mut self, file: F) -> Result<String, ProtocolError> {
self.write.send(Operation::GetOperation { path: file.into() }).await?;
match self.read.next().await.unwrap()? {
Response::GetOperation {
content
} => Ok(content.to_string()),
_ => unreachable!()
}
}
}
#[tokio::main]
async fn main() -> io::Result<()> {
let mut siv = cursive::default();
let client = Arc::new(RwLock::new(Client::new("127.0.0.1:4474").await?));
let files = client.write().await.list_files().await.unwrap().into_iter().map(|f| (f.clone(),f));
let select_view = SelectView::<String>::new()
.with_all(files)
.on_submit(move |s, f: &str | {
let f = f.to_owned();
let cb = s.cb_sink().clone();
let client = client.clone();
tokio::spawn(async move {
let content = client.write().await.download_file(f.clone()).await.unwrap();
cb.send(Box::new(move |v|
v.add_layer(
Dialog::around(TextArea::new().content(content))
.title(f.clone())
.button("Close", |s| {
s.pop_layer();
})
)
));
});
});
let dialog_name = "dialog";
// Creates a dialog with a single "Quit" button
siv.add_layer(Dialog::around(TextView::new("Files"))
.title("Files on the server")
.content(select_view)
.button("Quit", |s| s.quit())
.with_name(dialog_name)
);
// Starts the event loop.
siv.run();
Ok(())
}
| true
|
2b0f73567427a4f207fa8ab5216a42e0ab853727
|
Rust
|
rv32m1-rust/rv32m1_ri5cy-pac
|
/src/lptmr0/csr.rs
|
UTF-8
| 18,779
| 2.53125
| 3
|
[
"Apache-2.0",
"MIT"
] |
permissive
|
#[doc = "Reader of register CSR"]
pub type R = crate::R<u32, super::CSR>;
#[doc = "Writer for register CSR"]
pub type W = crate::W<u32, super::CSR>;
#[doc = "Register CSR `reset()`'s with value 0"]
impl crate::ResetValue for super::CSR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Timer Enable\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TEN_A {
#[doc = "0: LPTMR is disabled and internal logic is reset."]
TEN_0,
#[doc = "1: LPTMR is enabled."]
TEN_1,
}
impl From<TEN_A> for bool {
#[inline(always)]
fn from(variant: TEN_A) -> Self {
match variant {
TEN_A::TEN_0 => false,
TEN_A::TEN_1 => true,
}
}
}
#[doc = "Reader of field `TEN`"]
pub type TEN_R = crate::R<bool, TEN_A>;
impl TEN_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> TEN_A {
match self.bits {
false => TEN_A::TEN_0,
true => TEN_A::TEN_1,
}
}
#[doc = "Checks if the value of the field is `TEN_0`"]
#[inline(always)]
pub fn is_ten_0(&self) -> bool {
*self == TEN_A::TEN_0
}
#[doc = "Checks if the value of the field is `TEN_1`"]
#[inline(always)]
pub fn is_ten_1(&self) -> bool {
*self == TEN_A::TEN_1
}
}
#[doc = "Write proxy for field `TEN`"]
pub struct TEN_W<'a> {
w: &'a mut W,
}
impl<'a> TEN_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: TEN_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "LPTMR is disabled and internal logic is reset."]
#[inline(always)]
pub fn ten_0(self) -> &'a mut W {
self.variant(TEN_A::TEN_0)
}
#[doc = "LPTMR is enabled."]
#[inline(always)]
pub fn ten_1(self) -> &'a mut W {
self.variant(TEN_A::TEN_1)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01);
self.w
}
}
#[doc = "Timer Mode Select\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TMS_A {
#[doc = "0: Time Counter mode."]
TMS_0,
#[doc = "1: Pulse Counter mode."]
TMS_1,
}
impl From<TMS_A> for bool {
#[inline(always)]
fn from(variant: TMS_A) -> Self {
match variant {
TMS_A::TMS_0 => false,
TMS_A::TMS_1 => true,
}
}
}
#[doc = "Reader of field `TMS`"]
pub type TMS_R = crate::R<bool, TMS_A>;
impl TMS_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> TMS_A {
match self.bits {
false => TMS_A::TMS_0,
true => TMS_A::TMS_1,
}
}
#[doc = "Checks if the value of the field is `TMS_0`"]
#[inline(always)]
pub fn is_tms_0(&self) -> bool {
*self == TMS_A::TMS_0
}
#[doc = "Checks if the value of the field is `TMS_1`"]
#[inline(always)]
pub fn is_tms_1(&self) -> bool {
*self == TMS_A::TMS_1
}
}
#[doc = "Write proxy for field `TMS`"]
pub struct TMS_W<'a> {
w: &'a mut W,
}
impl<'a> TMS_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: TMS_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Time Counter mode."]
#[inline(always)]
pub fn tms_0(self) -> &'a mut W {
self.variant(TMS_A::TMS_0)
}
#[doc = "Pulse Counter mode."]
#[inline(always)]
pub fn tms_1(self) -> &'a mut W {
self.variant(TMS_A::TMS_1)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1);
self.w
}
}
#[doc = "Timer Free-Running Counter\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TFC_A {
#[doc = "0: CNR is reset whenever TCF is set."]
TFC_0,
#[doc = "1: CNR is reset on overflow."]
TFC_1,
}
impl From<TFC_A> for bool {
#[inline(always)]
fn from(variant: TFC_A) -> Self {
match variant {
TFC_A::TFC_0 => false,
TFC_A::TFC_1 => true,
}
}
}
#[doc = "Reader of field `TFC`"]
pub type TFC_R = crate::R<bool, TFC_A>;
impl TFC_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> TFC_A {
match self.bits {
false => TFC_A::TFC_0,
true => TFC_A::TFC_1,
}
}
#[doc = "Checks if the value of the field is `TFC_0`"]
#[inline(always)]
pub fn is_tfc_0(&self) -> bool {
*self == TFC_A::TFC_0
}
#[doc = "Checks if the value of the field is `TFC_1`"]
#[inline(always)]
pub fn is_tfc_1(&self) -> bool {
*self == TFC_A::TFC_1
}
}
#[doc = "Write proxy for field `TFC`"]
pub struct TFC_W<'a> {
w: &'a mut W,
}
impl<'a> TFC_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: TFC_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "CNR is reset whenever TCF is set."]
#[inline(always)]
pub fn tfc_0(self) -> &'a mut W {
self.variant(TFC_A::TFC_0)
}
#[doc = "CNR is reset on overflow."]
#[inline(always)]
pub fn tfc_1(self) -> &'a mut W {
self.variant(TFC_A::TFC_1)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2);
self.w
}
}
#[doc = "Timer Pin Polarity\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TPP_A {
#[doc = "0: Pulse Counter input source is active-high, and the CNR will increment on the rising-edge."]
TPP_0,
#[doc = "1: Pulse Counter input source is active-low, and the CNR will increment on the falling-edge."]
TPP_1,
}
impl From<TPP_A> for bool {
#[inline(always)]
fn from(variant: TPP_A) -> Self {
match variant {
TPP_A::TPP_0 => false,
TPP_A::TPP_1 => true,
}
}
}
#[doc = "Reader of field `TPP`"]
pub type TPP_R = crate::R<bool, TPP_A>;
impl TPP_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> TPP_A {
match self.bits {
false => TPP_A::TPP_0,
true => TPP_A::TPP_1,
}
}
#[doc = "Checks if the value of the field is `TPP_0`"]
#[inline(always)]
pub fn is_tpp_0(&self) -> bool {
*self == TPP_A::TPP_0
}
#[doc = "Checks if the value of the field is `TPP_1`"]
#[inline(always)]
pub fn is_tpp_1(&self) -> bool {
*self == TPP_A::TPP_1
}
}
#[doc = "Write proxy for field `TPP`"]
pub struct TPP_W<'a> {
w: &'a mut W,
}
impl<'a> TPP_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: TPP_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Pulse Counter input source is active-high, and the CNR will increment on the rising-edge."]
#[inline(always)]
pub fn tpp_0(self) -> &'a mut W {
self.variant(TPP_A::TPP_0)
}
#[doc = "Pulse Counter input source is active-low, and the CNR will increment on the falling-edge."]
#[inline(always)]
pub fn tpp_1(self) -> &'a mut W {
self.variant(TPP_A::TPP_1)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3);
self.w
}
}
#[doc = "Timer Pin Select\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TPS_A {
#[doc = "0: Pulse counter input 0 is selected."]
TPS_0,
#[doc = "1: Pulse counter input 1 is selected."]
TPS_1,
#[doc = "2: Pulse counter input 2 is selected."]
TPS_2,
#[doc = "3: Pulse counter input 3 is selected."]
TPS_3,
}
impl From<TPS_A> for u8 {
#[inline(always)]
fn from(variant: TPS_A) -> Self {
match variant {
TPS_A::TPS_0 => 0,
TPS_A::TPS_1 => 1,
TPS_A::TPS_2 => 2,
TPS_A::TPS_3 => 3,
}
}
}
#[doc = "Reader of field `TPS`"]
pub type TPS_R = crate::R<u8, TPS_A>;
impl TPS_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> TPS_A {
match self.bits {
0 => TPS_A::TPS_0,
1 => TPS_A::TPS_1,
2 => TPS_A::TPS_2,
3 => TPS_A::TPS_3,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `TPS_0`"]
#[inline(always)]
pub fn is_tps_0(&self) -> bool {
*self == TPS_A::TPS_0
}
#[doc = "Checks if the value of the field is `TPS_1`"]
#[inline(always)]
pub fn is_tps_1(&self) -> bool {
*self == TPS_A::TPS_1
}
#[doc = "Checks if the value of the field is `TPS_2`"]
#[inline(always)]
pub fn is_tps_2(&self) -> bool {
*self == TPS_A::TPS_2
}
#[doc = "Checks if the value of the field is `TPS_3`"]
#[inline(always)]
pub fn is_tps_3(&self) -> bool {
*self == TPS_A::TPS_3
}
}
#[doc = "Write proxy for field `TPS`"]
pub struct TPS_W<'a> {
w: &'a mut W,
}
impl<'a> TPS_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: TPS_A) -> &'a mut W {
{
self.bits(variant.into())
}
}
#[doc = "Pulse counter input 0 is selected."]
#[inline(always)]
pub fn tps_0(self) -> &'a mut W {
self.variant(TPS_A::TPS_0)
}
#[doc = "Pulse counter input 1 is selected."]
#[inline(always)]
pub fn tps_1(self) -> &'a mut W {
self.variant(TPS_A::TPS_1)
}
#[doc = "Pulse counter input 2 is selected."]
#[inline(always)]
pub fn tps_2(self) -> &'a mut W {
self.variant(TPS_A::TPS_2)
}
#[doc = "Pulse counter input 3 is selected."]
#[inline(always)]
pub fn tps_3(self) -> &'a mut W {
self.variant(TPS_A::TPS_3)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x03 << 4)) | (((value as u32) & 0x03) << 4);
self.w
}
}
#[doc = "Timer Interrupt Enable\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TIE_A {
#[doc = "0: Timer interrupt disabled."]
TIE_0,
#[doc = "1: Timer interrupt enabled."]
TIE_1,
}
impl From<TIE_A> for bool {
#[inline(always)]
fn from(variant: TIE_A) -> Self {
match variant {
TIE_A::TIE_0 => false,
TIE_A::TIE_1 => true,
}
}
}
#[doc = "Reader of field `TIE`"]
pub type TIE_R = crate::R<bool, TIE_A>;
impl TIE_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> TIE_A {
match self.bits {
false => TIE_A::TIE_0,
true => TIE_A::TIE_1,
}
}
#[doc = "Checks if the value of the field is `TIE_0`"]
#[inline(always)]
pub fn is_tie_0(&self) -> bool {
*self == TIE_A::TIE_0
}
#[doc = "Checks if the value of the field is `TIE_1`"]
#[inline(always)]
pub fn is_tie_1(&self) -> bool {
*self == TIE_A::TIE_1
}
}
#[doc = "Write proxy for field `TIE`"]
pub struct TIE_W<'a> {
w: &'a mut W,
}
impl<'a> TIE_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: TIE_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Timer interrupt disabled."]
#[inline(always)]
pub fn tie_0(self) -> &'a mut W {
self.variant(TIE_A::TIE_0)
}
#[doc = "Timer interrupt enabled."]
#[inline(always)]
pub fn tie_1(self) -> &'a mut W {
self.variant(TIE_A::TIE_1)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 6)) | (((value as u32) & 0x01) << 6);
self.w
}
}
#[doc = "Timer Compare Flag\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TCF_A {
#[doc = "0: The value of CNR is not equal to CMR and increments."]
TCF_0,
#[doc = "1: The value of CNR is equal to CMR and increments."]
TCF_1,
}
impl From<TCF_A> for bool {
#[inline(always)]
fn from(variant: TCF_A) -> Self {
match variant {
TCF_A::TCF_0 => false,
TCF_A::TCF_1 => true,
}
}
}
#[doc = "Reader of field `TCF`"]
pub type TCF_R = crate::R<bool, TCF_A>;
impl TCF_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> TCF_A {
match self.bits {
false => TCF_A::TCF_0,
true => TCF_A::TCF_1,
}
}
#[doc = "Checks if the value of the field is `TCF_0`"]
#[inline(always)]
pub fn is_tcf_0(&self) -> bool {
*self == TCF_A::TCF_0
}
#[doc = "Checks if the value of the field is `TCF_1`"]
#[inline(always)]
pub fn is_tcf_1(&self) -> bool {
*self == TCF_A::TCF_1
}
}
#[doc = "Write proxy for field `TCF`"]
pub struct TCF_W<'a> {
w: &'a mut W,
}
impl<'a> TCF_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: TCF_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "The value of CNR is not equal to CMR and increments."]
#[inline(always)]
pub fn tcf_0(self) -> &'a mut W {
self.variant(TCF_A::TCF_0)
}
#[doc = "The value of CNR is equal to CMR and increments."]
#[inline(always)]
pub fn tcf_1(self) -> &'a mut W {
self.variant(TCF_A::TCF_1)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 7)) | (((value as u32) & 0x01) << 7);
self.w
}
}
#[doc = "Timer DMA Request Enable\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TDRE_A {
#[doc = "0: Timer DMA Request disabled."]
TDRE_0,
#[doc = "1: Timer DMA Request enabled."]
TDRE_1,
}
impl From<TDRE_A> for bool {
#[inline(always)]
fn from(variant: TDRE_A) -> Self {
match variant {
TDRE_A::TDRE_0 => false,
TDRE_A::TDRE_1 => true,
}
}
}
#[doc = "Reader of field `TDRE`"]
pub type TDRE_R = crate::R<bool, TDRE_A>;
impl TDRE_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> TDRE_A {
match self.bits {
false => TDRE_A::TDRE_0,
true => TDRE_A::TDRE_1,
}
}
#[doc = "Checks if the value of the field is `TDRE_0`"]
#[inline(always)]
pub fn is_tdre_0(&self) -> bool {
*self == TDRE_A::TDRE_0
}
#[doc = "Checks if the value of the field is `TDRE_1`"]
#[inline(always)]
pub fn is_tdre_1(&self) -> bool {
*self == TDRE_A::TDRE_1
}
}
#[doc = "Write proxy for field `TDRE`"]
pub struct TDRE_W<'a> {
w: &'a mut W,
}
impl<'a> TDRE_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: TDRE_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Timer DMA Request disabled."]
#[inline(always)]
pub fn tdre_0(self) -> &'a mut W {
self.variant(TDRE_A::TDRE_0)
}
#[doc = "Timer DMA Request enabled."]
#[inline(always)]
pub fn tdre_1(self) -> &'a mut W {
self.variant(TDRE_A::TDRE_1)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8);
self.w
}
}
impl R {
#[doc = "Bit 0 - Timer Enable"]
#[inline(always)]
pub fn ten(&self) -> TEN_R {
TEN_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - Timer Mode Select"]
#[inline(always)]
pub fn tms(&self) -> TMS_R {
TMS_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 2 - Timer Free-Running Counter"]
#[inline(always)]
pub fn tfc(&self) -> TFC_R {
TFC_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 3 - Timer Pin Polarity"]
#[inline(always)]
pub fn tpp(&self) -> TPP_R {
TPP_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bits 4:5 - Timer Pin Select"]
#[inline(always)]
pub fn tps(&self) -> TPS_R {
TPS_R::new(((self.bits >> 4) & 0x03) as u8)
}
#[doc = "Bit 6 - Timer Interrupt Enable"]
#[inline(always)]
pub fn tie(&self) -> TIE_R {
TIE_R::new(((self.bits >> 6) & 0x01) != 0)
}
#[doc = "Bit 7 - Timer Compare Flag"]
#[inline(always)]
pub fn tcf(&self) -> TCF_R {
TCF_R::new(((self.bits >> 7) & 0x01) != 0)
}
#[doc = "Bit 8 - Timer DMA Request Enable"]
#[inline(always)]
pub fn tdre(&self) -> TDRE_R {
TDRE_R::new(((self.bits >> 8) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - Timer Enable"]
#[inline(always)]
pub fn ten(&mut self) -> TEN_W {
TEN_W { w: self }
}
#[doc = "Bit 1 - Timer Mode Select"]
#[inline(always)]
pub fn tms(&mut self) -> TMS_W {
TMS_W { w: self }
}
#[doc = "Bit 2 - Timer Free-Running Counter"]
#[inline(always)]
pub fn tfc(&mut self) -> TFC_W {
TFC_W { w: self }
}
#[doc = "Bit 3 - Timer Pin Polarity"]
#[inline(always)]
pub fn tpp(&mut self) -> TPP_W {
TPP_W { w: self }
}
#[doc = "Bits 4:5 - Timer Pin Select"]
#[inline(always)]
pub fn tps(&mut self) -> TPS_W {
TPS_W { w: self }
}
#[doc = "Bit 6 - Timer Interrupt Enable"]
#[inline(always)]
pub fn tie(&mut self) -> TIE_W {
TIE_W { w: self }
}
#[doc = "Bit 7 - Timer Compare Flag"]
#[inline(always)]
pub fn tcf(&mut self) -> TCF_W {
TCF_W { w: self }
}
#[doc = "Bit 8 - Timer DMA Request Enable"]
#[inline(always)]
pub fn tdre(&mut self) -> TDRE_W {
TDRE_W { w: self }
}
}
| true
|
adf9779c7c5700aa950fe59d81bf2a220fe6a896
|
Rust
|
LukeMathWalker/build-your-own-jira-with-rust
|
/jira-wip/src/koans/01_ticket/07_derive.rs
|
UTF-8
| 1,535
| 3.46875
| 3
|
[
"MIT"
] |
permissive
|
/// Cool, we learned what a trait is and how to implement one.
/// I am sure you agree with us though: implementing PartialEq was quite tedious
/// and repetitive, a computer can surely do a better job without having to trouble us!
///
/// The Rust team feels your pain, hence a handy feature: derive macros.
/// Derive macros are a code-generation tool: before code compilation kicks-in, derive
/// macros take as input the code they have been applied to (as a stream of tokens!)
/// and they have a chance to generate other code, as needed.
///
/// For example, this `#[derive(PartialEq)]` will take as input the definition of our
/// enum and generate an implementation of PartialEq which is exactly equivalent to
/// the one we rolled out manually in the previous koan.
/// You can check the code generated by derive macros using `cargo expand`:
/// https://github.com/dtolnay/cargo-expand
///
/// ```sh
/// cargo install cargo-expand
/// cargo expand -p jira-wip path_to_enlightenment::derive
/// ```
///
/// PartialEq is not the only trait whose implementation can be derived automatically!
#[derive(PartialEq)]
pub enum Status {
ToDo,
InProgress,
Blocked,
Done,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn assertions() {
// Your goal is to make this test compile.
assert_eq!(Status::ToDo, Status::ToDo);
assert_ne!(Status::Done, Status::ToDo);
assert_ne!(Status::InProgress, Status::ToDo);
assert_eq!(Status::InProgress, Status::InProgress);
}
}
| true
|
7d81dbbac059a51f2a747a61cbe2f6a4aa3a730d
|
Rust
|
cyber-meow/ReactiveRs
|
/src/signal/valued_signal/emit.rs
|
UTF-8
| 2,483
| 2.984375
| 3
|
[
"MIT"
] |
permissive
|
use runtime::{Runtime, SingleThreadRuntime, ParallelRuntime};
use continuation::{ContinuationSt, ContinuationPl};
use process::{Process, ProcessMut, ProcessSt, ProcessMutSt};
use process::{ProcessPl, ProcessMutPl, ConstraintOnValue};
use signal::signal_runtime::SignalRuntimeRefBase;
use signal::ValuedSignal;
/// Process that represents an emission of a signal with some value.
pub struct EmitValue<S, A> {
pub(crate) signal: S,
pub(crate) emitted: A,
}
impl<S, A> Process for EmitValue<S, A> where S: ValuedSignal, A: 'static {
type Value = ();
}
impl<S, A> ProcessMut for EmitValue<S, A> where S: ValuedSignal, A: 'static {}
pub trait CanEmit<R, A>: SignalRuntimeRefBase<R> where R: Runtime {
/// Emits the value `emitted` to the signal.
fn emit(&mut self, runtime: &mut R, emitted: A);
}
// Non-parallel
impl<S, A> ProcessSt for EmitValue<S, A>
where S: ValuedSignal, S::RuntimeRef: CanEmit<SingleThreadRuntime, A>, A: 'static
{
fn call<C>(self, runtime: &mut SingleThreadRuntime, next: C)
where C: ContinuationSt<Self::Value>
{
self.signal.runtime().emit(runtime, self.emitted);
next.call(runtime, ());
}
}
impl<S, A> ProcessMutSt for EmitValue<S, A>
where S: ValuedSignal, S::RuntimeRef: CanEmit<SingleThreadRuntime, A>, A: Clone + 'static
{
fn call_mut<C>(self, runtime: &mut SingleThreadRuntime, next: C)
where Self: Sized, C: ContinuationSt<(Self, Self::Value)>
{
self.signal.runtime().emit(runtime, self.emitted.clone());
next.call(runtime, (self, ()));
}
}
// Parallel
impl<S, A> ConstraintOnValue for EmitValue<S, A> {
type T = ();
}
impl<S, A> ProcessPl for EmitValue<S, A>
where S: ValuedSignal + Send + Sync,
S::RuntimeRef: CanEmit<ParallelRuntime, A>,
A: Send + Sync + 'static,
{
fn call<C>(self, runtime: &mut ParallelRuntime, next: C)
where C: ContinuationPl<Self::Value>
{
self.signal.runtime().emit(runtime, self.emitted);
next.call(runtime, ());
}
}
impl<S, A> ProcessMutPl for EmitValue<S, A>
where S: ValuedSignal + Send + Sync,
S::RuntimeRef: CanEmit<ParallelRuntime, A>,
A: Clone + Send + Sync + 'static,
{
fn call_mut<C>(self, runtime: &mut ParallelRuntime, next: C)
where Self: Sized, C: ContinuationPl<(Self, Self::Value)>
{
self.signal.runtime().emit(runtime, self.emitted.clone());
next.call(runtime, (self, ()));
}
}
| true
|
531451e2c9f46849812ee5481655ff72130fcc4f
|
Rust
|
binh-vu/rython
|
/src/types/and_semantic.rs
|
UTF-8
| 772
| 2.875
| 3
|
[] |
no_license
|
use std::borrow::Cow;
use crate::types::Str;
pub trait AndSemantic<RHS=Self> {
fn and(self, rhs: RHS) -> Self;
}
impl AndSemantic for bool {
fn and(self, rhs: bool) -> Self {
self && rhs
}
}
impl AndSemantic for Str {
fn and(self, rhs: Str) -> Self {
unimplemented!()
}
}
impl AndSemantic for i64 {
fn and(self, rhs: i64) -> Self {
unimplemented!()
}
}
impl AndSemantic for f64 {
fn and(self, rhs: f64) -> Self {
unimplemented!()
}
}
impl AndSemantic for Vec<Str> {
fn and(self, rhs: Vec<Str>) -> Self {
unimplemented!()
}
}
impl AndSemantic for Vec<i64> {
fn and(self, rhs: Vec<i64>) -> Self {
unimplemented!()
}
}
impl AndSemantic for Vec<f64> {
fn and(self, rhs: Vec<f64>) -> Self {
unimplemented!()
}
}
| true
|
9272c80c194d3a40478d1c6d604faebf55bf2541
|
Rust
|
solana-labs/solana
|
/accounts-db/src/storable_accounts.rs
|
UTF-8
| 23,475
| 3.046875
| 3
|
[
"Apache-2.0"
] |
permissive
|
//! trait for abstracting underlying storage of pubkey and account pairs to be written
use {
crate::{account_storage::meta::StoredAccountMeta, accounts_db::IncludeSlotInHash},
solana_sdk::{account::ReadableAccount, clock::Slot, hash::Hash, pubkey::Pubkey},
};
/// abstract access to pubkey, account, slot, target_slot of either:
/// a. (slot, &[&Pubkey, &ReadableAccount])
/// b. (slot, &[&Pubkey, &ReadableAccount, Slot]) (we will use this later)
/// This trait avoids having to allocate redundant data when there is a duplicated slot parameter.
/// All legacy callers do not have a unique slot per account to store.
pub trait StorableAccounts<'a, T: ReadableAccount + Sync>: Sync {
/// pubkey at 'index'
fn pubkey(&self, index: usize) -> &Pubkey;
/// account at 'index'
fn account(&self, index: usize) -> &T;
/// None if account is zero lamports
fn account_default_if_zero_lamport(&self, index: usize) -> Option<&T> {
let account = self.account(index);
(account.lamports() != 0).then_some(account)
}
// current slot for account at 'index'
fn slot(&self, index: usize) -> Slot;
/// slot that all accounts are to be written to
fn target_slot(&self) -> Slot;
/// true if no accounts to write
fn is_empty(&self) -> bool {
self.len() == 0
}
/// # accounts to write
fn len(&self) -> usize;
/// are there accounts from multiple slots
/// only used for an assert
fn contains_multiple_slots(&self) -> bool {
false
}
/// true iff hashing these accounts should include the slot
fn include_slot_in_hash(&self) -> IncludeSlotInHash;
/// true iff the impl can provide hash and write_version
/// Otherwise, hash and write_version have to be provided separately to store functions.
fn has_hash_and_write_version(&self) -> bool {
false
}
/// return hash for account at 'index'
/// Should only be called if 'has_hash_and_write_version' = true
fn hash(&self, _index: usize) -> &Hash {
// this should never be called if has_hash_and_write_version returns false
unimplemented!();
}
/// return write_version for account at 'index'
/// Should only be called if 'has_hash_and_write_version' = true
fn write_version(&self, _index: usize) -> u64 {
// this should never be called if has_hash_and_write_version returns false
unimplemented!();
}
}
/// accounts that are moving from 'old_slot' to 'target_slot'
/// since all accounts are from the same old slot, we don't need to create a slice with per-account slot
/// but, we need slot(_) to return 'old_slot' for all accounts
/// Created a struct instead of a tuple to make the code easier to read.
pub struct StorableAccountsMovingSlots<'a, T: ReadableAccount + Sync> {
pub accounts: &'a [(&'a Pubkey, &'a T)],
/// accounts will be written to this slot
pub target_slot: Slot,
/// slot where accounts are currently stored
pub old_slot: Slot,
/// This is temporarily here until feature activation.
pub include_slot_in_hash: IncludeSlotInHash,
}
impl<'a, T: ReadableAccount + Sync> StorableAccounts<'a, T> for StorableAccountsMovingSlots<'a, T> {
fn pubkey(&self, index: usize) -> &Pubkey {
self.accounts[index].0
}
fn account(&self, index: usize) -> &T {
self.accounts[index].1
}
fn slot(&self, _index: usize) -> Slot {
// per-index slot is not unique per slot, but it is different than 'target_slot'
self.old_slot
}
fn target_slot(&self) -> Slot {
self.target_slot
}
fn len(&self) -> usize {
self.accounts.len()
}
fn include_slot_in_hash(&self) -> IncludeSlotInHash {
self.include_slot_in_hash
}
}
/// The last parameter exists until this feature is activated:
/// ignore slot when calculating an account hash #28420
impl<'a, T: ReadableAccount + Sync> StorableAccounts<'a, T>
for (Slot, &'a [(&'a Pubkey, &'a T)], IncludeSlotInHash)
{
fn pubkey(&self, index: usize) -> &Pubkey {
self.1[index].0
}
fn account(&self, index: usize) -> &T {
self.1[index].1
}
fn slot(&self, _index: usize) -> Slot {
// per-index slot is not unique per slot when per-account slot is not included in the source data
self.target_slot()
}
fn target_slot(&self) -> Slot {
self.0
}
fn len(&self) -> usize {
self.1.len()
}
fn include_slot_in_hash(&self) -> IncludeSlotInHash {
self.2
}
}
#[allow(dead_code)]
/// The last parameter exists until this feature is activated:
/// ignore slot when calculating an account hash #28420
impl<'a, T: ReadableAccount + Sync> StorableAccounts<'a, T>
for (Slot, &'a [&'a (Pubkey, T)], IncludeSlotInHash)
{
fn pubkey(&self, index: usize) -> &Pubkey {
&self.1[index].0
}
fn account(&self, index: usize) -> &T {
&self.1[index].1
}
fn slot(&self, _index: usize) -> Slot {
// per-index slot is not unique per slot when per-account slot is not included in the source data
self.target_slot()
}
fn target_slot(&self) -> Slot {
self.0
}
fn len(&self) -> usize {
self.1.len()
}
fn include_slot_in_hash(&self) -> IncludeSlotInHash {
self.2
}
}
/// The last parameter exists until this feature is activated:
/// ignore slot when calculating an account hash #28420
impl<'a> StorableAccounts<'a, StoredAccountMeta<'a>>
for (Slot, &'a [&'a StoredAccountMeta<'a>], IncludeSlotInHash)
{
fn pubkey(&self, index: usize) -> &Pubkey {
self.account(index).pubkey()
}
fn account(&self, index: usize) -> &StoredAccountMeta<'a> {
self.1[index]
}
fn slot(&self, _index: usize) -> Slot {
// per-index slot is not unique per slot when per-account slot is not included in the source data
self.0
}
fn target_slot(&self) -> Slot {
self.0
}
fn len(&self) -> usize {
self.1.len()
}
fn include_slot_in_hash(&self) -> IncludeSlotInHash {
self.2
}
fn has_hash_and_write_version(&self) -> bool {
true
}
fn hash(&self, index: usize) -> &Hash {
self.account(index).hash()
}
fn write_version(&self, index: usize) -> u64 {
self.account(index).write_version()
}
}
/// holds slices of accounts being moved FROM a common source slot to 'target_slot'
pub struct StorableAccountsBySlot<'a> {
target_slot: Slot,
/// each element is (source slot, accounts moving FROM source slot)
slots_and_accounts: &'a [(Slot, &'a [&'a StoredAccountMeta<'a>])],
include_slot_in_hash: IncludeSlotInHash,
/// This is calculated based off slots_and_accounts.
/// cumulative offset of all account slices prior to this one
/// starting_offsets[0] is the starting offset of slots_and_accounts[1]
/// The starting offset of slots_and_accounts[0] is always 0
starting_offsets: Vec<usize>,
/// true if there is more than 1 slot represented in slots_and_accounts
contains_multiple_slots: bool,
/// total len of all accounts, across all slots_and_accounts
len: usize,
}
impl<'a> StorableAccountsBySlot<'a> {
#[allow(dead_code)]
/// each element of slots_and_accounts is (source slot, accounts moving FROM source slot)
pub fn new(
target_slot: Slot,
slots_and_accounts: &'a [(Slot, &'a [&'a StoredAccountMeta<'a>])],
include_slot_in_hash: IncludeSlotInHash,
) -> Self {
let mut cumulative_len = 0usize;
let mut starting_offsets = Vec::with_capacity(slots_and_accounts.len());
let first_slot = slots_and_accounts
.first()
.map(|(slot, _)| *slot)
.unwrap_or_default();
let mut contains_multiple_slots = false;
for (slot, accounts) in slots_and_accounts {
cumulative_len = cumulative_len.saturating_add(accounts.len());
starting_offsets.push(cumulative_len);
contains_multiple_slots |= &first_slot != slot;
}
Self {
target_slot,
slots_and_accounts,
starting_offsets,
include_slot_in_hash,
contains_multiple_slots,
len: cumulative_len,
}
}
/// given an overall index for all accounts in self:
/// return (slots_and_accounts index, index within those accounts)
fn find_internal_index(&self, index: usize) -> (usize, usize) {
// search offsets for the accounts slice that contains 'index'.
// This could be a binary search.
for (offset_index, next_offset) in self.starting_offsets.iter().enumerate() {
if next_offset > &index {
// offset of prior entry
let prior_offset = if offset_index > 0 {
self.starting_offsets[offset_index.saturating_sub(1)]
} else {
0
};
return (offset_index, index - prior_offset);
}
}
panic!("failed");
}
}
/// The last parameter exists until this feature is activated:
/// ignore slot when calculating an account hash #28420
impl<'a> StorableAccounts<'a, StoredAccountMeta<'a>> for StorableAccountsBySlot<'a> {
fn pubkey(&self, index: usize) -> &Pubkey {
self.account(index).pubkey()
}
fn account(&self, index: usize) -> &StoredAccountMeta<'a> {
let indexes = self.find_internal_index(index);
self.slots_and_accounts[indexes.0].1[indexes.1]
}
fn slot(&self, index: usize) -> Slot {
let indexes = self.find_internal_index(index);
self.slots_and_accounts[indexes.0].0
}
fn target_slot(&self) -> Slot {
self.target_slot
}
fn len(&self) -> usize {
self.len
}
fn contains_multiple_slots(&self) -> bool {
self.contains_multiple_slots
}
fn include_slot_in_hash(&self) -> IncludeSlotInHash {
self.include_slot_in_hash
}
fn has_hash_and_write_version(&self) -> bool {
true
}
fn hash(&self, index: usize) -> &Hash {
self.account(index).hash()
}
fn write_version(&self, index: usize) -> u64 {
self.account(index).write_version()
}
}
/// this tuple contains a single different source slot that applies to all accounts
/// accounts are StoredAccountMeta
impl<'a> StorableAccounts<'a, StoredAccountMeta<'a>>
for (
Slot,
&'a [&'a StoredAccountMeta<'a>],
IncludeSlotInHash,
Slot,
)
{
fn pubkey(&self, index: usize) -> &Pubkey {
self.account(index).pubkey()
}
fn account(&self, index: usize) -> &StoredAccountMeta<'a> {
self.1[index]
}
fn slot(&self, _index: usize) -> Slot {
// same other slot for all accounts
self.3
}
fn target_slot(&self) -> Slot {
self.0
}
fn len(&self) -> usize {
self.1.len()
}
fn include_slot_in_hash(&self) -> IncludeSlotInHash {
self.2
}
fn has_hash_and_write_version(&self) -> bool {
true
}
fn hash(&self, index: usize) -> &Hash {
self.account(index).hash()
}
fn write_version(&self, index: usize) -> u64 {
self.account(index).write_version()
}
}
#[cfg(test)]
pub mod tests {
use {
super::*,
crate::{
account_storage::meta::{AccountMeta, StoredAccountMeta, StoredMeta},
accounts_db::INCLUDE_SLOT_IN_HASH_TESTS,
append_vec::AppendVecStoredAccountMeta,
},
solana_sdk::{
account::{accounts_equal, AccountSharedData, WritableAccount},
hash::Hash,
},
};
fn compare<
'a,
T: ReadableAccount + Sync + PartialEq + std::fmt::Debug,
U: ReadableAccount + Sync + PartialEq + std::fmt::Debug,
>(
a: &impl StorableAccounts<'a, T>,
b: &impl StorableAccounts<'a, U>,
) {
assert_eq!(a.target_slot(), b.target_slot());
assert_eq!(a.len(), b.len());
assert_eq!(a.is_empty(), b.is_empty());
assert_eq!(a.include_slot_in_hash(), b.include_slot_in_hash());
(0..a.len()).for_each(|i| {
assert_eq!(a.pubkey(i), b.pubkey(i));
assert!(accounts_equal(a.account(i), b.account(i)));
})
}
#[test]
fn test_contains_multiple_slots() {
let pk = Pubkey::from([1; 32]);
let slot = 0;
let lamports = 1;
let owner = Pubkey::default();
let executable = false;
let rent_epoch = 0;
let meta = StoredMeta {
write_version_obsolete: 5,
pubkey: pk,
data_len: 7,
};
let account_meta = AccountMeta {
lamports,
owner,
executable,
rent_epoch,
};
let data = Vec::default();
let offset = 99;
let stored_size = 101;
let hash = Hash::new_unique();
let stored_account = StoredAccountMeta::AppendVec(AppendVecStoredAccountMeta {
meta: &meta,
account_meta: &account_meta,
data: &data,
offset,
stored_size,
hash: &hash,
});
let test3 = (
slot,
&vec![&stored_account, &stored_account][..],
INCLUDE_SLOT_IN_HASH_TESTS,
slot,
);
assert!(!test3.contains_multiple_slots());
}
#[test]
fn test_storable_accounts() {
let max_slots = 3_u64;
for target_slot in 0..max_slots {
for entries in 0..2 {
for starting_slot in 0..max_slots {
let data = Vec::default();
let hash = Hash::new_unique();
let mut raw = Vec::new();
let mut raw2 = Vec::new();
let mut raw4 = Vec::new();
for entry in 0..entries {
let pk = Pubkey::from([entry; 32]);
let account = AccountSharedData::create(
(entry as u64) * starting_slot,
Vec::default(),
Pubkey::default(),
false,
0,
);
raw.push((
pk,
account.clone(),
starting_slot % max_slots,
StoredMeta {
write_version_obsolete: 0, // just something
pubkey: pk,
data_len: u64::MAX, // just something
},
AccountMeta {
lamports: account.lamports(),
owner: *account.owner(),
executable: account.executable(),
rent_epoch: account.rent_epoch(),
},
));
}
for entry in 0..entries {
let offset = 99;
let stored_size = 101;
let raw = &raw[entry as usize];
raw2.push(StoredAccountMeta::AppendVec(AppendVecStoredAccountMeta {
meta: &raw.3,
account_meta: &raw.4,
data: &data,
offset,
stored_size,
hash: &hash,
}));
raw4.push((raw.0, raw.1.clone()));
}
let mut two = Vec::new();
let mut three = Vec::new();
let mut four_pubkey_and_account_value = Vec::new();
raw.iter()
.zip(raw2.iter().zip(raw4.iter()))
.for_each(|(raw, (raw2, raw4))| {
two.push((&raw.0, &raw.1)); // 2 item tuple
three.push(raw2);
four_pubkey_and_account_value.push(raw4);
});
let test2 = (target_slot, &two[..], INCLUDE_SLOT_IN_HASH_TESTS);
let test4 = (
target_slot,
&four_pubkey_and_account_value[..],
INCLUDE_SLOT_IN_HASH_TESTS,
);
let source_slot = starting_slot % max_slots;
let test3 = (
target_slot,
&three[..],
INCLUDE_SLOT_IN_HASH_TESTS,
source_slot,
);
let old_slot = starting_slot;
let test_moving_slots = StorableAccountsMovingSlots {
accounts: &two[..],
target_slot,
old_slot,
include_slot_in_hash: INCLUDE_SLOT_IN_HASH_TESTS,
};
let for_slice = [(old_slot, &three[..])];
let test_moving_slots2 = StorableAccountsBySlot::new(
target_slot,
&for_slice,
INCLUDE_SLOT_IN_HASH_TESTS,
);
compare(&test2, &test3);
compare(&test2, &test4);
compare(&test2, &test_moving_slots);
compare(&test2, &test_moving_slots2);
for (i, raw) in raw.iter().enumerate() {
assert_eq!(raw.0, *test3.pubkey(i));
assert!(accounts_equal(&raw.1, test3.account(i)));
assert_eq!(raw.2, test3.slot(i));
assert_eq!(target_slot, test4.slot(i));
assert_eq!(target_slot, test2.slot(i));
assert_eq!(old_slot, test_moving_slots.slot(i));
assert_eq!(old_slot, test_moving_slots2.slot(i));
}
assert_eq!(target_slot, test3.target_slot());
assert_eq!(target_slot, test4.target_slot());
assert_eq!(target_slot, test_moving_slots2.target_slot());
assert!(!test2.contains_multiple_slots());
assert!(!test4.contains_multiple_slots());
assert!(!test_moving_slots.contains_multiple_slots());
assert_eq!(test3.contains_multiple_slots(), entries > 1);
}
}
}
}
#[test]
fn test_storable_accounts_by_slot() {
solana_logger::setup();
// slots 0..4
// each one containing a subset of the overall # of entries (0..4)
for entries in 0..6 {
let data = Vec::default();
let hashes = (0..entries).map(|_| Hash::new_unique()).collect::<Vec<_>>();
let mut raw = Vec::new();
let mut raw2 = Vec::new();
for entry in 0..entries {
let pk = Pubkey::from([entry; 32]);
let account = AccountSharedData::create(
entry as u64,
Vec::default(),
Pubkey::default(),
false,
0,
);
raw.push((
pk,
account.clone(),
StoredMeta {
write_version_obsolete: 500 + (entry * 3) as u64, // just something
pubkey: pk,
data_len: (entry * 2) as u64, // just something
},
AccountMeta {
lamports: account.lamports(),
owner: *account.owner(),
executable: account.executable(),
rent_epoch: account.rent_epoch(),
},
));
}
for entry in 0..entries {
let offset = 99;
let stored_size = 101;
raw2.push(StoredAccountMeta::AppendVec(AppendVecStoredAccountMeta {
meta: &raw[entry as usize].2,
account_meta: &raw[entry as usize].3,
data: &data,
offset,
stored_size,
hash: &hashes[entry as usize],
}));
}
let raw2_refs = raw2.iter().collect::<Vec<_>>();
// enumerate through permutations of # entries (ie. accounts) in each slot. Each one is 0..=entries.
for entries0 in 0..=entries {
let remaining1 = entries.saturating_sub(entries0);
for entries1 in 0..=remaining1 {
let remaining2 = entries.saturating_sub(entries0 + entries1);
for entries2 in 0..=remaining2 {
let remaining3 = entries.saturating_sub(entries0 + entries1 + entries2);
let entries_by_level = [entries0, entries1, entries2, remaining3];
let mut overall_index = 0;
let mut expected_slots = Vec::default();
let slots_and_accounts = entries_by_level
.iter()
.enumerate()
.filter_map(|(slot, count)| {
let slot = slot as Slot;
let count = *count as usize;
(overall_index < raw2.len()).then(|| {
let range = overall_index..(overall_index + count);
let result = &raw2_refs[range.clone()];
range.for_each(|_| expected_slots.push(slot));
overall_index += count;
(slot, result)
})
})
.collect::<Vec<_>>();
let storable = StorableAccountsBySlot::new(
99,
&slots_and_accounts[..],
INCLUDE_SLOT_IN_HASH_TESTS,
);
assert!(storable.has_hash_and_write_version());
assert_eq!(99, storable.target_slot());
assert_eq!(entries0 != entries, storable.contains_multiple_slots());
(0..entries).for_each(|index| {
let index = index as usize;
assert_eq!(storable.account(index), &raw2[index]);
assert_eq!(storable.pubkey(index), raw2[index].pubkey());
assert_eq!(storable.hash(index), raw2[index].hash());
assert_eq!(storable.slot(index), expected_slots[index]);
assert_eq!(storable.write_version(index), raw2[index].write_version());
})
}
}
}
}
}
}
| true
|
b2898c034e1d2e45f4755604f5cadf4e8a83e79d
|
Rust
|
MitchellHansen/advent-2019
|
/src/main.rs
|
UTF-8
| 1,395
| 2.546875
| 3
|
[] |
no_license
|
extern crate reqwest;
extern crate tempfile;
use crate::problem1::part1::Problem1;
use crate::problem2::part1::Problem2;
use crate::problem3::part1::Problem3;
use crate::problem4::part1::Problem4;
use crate::problem5::part1::Problem5;
use crate::problem6::part1::Problem6;
use crate::problem7::part1::Problem7;
mod problem1;
mod problem2;
mod problem3;
mod problem4;
mod problem5;
mod problem6;
mod problem7;
mod util;
pub trait Problem {
// Parses input and generates state
fn new(input: &String) -> Self;
// Runs on state
fn run_part1(&self);
fn run_part2(&self);
}
fn main() {
// let problem1 = Problem1::new(&util::get_problem(1));
// problem1.run_part1();
// problem1.run_part2();
//
// let problem2 = Problem2::new(&util::get_problem(2));
// problem2.run_part1();
// problem2.run_part2();
//
// let problem3 = Problem3::new(&util::get_problem(3));
// problem3.run_part1();
// problem3.run_part2();
//
// let problem4 = Problem4::new(&util::get_problem(4));
// problem4.run_part1();
// problem4.run_part2();
//
// let problem5 = Problem5::new(&util::get_problem(5));
// problem5.run_part1();
//
// let problem6 = Problem6::new(&util::get_problem(6));
// problem6.run_part1();
// problem6.run_part2();
let problem7 = Problem7::new(&util::get_problem(7));
problem7.run_part1();
problem7.run_part2();
}
| true
|
7d99cbbb27bb844ea84508c34e892dc841b01aac
|
Rust
|
rust-lang-ja/rust-by-example-ja
|
/src-old/std_misc/file/open/open.rs
|
UTF-8
| 1,079
| 3.703125
| 4
|
[
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
use std::error::Error;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
fn main() {
// 目的ファイルに対する`Path`を作成
let path = Path::new("hello.txt");
let display = path.display();
// pathを読み込み専用モードで開く。これは`io::Result<File>`を返す。
let mut file = match File::open(&path) {
// `io::Error`の`description`メソッドはエラーを説明する文字列を返す。
Err(why) => panic!("couldn't open {}: {}", display,
Error::description(&why)),
Ok(file) => file,
};
// ファイルの中身を文字列に読み込む。`io::Result<useize>`を返す。
let mut s = String::new();
match file.read_to_string(&mut s) {
Err(why) => panic!("couldn't read {}: {}", display,
Error::description(&why)),
Ok(_) => print!("{} contains:\n{}", display, s),
}
// `file`がスコープから抜け、"hello.txt"が閉じられる。
}
| true
|
490612e0285d2c6377a75e209b4db1758caa4ceb
|
Rust
|
DaixuanLi/UndergradCourseProject
|
/OperatingSystem_Rust/os/src/memory/page_replace/fifo.rs
|
UTF-8
| 1,522
| 2.6875
| 3
|
[] |
no_license
|
use {
super::*,
alloc::{collections::VecDeque, sync::Arc},
spin::Mutex,
};
#[derive(Default)]
pub struct FifoPageReplace {
frames: VecDeque<(usize, Arc<Mutex<PageTableImpl>>)>,
pointer: usize,
}
impl PageReplace for FifoPageReplace {
fn push_frame(&mut self, vaddr: usize, pt: Arc<Mutex<PageTableImpl>>) {
//println!("push pointer: {}",self.pointer);
//println!("push vaddr: {:#x?}", vaddr);
self.frames.insert(self.pointer,(vaddr, pt));
self.pointer = self.pointer + 1;
if self.pointer == self.frames.len() {
self.pointer = 0;
}
}
fn choose_victim(&mut self) -> Option<(usize, Arc<Mutex<PageTableImpl>>)> {
// 选择一个已经分配的物理页帧
while true {
//println!("pop check pointer: {}",self.pointer);
let mut pt = self.frames.get(self.pointer).unwrap();
let mut ptl = pt.1.lock().get_entry(pt.0).unwrap().accessed();
if ptl {
pt.1.lock().get_entry(pt.0).unwrap().clear_accessed();
} else {
break
}
self.pointer = self.pointer + 1;
if self.pointer == self.frames.len() {
self.pointer = 0;
}
}
//println!("pop pointer: {}",self.pointer);
let popid = self.pointer;
if self.pointer == self.frames.len() - 1 {
self.pointer = 0;
}
self.frames.remove(popid)
}
fn tick(&self) {}
}
| true
|
4c0efaa928a82a2c716ef9ecd83a40c68895e349
|
Rust
|
z1queue/smartcore
|
/src/linalg/mod.rs
|
UTF-8
| 23,629
| 3.203125
| 3
|
[
"Apache-2.0"
] |
permissive
|
#![allow(clippy::wrong_self_convention)]
//! # Linear Algebra and Matrix Decomposition
//!
//! Most machine learning algorithms in SmartCore depend on linear algebra and matrix decomposition methods from this module.
//!
//! Traits [`BaseMatrix`](trait.BaseMatrix.html), [`Matrix`](trait.Matrix.html) and [`BaseVector`](trait.BaseVector.html) define
//! abstract methods that can be implemented for any two-dimensional and one-dimentional arrays (matrix and vector).
//! Functions from these traits are designed for SmartCore machine learning algorithms and should not be used directly in your code.
//! If you still want to use functions from `BaseMatrix`, `Matrix` and `BaseVector` please be aware that methods defined in these
//! traits might change in the future.
//!
//! One reason why linear algebra traits are public is to allow for different types of matrices and vectors to be plugged into SmartCore.
//! Once all methods defined in `BaseMatrix`, `Matrix` and `BaseVector` are implemented for your favourite type of matrix and vector you
//! should be able to run SmartCore algorithms on it. Please see `nalgebra_bindings` and `ndarray_bindings` modules for an example of how
//! it is done for other libraries.
//!
//! You will also find verious matrix decomposition methods that work for any matrix that extends [`Matrix`](trait.Matrix.html).
//! For example, to decompose matrix defined as [Vec](https://doc.rust-lang.org/std/vec/struct.Vec.html):
//!
//! ```
//! use smartcore::linalg::naive::dense_matrix::*;
//! use smartcore::linalg::svd::*;
//!
//! let A = DenseMatrix::from_2d_array(&[
//! &[0.9000, 0.4000, 0.7000],
//! &[0.4000, 0.5000, 0.3000],
//! &[0.7000, 0.3000, 0.8000],
//! ]);
//!
//! let svd = A.svd().unwrap();
//!
//! let s: Vec<f64> = svd.s;
//! let v: DenseMatrix<f64> = svd.V;
//! let u: DenseMatrix<f64> = svd.U;
//! ```
pub mod cholesky;
/// The matrix is represented in terms of its eigenvalues and eigenvectors.
pub mod evd;
pub mod high_order;
/// Factors a matrix as the product of a lower triangular matrix and an upper triangular matrix.
pub mod lu;
/// Dense matrix with column-major order that wraps [Vec](https://doc.rust-lang.org/std/vec/struct.Vec.html).
pub mod naive;
/// [nalgebra](https://docs.rs/nalgebra/) bindings.
#[cfg(feature = "nalgebra-bindings")]
pub mod nalgebra_bindings;
/// [ndarray](https://docs.rs/ndarray) bindings.
#[cfg(feature = "ndarray-bindings")]
pub mod ndarray_bindings;
/// QR factorization that factors a matrix into a product of an orthogonal matrix and an upper triangular matrix.
pub mod qr;
pub mod stats;
/// Singular value decomposition.
pub mod svd;
use std::fmt::{Debug, Display};
use std::marker::PhantomData;
use std::ops::Range;
use crate::math::num::RealNumber;
use cholesky::CholeskyDecomposableMatrix;
use evd::EVDDecomposableMatrix;
use high_order::HighOrderOperations;
use lu::LUDecomposableMatrix;
use qr::QRDecomposableMatrix;
use stats::{MatrixPreprocessing, MatrixStats};
use svd::SVDDecomposableMatrix;
/// Column or row vector
pub trait BaseVector<T: RealNumber>: Clone + Debug {
/// Get an element of a vector
/// * `i` - index of an element
fn get(&self, i: usize) -> T;
/// Set an element at `i` to `x`
/// * `i` - index of an element
/// * `x` - new value
fn set(&mut self, i: usize, x: T);
/// Get number of elevemnt in the vector
fn len(&self) -> usize;
/// Returns true if the vector is empty.
fn is_empty(&self) -> bool {
self.len() == 0
}
/// Create a new vector from a &[T]
/// ```
/// use smartcore::linalg::naive::dense_matrix::*;
/// let a: [f64; 5] = [0., 0.5, 2., 3., 4.];
/// let v: Vec<f64> = BaseVector::from_array(&a);
/// assert_eq!(v, vec![0., 0.5, 2., 3., 4.]);
/// ```
fn from_array(f: &[T]) -> Self {
let mut v = Self::zeros(f.len());
for (i, elem) in f.iter().enumerate() {
v.set(i, *elem);
}
v
}
/// Return a vector with the elements of the one-dimensional array.
fn to_vec(&self) -> Vec<T>;
/// Create new vector with zeros of size `len`.
fn zeros(len: usize) -> Self;
/// Create new vector with ones of size `len`.
fn ones(len: usize) -> Self;
/// Create new vector of size `len` where each element is set to `value`.
fn fill(len: usize, value: T) -> Self;
/// Vector dot product
fn dot(&self, other: &Self) -> T;
/// Returns True if matrices are element-wise equal within a tolerance `error`.
fn approximate_eq(&self, other: &Self, error: T) -> bool;
/// Returns [L2 norm] of the vector(https://en.wikipedia.org/wiki/Matrix_norm).
fn norm2(&self) -> T;
/// Returns [vectors norm](https://en.wikipedia.org/wiki/Matrix_norm) of order `p`.
fn norm(&self, p: T) -> T;
/// Divide single element of the vector by `x`, write result to original vector.
fn div_element_mut(&mut self, pos: usize, x: T);
/// Multiply single element of the vector by `x`, write result to original vector.
fn mul_element_mut(&mut self, pos: usize, x: T);
/// Add single element of the vector to `x`, write result to original vector.
fn add_element_mut(&mut self, pos: usize, x: T);
/// Subtract `x` from single element of the vector, write result to original vector.
fn sub_element_mut(&mut self, pos: usize, x: T);
/// Subtract scalar
fn sub_scalar_mut(&mut self, x: T) -> &Self {
for i in 0..self.len() {
self.set(i, self.get(i) - x);
}
self
}
/// Subtract scalar
fn add_scalar_mut(&mut self, x: T) -> &Self {
for i in 0..self.len() {
self.set(i, self.get(i) + x);
}
self
}
/// Subtract scalar
fn mul_scalar_mut(&mut self, x: T) -> &Self {
for i in 0..self.len() {
self.set(i, self.get(i) * x);
}
self
}
/// Subtract scalar
fn div_scalar_mut(&mut self, x: T) -> &Self {
for i in 0..self.len() {
self.set(i, self.get(i) / x);
}
self
}
/// Add vectors, element-wise
fn add_scalar(&self, x: T) -> Self {
let mut r = self.clone();
r.add_scalar_mut(x);
r
}
/// Subtract vectors, element-wise
fn sub_scalar(&self, x: T) -> Self {
let mut r = self.clone();
r.sub_scalar_mut(x);
r
}
/// Multiply vectors, element-wise
fn mul_scalar(&self, x: T) -> Self {
let mut r = self.clone();
r.mul_scalar_mut(x);
r
}
/// Divide vectors, element-wise
fn div_scalar(&self, x: T) -> Self {
let mut r = self.clone();
r.div_scalar_mut(x);
r
}
/// Add vectors, element-wise, overriding original vector with result.
fn add_mut(&mut self, other: &Self) -> &Self;
/// Subtract vectors, element-wise, overriding original vector with result.
fn sub_mut(&mut self, other: &Self) -> &Self;
/// Multiply vectors, element-wise, overriding original vector with result.
fn mul_mut(&mut self, other: &Self) -> &Self;
/// Divide vectors, element-wise, overriding original vector with result.
fn div_mut(&mut self, other: &Self) -> &Self;
/// Add vectors, element-wise
fn add(&self, other: &Self) -> Self {
let mut r = self.clone();
r.add_mut(other);
r
}
/// Subtract vectors, element-wise
fn sub(&self, other: &Self) -> Self {
let mut r = self.clone();
r.sub_mut(other);
r
}
/// Multiply vectors, element-wise
fn mul(&self, other: &Self) -> Self {
let mut r = self.clone();
r.mul_mut(other);
r
}
/// Divide vectors, element-wise
fn div(&self, other: &Self) -> Self {
let mut r = self.clone();
r.div_mut(other);
r
}
/// Calculates sum of all elements of the vector.
fn sum(&self) -> T;
/// Returns unique values from the vector.
/// ```
/// use smartcore::linalg::naive::dense_matrix::*;
/// let a = vec!(1., 2., 2., -2., -6., -7., 2., 3., 4.);
///
///assert_eq!(a.unique(), vec![-7., -6., -2., 1., 2., 3., 4.]);
/// ```
fn unique(&self) -> Vec<T>;
/// Computes the arithmetic mean.
fn mean(&self) -> T {
self.sum() / T::from_usize(self.len()).unwrap()
}
/// Computes variance.
fn var(&self) -> T {
let n = self.len();
let mut mu = T::zero();
let mut sum = T::zero();
let div = T::from_usize(n).unwrap();
for i in 0..n {
let xi = self.get(i);
mu += xi;
sum += xi * xi;
}
mu /= div;
sum / div - mu.powi(2)
}
/// Computes the standard deviation.
fn std(&self) -> T {
self.var().sqrt()
}
/// Copies content of `other` vector.
fn copy_from(&mut self, other: &Self);
/// Take elements from an array.
fn take(&self, index: &[usize]) -> Self {
let n = index.len();
let mut result = Self::zeros(n);
for (i, idx) in index.iter().enumerate() {
result.set(i, self.get(*idx));
}
result
}
}
/// Generic matrix type.
pub trait BaseMatrix<T: RealNumber>: Clone + Debug {
/// Row vector that is associated with this matrix type,
/// e.g. if we have an implementation of sparce matrix
/// we should have an associated sparce vector type that
/// represents a row in this matrix.
type RowVector: BaseVector<T> + Clone + Debug;
/// Transforms row vector `vec` into a 1xM matrix.
fn from_row_vector(vec: Self::RowVector) -> Self;
/// Transforms 1-d matrix of 1xM into a row vector.
fn to_row_vector(self) -> Self::RowVector;
/// Get an element of the matrix.
/// * `row` - row number
/// * `col` - column number
fn get(&self, row: usize, col: usize) -> T;
/// Get a vector with elements of the `row`'th row
/// * `row` - row number
fn get_row_as_vec(&self, row: usize) -> Vec<T>;
/// Get the `row`'th row
/// * `row` - row number
fn get_row(&self, row: usize) -> Self::RowVector;
/// Copies a vector with elements of the `row`'th row into `result`
/// * `row` - row number
/// * `result` - receiver for the row
fn copy_row_as_vec(&self, row: usize, result: &mut Vec<T>);
/// Get a vector with elements of the `col`'th column
/// * `col` - column number
fn get_col_as_vec(&self, col: usize) -> Vec<T>;
/// Copies a vector with elements of the `col`'th column into `result`
/// * `col` - column number
/// * `result` - receiver for the col
fn copy_col_as_vec(&self, col: usize, result: &mut Vec<T>);
/// Set an element at `col`, `row` to `x`
fn set(&mut self, row: usize, col: usize, x: T);
/// Create an identity matrix of size `size`
fn eye(size: usize) -> Self;
/// Create new matrix with zeros of size `nrows` by `ncols`.
fn zeros(nrows: usize, ncols: usize) -> Self;
/// Create new matrix with ones of size `nrows` by `ncols`.
fn ones(nrows: usize, ncols: usize) -> Self;
/// Create new matrix of size `nrows` by `ncols` where each element is set to `value`.
fn fill(nrows: usize, ncols: usize, value: T) -> Self;
/// Return the shape of an array.
fn shape(&self) -> (usize, usize);
/// Stack arrays in sequence vertically (row wise).
/// ```
/// use smartcore::linalg::naive::dense_matrix::*;
///
/// let a = DenseMatrix::from_2d_array(&[&[1., 2., 3.], &[4., 5., 6.]]);
/// let b = DenseMatrix::from_2d_array(&[&[1., 2.], &[3., 4.]]);
/// let expected = DenseMatrix::from_2d_array(&[
/// &[1., 2., 3., 1., 2.],
/// &[4., 5., 6., 3., 4.]
/// ]);
///
/// assert_eq!(a.h_stack(&b), expected);
/// ```
fn h_stack(&self, other: &Self) -> Self;
/// Stack arrays in sequence horizontally (column wise).
/// ```
/// use smartcore::linalg::naive::dense_matrix::*;
///
/// let a = DenseMatrix::from_array(1, 3, &[1., 2., 3.]);
/// let b = DenseMatrix::from_array(1, 3, &[4., 5., 6.]);
/// let expected = DenseMatrix::from_2d_array(&[
/// &[1., 2., 3.],
/// &[4., 5., 6.]
/// ]);
///
/// assert_eq!(a.v_stack(&b), expected);
/// ```
fn v_stack(&self, other: &Self) -> Self;
/// Matrix product.
/// ```
/// use smartcore::linalg::naive::dense_matrix::*;
///
/// let a = DenseMatrix::from_2d_array(&[&[1., 2.], &[3., 4.]]);
/// let expected = DenseMatrix::from_2d_array(&[
/// &[7., 10.],
/// &[15., 22.]
/// ]);
///
/// assert_eq!(a.matmul(&a), expected);
/// ```
fn matmul(&self, other: &Self) -> Self;
/// Vector dot product
/// Both matrices should be of size _1xM_
/// ```
/// use smartcore::linalg::naive::dense_matrix::*;
///
/// let a = DenseMatrix::from_array(1, 3, &[1., 2., 3.]);
/// let b = DenseMatrix::from_array(1, 3, &[4., 5., 6.]);
///
/// assert_eq!(a.dot(&b), 32.);
/// ```
fn dot(&self, other: &Self) -> T;
/// Return a slice of the matrix.
/// * `rows` - range of rows to return
/// * `cols` - range of columns to return
/// ```
/// use smartcore::linalg::naive::dense_matrix::*;
///
/// let m = DenseMatrix::from_2d_array(&[
/// &[1., 2., 3., 1.],
/// &[4., 5., 6., 3.],
/// &[7., 8., 9., 5.]
/// ]);
/// let expected = DenseMatrix::from_2d_array(&[&[2., 3.], &[5., 6.]]);
/// let result = m.slice(0..2, 1..3);
/// assert_eq!(result, expected);
/// ```
fn slice(&self, rows: Range<usize>, cols: Range<usize>) -> Self;
/// Returns True if matrices are element-wise equal within a tolerance `error`.
fn approximate_eq(&self, other: &Self, error: T) -> bool;
/// Add matrices, element-wise, overriding original matrix with result.
fn add_mut(&mut self, other: &Self) -> &Self;
/// Subtract matrices, element-wise, overriding original matrix with result.
fn sub_mut(&mut self, other: &Self) -> &Self;
/// Multiply matrices, element-wise, overriding original matrix with result.
fn mul_mut(&mut self, other: &Self) -> &Self;
/// Divide matrices, element-wise, overriding original matrix with result.
fn div_mut(&mut self, other: &Self) -> &Self;
/// Divide single element of the matrix by `x`, write result to original matrix.
fn div_element_mut(&mut self, row: usize, col: usize, x: T);
/// Multiply single element of the matrix by `x`, write result to original matrix.
fn mul_element_mut(&mut self, row: usize, col: usize, x: T);
/// Add single element of the matrix to `x`, write result to original matrix.
fn add_element_mut(&mut self, row: usize, col: usize, x: T);
/// Subtract `x` from single element of the matrix, write result to original matrix.
fn sub_element_mut(&mut self, row: usize, col: usize, x: T);
/// Add matrices, element-wise
fn add(&self, other: &Self) -> Self {
let mut r = self.clone();
r.add_mut(other);
r
}
/// Subtract matrices, element-wise
fn sub(&self, other: &Self) -> Self {
let mut r = self.clone();
r.sub_mut(other);
r
}
/// Multiply matrices, element-wise
fn mul(&self, other: &Self) -> Self {
let mut r = self.clone();
r.mul_mut(other);
r
}
/// Divide matrices, element-wise
fn div(&self, other: &Self) -> Self {
let mut r = self.clone();
r.div_mut(other);
r
}
/// Add `scalar` to the matrix, override original matrix with result.
fn add_scalar_mut(&mut self, scalar: T) -> &Self;
/// Subtract `scalar` from the elements of matrix, override original matrix with result.
fn sub_scalar_mut(&mut self, scalar: T) -> &Self;
/// Multiply `scalar` by the elements of matrix, override original matrix with result.
fn mul_scalar_mut(&mut self, scalar: T) -> &Self;
/// Divide elements of the matrix by `scalar`, override original matrix with result.
fn div_scalar_mut(&mut self, scalar: T) -> &Self;
/// Add `scalar` to the matrix.
fn add_scalar(&self, scalar: T) -> Self {
let mut r = self.clone();
r.add_scalar_mut(scalar);
r
}
/// Subtract `scalar` from the elements of matrix.
fn sub_scalar(&self, scalar: T) -> Self {
let mut r = self.clone();
r.sub_scalar_mut(scalar);
r
}
/// Multiply `scalar` by the elements of matrix.
fn mul_scalar(&self, scalar: T) -> Self {
let mut r = self.clone();
r.mul_scalar_mut(scalar);
r
}
/// Divide elements of the matrix by `scalar`.
fn div_scalar(&self, scalar: T) -> Self {
let mut r = self.clone();
r.div_scalar_mut(scalar);
r
}
/// Reverse or permute the axes of the matrix, return new matrix.
fn transpose(&self) -> Self;
/// Create new `nrows` by `ncols` matrix and populate it with random samples from a uniform distribution over [0, 1).
fn rand(nrows: usize, ncols: usize) -> Self;
/// Returns [L2 norm](https://en.wikipedia.org/wiki/Matrix_norm).
fn norm2(&self) -> T;
/// Returns [matrix norm](https://en.wikipedia.org/wiki/Matrix_norm) of order `p`.
fn norm(&self, p: T) -> T;
/// Returns the average of the matrix columns.
fn column_mean(&self) -> Vec<T>;
/// Numerical negative, element-wise. Overrides original matrix.
fn negative_mut(&mut self);
/// Numerical negative, element-wise.
fn negative(&self) -> Self {
let mut result = self.clone();
result.negative_mut();
result
}
/// Returns new matrix of shape `nrows` by `ncols` with data copied from original matrix.
/// ```
/// use smartcore::linalg::naive::dense_matrix::*;
///
/// let a = DenseMatrix::from_array(1, 6, &[1., 2., 3., 4., 5., 6.]);
/// let expected = DenseMatrix::from_2d_array(&[
/// &[1., 2., 3.],
/// &[4., 5., 6.]
/// ]);
///
/// assert_eq!(a.reshape(2, 3), expected);
/// ```
fn reshape(&self, nrows: usize, ncols: usize) -> Self;
/// Copies content of `other` matrix.
fn copy_from(&mut self, other: &Self);
/// Calculate the absolute value element-wise. Overrides original matrix.
fn abs_mut(&mut self) -> &Self;
/// Calculate the absolute value element-wise.
fn abs(&self) -> Self {
let mut result = self.clone();
result.abs_mut();
result
}
/// Calculates sum of all elements of the matrix.
fn sum(&self) -> T;
/// Calculates max of all elements of the matrix.
fn max(&self) -> T;
/// Calculates min of all elements of the matrix.
fn min(&self) -> T;
/// Calculates max(|a - b|) of two matrices
/// ```
/// use smartcore::linalg::naive::dense_matrix::*;
///
/// let a = DenseMatrix::from_array(2, 3, &[1., 2., 3., 4., -5., 6.]);
/// let b = DenseMatrix::from_array(2, 3, &[2., 3., 4., 1., 0., -12.]);
///
/// assert_eq!(a.max_diff(&b), 18.);
/// assert_eq!(b.max_diff(&b), 0.);
/// ```
fn max_diff(&self, other: &Self) -> T {
self.sub(other).abs().max()
}
/// Calculates [Softmax function](https://en.wikipedia.org/wiki/Softmax_function). Overrides the matrix with result.
fn softmax_mut(&mut self);
/// Raises elements of the matrix to the power of `p`
fn pow_mut(&mut self, p: T) -> &Self;
/// Returns new matrix with elements raised to the power of `p`
fn pow(&mut self, p: T) -> Self {
let mut result = self.clone();
result.pow_mut(p);
result
}
/// Returns the indices of the maximum values in each row.
/// ```
/// use smartcore::linalg::naive::dense_matrix::*;
/// let a = DenseMatrix::from_array(2, 3, &[1., 2., 3., -5., -6., -7.]);
///
/// assert_eq!(a.argmax(), vec![2, 0]);
/// ```
fn argmax(&self) -> Vec<usize>;
/// Returns vector with unique values from the matrix.
/// ```
/// use smartcore::linalg::naive::dense_matrix::*;
/// let a = DenseMatrix::from_array(3, 3, &[1., 2., 2., -2., -6., -7., 2., 3., 4.]);
///
///assert_eq!(a.unique(), vec![-7., -6., -2., 1., 2., 3., 4.]);
/// ```
fn unique(&self) -> Vec<T>;
/// Calculates the covariance matrix
fn cov(&self) -> Self;
/// Take elements from an array along an axis.
fn take(&self, index: &[usize], axis: u8) -> Self {
let (n, p) = self.shape();
let k = match axis {
0 => p,
_ => n,
};
let mut result = match axis {
0 => Self::zeros(index.len(), p),
_ => Self::zeros(n, index.len()),
};
for (i, idx) in index.iter().enumerate() {
for j in 0..k {
match axis {
0 => result.set(i, j, self.get(*idx, j)),
_ => result.set(j, i, self.get(j, *idx)),
};
}
}
result
}
}
/// Generic matrix with additional mixins like various factorization methods.
pub trait Matrix<T: RealNumber>:
BaseMatrix<T>
+ SVDDecomposableMatrix<T>
+ EVDDecomposableMatrix<T>
+ QRDecomposableMatrix<T>
+ LUDecomposableMatrix<T>
+ CholeskyDecomposableMatrix<T>
+ MatrixStats<T>
+ MatrixPreprocessing<T>
+ HighOrderOperations<T>
+ PartialEq
+ Display
{
}
pub(crate) fn row_iter<F: RealNumber, M: BaseMatrix<F>>(m: &M) -> RowIter<'_, F, M> {
RowIter {
m,
pos: 0,
max_pos: m.shape().0,
phantom: PhantomData,
}
}
pub(crate) struct RowIter<'a, T: RealNumber, M: BaseMatrix<T>> {
m: &'a M,
pos: usize,
max_pos: usize,
phantom: PhantomData<&'a T>,
}
impl<'a, T: RealNumber, M: BaseMatrix<T>> Iterator for RowIter<'a, T, M> {
type Item = Vec<T>;
fn next(&mut self) -> Option<Vec<T>> {
let res;
if self.pos < self.max_pos {
res = Some(self.m.get_row_as_vec(self.pos))
} else {
res = None
}
self.pos += 1;
res
}
}
#[cfg(test)]
mod tests {
use crate::linalg::naive::dense_matrix::DenseMatrix;
use crate::linalg::BaseMatrix;
use crate::linalg::BaseVector;
#[test]
fn mean() {
let m = vec![1., 2., 3.];
assert_eq!(m.mean(), 2.0);
}
#[test]
fn std() {
let m = vec![1., 2., 3.];
assert!((m.std() - 0.81f64).abs() < 1e-2);
}
#[test]
fn var() {
let m = vec![1., 2., 3., 4.];
assert!((m.var() - 1.25f64).abs() < std::f64::EPSILON);
}
#[test]
fn vec_take() {
let m = vec![1., 2., 3., 4., 5.];
assert_eq!(m.take(&vec!(0, 0, 4, 4)), vec![1., 1., 5., 5.]);
}
#[test]
fn take() {
let m = DenseMatrix::from_2d_array(&[
&[1.0, 2.0],
&[3.0, 4.0],
&[5.0, 6.0],
&[7.0, 8.0],
&[9.0, 10.0],
]);
let expected_0 = DenseMatrix::from_2d_array(&[&[3.0, 4.0], &[3.0, 4.0], &[7.0, 8.0]]);
let expected_1 = DenseMatrix::from_2d_array(&[
&[2.0, 1.0],
&[4.0, 3.0],
&[6.0, 5.0],
&[8.0, 7.0],
&[10.0, 9.0],
]);
assert_eq!(m.take(&vec!(1, 1, 3), 0), expected_0);
assert_eq!(m.take(&vec!(1, 0), 1), expected_1);
}
}
| true
|
e6b8bb9ad5951c4991e830d83e471ccfc8e79a74
|
Rust
|
kruschk/intcode
|
/src/instruction.rs
|
UTF-8
| 4,281
| 3.96875
| 4
|
[
"MIT"
] |
permissive
|
use crate::{
machine::Machine,
opcode::{OpCode, OpCodeType, Operand},
};
// Intcode instructions come in two parts: an opcode and one or more operands.
// This enum specifies an instruction, which collects the opcode and its
// arguments into a convenient data structure.
#[derive(Debug)]
pub enum Instruction {
// Add op1 to op2 and store the result at address.
Add {
op1: Operand,
op2: Operand,
address: Operand,
},
// Adjust the base pointer.
AdjustBase(Operand),
// Halt the program.
Halt,
// Read input and store it in memory.
Input(Operand),
// Jump to address if condition is false.
JumpIfFalse {
condition: Operand,
address: Operand,
},
// Jump to address if condition is true.
JumpIfTrue {
condition: Operand,
address: Operand,
},
// Multiply op1 with op2 and store the result at address.
Multiply {
op1: Operand,
op2: Operand,
address: Operand,
},
// Write output.
Output(Operand),
// Test if op1 = op2, and store 1 (true) or 0 (false) at address.
TestEqual {
op1: Operand,
op2: Operand,
address: Operand,
},
// Test if op1 < op2, and store 1 (true) or 0 (false) at address.
TestLessThan {
op1: Operand,
op2: Operand,
address: Operand,
},
}
impl Instruction {
// Create a new instruction based on the current state of the machine and
// an opcode.
pub fn new(machine: &Machine, opcode: OpCode) -> Self {
// Save the machine's instruction pointer for convenience.
let ip = machine.get_ip();
// Destructure the opcode.
let OpCode {
opcode_type,
param1_mode,
param2_mode,
param3_mode,
} = opcode;
// Match based on the opcode type and return an instruction. The
// parameters are offset in memory from the current position of the
// instruction pointer, and the number of arguments depends on the
// opcode type.
match opcode_type {
OpCodeType::Add => Self::Add {
op1: Operand::new(param1_mode, machine.read_mem(ip + 1)),
op2: Operand::new(param2_mode, machine.read_mem(ip + 2)),
address: Operand::new(param3_mode, machine.read_mem(ip + 3)),
},
OpCodeType::AdjustBase => Self::AdjustBase(
Operand::new(param1_mode, machine.read_mem(ip + 1)),
),
OpCodeType::Halt => Self::Halt,
OpCodeType::JumpIfFalse => Self::JumpIfFalse {
condition: Operand::new(param1_mode, machine.read_mem(ip + 1)),
address: Operand::new(param2_mode, machine.read_mem(ip + 2)),
},
OpCodeType::JumpIfTrue => Self::JumpIfTrue {
condition: Operand::new(param1_mode, machine.read_mem(ip + 1)),
address: Operand::new(param2_mode, machine.read_mem(ip + 2)),
},
OpCodeType::Input => Self::Input(
Operand::new(param1_mode, machine.read_mem(ip + 1)),
),
OpCodeType::Multiply => Self::Multiply {
op1: Operand::new(param1_mode, machine.read_mem(ip + 1)),
op2: Operand::new(param2_mode, machine.read_mem(ip + 2)),
address: Operand::new(param3_mode, machine.read_mem(ip + 3)),
},
OpCodeType::Output => Self::Output(
Operand::new(param1_mode, machine.read_mem(ip + 1)),
),
OpCodeType::TestLessThan => Self::TestLessThan {
op1: Operand::new(param1_mode, machine.read_mem(ip + 1)),
op2: Operand::new(param2_mode, machine.read_mem(ip + 2)),
address: Operand::new(param3_mode, machine.read_mem(ip + 3)),
},
OpCodeType::TestEqual => Self::TestEqual {
op1: Operand::new(param1_mode, machine.read_mem(ip + 1)),
op2: Operand::new(param2_mode, machine.read_mem(ip + 2)),
address: Operand::new(param3_mode, machine.read_mem(ip + 3)),
},
}
}
}
| true
|
cd8973d0c4fa2062a7fb04244c7bcdfbef08d4ee
|
Rust
|
JMAlego/rusty_jello
|
/src/machine.rs
|
UTF-8
| 6,990
| 3.140625
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
//! Representation of the Rusty Jello machine
use std::fmt;
use instructions;
use std::time::Duration;
use std::thread;
pub enum Register {
R0 = 0,
R1 = 1,
R2 = 2,
R3 = 3,
}
pub struct Flags {
pub halt: bool,
pub carry: bool,
pub overflow: bool,
pub test: bool,
}
impl fmt::Debug for Flags {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"{{halt: {}, carry: {}, overflow: {}, test: {}}}",
self.halt,
self.carry,
self.overflow,
self.test
)
}
}
pub struct SerialBuffer {
buffer: Vec<u8>,
}
impl SerialBuffer {
pub fn new() -> SerialBuffer {
return SerialBuffer { buffer: Vec::new() };
}
}
impl SerialBuffer {
pub fn put(&mut self, item: u8) -> bool {
if self.buffer.len() == 256 {
return false;
}
self.buffer.insert(0, item);
return true;
}
}
impl SerialBuffer {
pub fn put_char(&mut self, item: char) -> bool {
if self.buffer.len() == 256 {
return false;
}
self.buffer.insert(0, item as u8);
return true;
}
}
impl SerialBuffer {
pub fn put_string(&mut self, items: String) -> bool {
for item in items.chars() {
if self.buffer.len() == 256 {
return false;
}
self.buffer.insert(0, item as u8);
}
return true;
}
}
impl SerialBuffer {
pub fn put_all(&mut self, items: Vec<u8>) -> bool {
for item in items {
if self.buffer.len() == 256 {
return false;
}
self.buffer.insert(0, item);
}
return true;
}
}
impl SerialBuffer {
pub fn put_all_char(&mut self, items: Vec<char>) -> bool {
for item in items {
if self.buffer.len() == 256 {
return false;
}
self.buffer.insert(0, item as u8);
}
return true;
}
}
impl SerialBuffer {
pub fn take(&mut self) -> Option<u8> {
self.buffer.pop()
}
}
impl SerialBuffer {
pub fn take_all(&mut self) -> Vec<u8> {
let mut result: Vec<u8> = Vec::new();
while self.buffer.len() > 0 {
result.push(self.buffer.pop().unwrap());
}
return result;
}
}
impl SerialBuffer {
pub fn clear(&mut self) {
self.buffer.clear()
}
}
impl SerialBuffer {
pub fn has_bytes(&self) -> bool {
self.buffer.len() > 0
}
}
pub struct Stack {
stack_pointer: u8,
stack: [u16; 16],
}
impl Stack {
pub fn new() -> Stack {
return Stack {
stack_pointer: 0,
stack: [0; 16],
};
}
}
impl Stack {
pub fn push(&mut self, item: u16) -> bool {
if self.stack_pointer < 15 {
self.stack[self.stack_pointer as usize] = item;
self.stack_pointer += 1;
return true;
}
for i in 0..15 {
self.stack[i] = self.stack[i + 1];
}
self.stack[self.stack_pointer as usize] = item;
return false;
}
pub fn pop(&mut self) -> u16 {
if self.stack_pointer > 0 {
self.stack_pointer -= 1;
return self.stack[self.stack_pointer as usize];
}
return 0;
}
}
impl fmt::Debug for Stack {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut stack: String = String::new();
for index in 0..self.stack_pointer {
stack = format!("{:04x}", self.stack[index as usize]) + stack.as_str();
if index + 1 != self.stack_pointer {
stack = " ".to_string() + stack.as_str();
}
}
write!(f, "{{{}}}", stack)
}
}
pub struct Machine {
pub memory: [u8; 65536],
pub registers: [u16; 4],
pub accumulator: u16,
pub instruction_pointer: u16,
pub stack: Stack,
pub instruction_pointer_stack: Stack,
pub flags: Flags,
pub clock_speed_hz: f64,
pub output_buffer: SerialBuffer,
pub input_buffer: SerialBuffer,
}
impl Machine {
pub fn new() -> Machine {
return Machine {
memory: [0; 65536],
registers: [0; 4],
accumulator: 0,
instruction_pointer: 0,
stack: Stack::new(),
instruction_pointer_stack: Stack::new(),
flags: Flags {
halt: false,
carry: false,
overflow: false,
test: false,
},
clock_speed_hz: 0.0,
output_buffer: SerialBuffer::new(),
input_buffer: SerialBuffer::new(),
};
}
}
impl Machine {
fn format_memory(&self) -> String {
let mut result: String = String::new();
let mut first: bool = true;
let mut interesting_count: usize = 0;
for index in 0..65536 {
if self.memory[index] != 0 {
if interesting_count == 0 {
first = true;
}
interesting_count = 3;
} else if interesting_count > 0 {
interesting_count -= 1;
if interesting_count == 0 {
result += format!(" [{:04x}] ... ", index).as_str();
}
}
if interesting_count > 0 {
if first {
first = false;
result += format!("[{:04x}] ", index).as_str();
} else {
result += " ";
}
result += format!("{:02x}", self.memory[index]).as_str();
}
}
return result;
}
}
impl Machine {
pub fn step(&mut self) {
let loc: u8 = self.memory[self.instruction_pointer as usize];
if let Some(inst) = instructions::find_inst_by_opcode(&loc) {
(inst.run)(self);
if self.clock_speed_hz != 0.0 {
let instruction_speed: f64 =
(inst.clock_cycles as f64) * (1.0f64 / self.clock_speed_hz) * 1000.0f64;
thread::sleep(Duration::from_millis(instruction_speed as u64));
}
}
}
}
impl Machine {
pub fn format_inst(&mut self) -> String {
let loc: u8 = self.memory[self.instruction_pointer as usize];
if let Some(inst) = instructions::find_inst_by_opcode(&loc) {
let mut data: String = String::new();
let mut byte_count: u16 = 0;
for _ in 0..((inst.bytes_per_arg as usize) * (inst.num_args as usize)) {
if byte_count != 0 {
data += " ";
if byte_count % inst.bytes_per_arg as u16 == 0 {
data += ". ";
}
}
data += format!(
"{:02x}",
self.memory[(self.instruction_pointer + 1 + byte_count) as usize]
).as_str();
byte_count += 1;
}
return format!(
"[{:04x}] {} ({:02x} | {})",
self.instruction_pointer,
inst.inst,
loc,
data
).to_string();
} else {
return format!("Unknown Instruction {:2x}", loc).to_string();
}
}
}
impl fmt::Debug for Machine {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"Machine {{
acc: {},
ip: {},
ip_stack: {:?},
stack: {:?},
flags: {:?},
sp_reg: {{r0:{:04x}, r1:{:04x}, r2:{:04x}, r3:{:04x}}},
memory: {}
}}",
format!("{:04x}: ", self.accumulator),
format!("{:04x}: ", self.instruction_pointer),
self.instruction_pointer_stack,
self.stack,
self.flags,
self.registers[0],
self.registers[1],
self.registers[2],
self.registers[3],
self.format_memory(),
)
}
}
| true
|
541ebf070482bbb671be9c652d6058c8736c4194
|
Rust
|
LuisAyuso/quepintoyo
|
/qpy_core/src/error.rs
|
UTF-8
| 647
| 2.6875
| 3
|
[] |
no_license
|
#[derive(Debug)]
pub enum Conversion {
BsonFailed,
JsonFailed,
VersionUnknown,
}
impl std::convert::From<crate::error::Conversion> for rocket::http::Status {
fn from(error: crate::error::Conversion) -> rocket::http::Status {
println!("error: {:?}", error);
rocket::http::Status::InternalServerError
}
}
#[derive(Debug)]
pub enum Db {
ConnectionError,
QuerryError,
LogicalError,
NotFound,
}
impl std::convert::From<Db> for rocket::http::Status {
fn from(error: Db) -> rocket::http::Status {
println!("error: {:?}", error);
rocket::http::Status::InternalServerError
}
}
| true
|
b6d49bd075e2ca07d127b632375dd2a70a6acc56
|
Rust
|
infiniteprairie/rust-newbie
|
/simple_tree/src/main.rs
|
UTF-8
| 1,508
| 3.328125
| 3
|
[] |
no_license
|
//! This sample program, `simple_tree`, is taken from the Rust Book,
//! chapter 15.6 (https://doc.rust-lang.org/book/ch15-06-reference-cycles.html)
//! on smart pointers, strong and weak references
//!
use std::cell::RefCell;
use std::rc::{Rc, Weak};
#[derive(Debug)]
struct Node {
value: i32,
parent: RefCell<Weak<Node>>,
children: RefCell<Vec<Rc<Node>>>,
}
fn main() {
let leaf = Rc::new( Node {
value: 3,
parent: RefCell::new(Weak::new()),
children: RefCell::new(vec![]),
});
println!("_leaf_ strong={}, weak={}",
Rc::strong_count(&leaf),
Rc::weak_count(&leaf)
);
{
let branch = Rc::new( Node {
value: 5,
parent: RefCell::new(Weak::new()),
children: RefCell::new(vec![Rc::clone(&leaf)]),
});
*leaf.parent.borrow_mut() = Rc::downgrade(&branch);
println!("inner scope...");
println!("_branch_ strong={}, weak={}",
Rc::strong_count(&branch),
Rc::weak_count(&branch)
);
println!("_leaf_ strong={}, weak={}",
Rc::strong_count(&leaf),
Rc::weak_count(&leaf)
);
println!("leaf parent = {:?}", leaf.parent.borrow().upgrade());
}
println!("outer scope...");
println!("_leaf_ strong={}, weak={}",
Rc::strong_count(&leaf),
Rc::weak_count(&leaf)
);
println!("leaf parent = {:?}", leaf.parent.borrow().upgrade());
}
| true
|
db1dce83fbacd7cf542337480a82a5323a4d28d8
|
Rust
|
acmfi/AdventCode
|
/2022/andsanmar/src/day12.rs
|
UTF-8
| 2,434
| 3.25
| 3
|
[] |
no_license
|
use std::collections::HashSet;
type Struct = Vec<Vec<u64>>;
fn find(c: char, l : &Struct) -> (usize, usize){
let code = c as u64;
for i in 0..l.len() {
for j in 0..l[i].len() {
if l[i][j] == code {
return (i,j)
}
}
}
(0,0)
}
fn update_elems((i,j): (usize, usize), vals: &mut Vec<Vec<Option<u64>>>, l: &Struct) -> Vec<(usize,usize)> {
let mut coords = vec![(i+1,j),(i,j+1)];
if i!=0 { coords.push((i-1,j)); }
if j!=0 { coords.push((i,j-1)); }
let mut updated = vec![];
for (x,y) in coords {
if let Some(v) = l.get(x) {
if let Some(e) = v.get(y) {
if e-1 <= l[i][j] {
if vals[x][y] == None || vals[x][y] > vals[i][j] {
vals[x][y] = Some(vals[i][j].unwrap() + 1);
updated.push((x,y))
}
}
}
}
}
updated
}
fn path(start : (usize, usize), end : (usize, usize), l : &Struct) -> Option<u64> {
let mut vals = vec![vec![None;l[0].len()];l.len()];
vals[start.0][start.1] = Some(0);
let mut to_inspect = HashSet::from([start]);
while vals[end.0][end.1] == None {
let updated = to_inspect.iter().map(|coord| update_elems(*coord, &mut vals, l)).flatten().collect();
to_inspect = updated;
if to_inspect.is_empty() {
break
}
}
vals[end.0][end.1]
}
fn stars(l : &mut Struct) {
let start = find('S', &l);
l[start.0][start.1] = 'a' as u64;
let end = find('E', &l);
l[end.0][end.1] = 'z' as u64;
let l : &Struct = l;
println!("{}", path(start, end, l).unwrap()); // star1
let vals = (0..l.len()).map(|i| {
(0..l[i].len()).filter_map(move |j| {
if l[i][j] == 'a' as u64 {
path((i,j), end, l)
} else {
None
}
})
}).flatten();
println!("{}", vals.min().unwrap());
}
fn main() {
let args: Vec<String> = std::env::args().collect();
if args.len() < 2 {
eprintln!("Feed me with the input!");
std::process::exit(1);
};
let mut l : Struct = std::fs::read_to_string(args[1].clone()).unwrap().lines().filter_map(|l| {
if !l.is_empty() {
Some(l.chars().map(|c| c as u64).collect())
}
else { None }
}).collect();
stars(&mut l);
}
| true
|
441c70d1e98f833516d26360ba2e8625ce77e50f
|
Rust
|
mlsteele/wavebrush
|
/lib/src/sample.rs
|
UTF-8
| 1,339
| 3.265625
| 3
|
[] |
no_license
|
// Convert between sample representations.
pub trait SampleConvertTrait<X,Y> {
fn convert(x: X) -> Y;
}
pub struct SampleConvert {}
impl SampleConvertTrait<i32, f64> for SampleConvert {
fn convert(x: i32) -> f64 {
match x as f64 / std::i32::MAX as f64 {
y if y > 1. => 1.,
y if y < -1. => -1.,
y => y,
}
}
}
impl SampleConvertTrait<i16, f64> for SampleConvert {
fn convert(x: i16) -> f64 {
match x as f64 / std::i16::MAX as f64 {
y if y > 1. => 1.,
y if y < -1. => -1.,
y => y,
}
}
}
impl SampleConvertTrait<i16, f32> for SampleConvert {
fn convert(x: i16) -> f32 {
match x as f32 / std::i16::MAX as f32 {
y if y > 1. => 1.,
y if y < -1. => -1.,
y => y,
}
}
}
impl SampleConvertTrait<f64, i16> for SampleConvert {
fn convert(x: f64) -> i16 {
let max = std::i16::MAX;
match (x * max as f64) as i16 {
y if y > max => max,
y if y < -max => -max,
y => y,
}
}
}
impl SampleConvertTrait<f32, f64> for SampleConvert {
fn convert(x: f32) -> f64 {
x as f64
}
}
impl SampleConvertTrait<f64, f32> for SampleConvert {
fn convert(x: f64) -> f32 {
x as f32
}
}
| true
|
114eb3c07c904e9c56296749f97080ed6038696a
|
Rust
|
aDotInTheVoid/noria
|
/server/src/controller/security/group.rs
|
UTF-8
| 1,971
| 3.1875
| 3
|
[
"MIT",
"Apache-2.0"
] |
permissive
|
use crate::controller::security::policy::Policy;
use nom_sql::parser as sql_parser;
use nom_sql::SqlQuery;
use serde_json;
use serde_json::Value;
#[derive(Clone, Debug, Hash, PartialEq, Serialize, Deserialize)]
pub struct Group {
name: String,
membership: SqlQuery,
policies: Vec<Policy>,
}
impl Group {
pub fn parse(grou_txt: &str) -> Vec<Group> {
let groups: Vec<Value> = match serde_json::from_str(grou_txt) {
Ok(v) => v,
Err(e) => panic!(e.to_string()),
};
groups
.iter()
.map(|g| {
let name = g["name"].as_str().unwrap();
let membership = g["membership"].as_str().unwrap();
let policies = format!("{}", g["policies"]);
Group {
name: name.to_string(),
membership: sql_parser::parse_query(membership).unwrap(),
policies: Policy::parse(&policies),
}
})
.collect()
}
pub fn membership(&self) -> SqlQuery {
self.membership.clone()
}
pub fn name(&self) -> String {
self.name.clone()
}
pub fn policies(&self) -> &[Policy] {
self.policies.as_slice()
}
}
mod tests {
#[test]
fn it_parses() {
use super::*;
let membership = "select uid, cid FROM tas";
let group_text = r#"
[
{
"name": "ta",
"membership": "select uid, cid FROM tas;",
"policies": [
{ "table": "post", "predicate": "WHERE post.type = ?" }
]
}
]"#;
let groups = Group::parse(group_text);
assert_eq!(groups.len(), 1);
assert_eq!(groups[0].name, "ta");
assert_eq!(
groups[0].membership,
sql_parser::parse_query(membership).unwrap()
);
}
}
| true
|
befa2cd77fb441bccd068f1df0ccfa9a0d7d496d
|
Rust
|
etclabscore/jade-signer-rpc
|
/src/util/rlp.rs
|
UTF-8
| 15,289
| 3.53125
| 4
|
[
"Apache-2.0"
] |
permissive
|
//! RLP (Recursive Length Prefix) is to encode arbitrarily nested arrays of binary data,
//! RLP is the main encoding method used to serialize objects in Ethereum.
//!
//! See [RLP spec](https://github.com/ethereumproject/wiki/wiki/RLP)
use super::{bytes_count, to_bytes, trim_bytes};
/// The `WriteRLP` trait is used to specify functionality of serializing data to RLP bytes
pub trait WriteRLP {
/// Writes itself as RLP bytes into specified buffer
fn write_rlp(&self, buf: &mut Vec<u8>);
}
/// A list serializable to RLP
#[derive(Debug)]
pub struct RLPList {
tail: Vec<u8>,
}
impl RLPList {
/// Start with provided vector
pub fn from_slice<T: WriteRLP>(items: &[T]) -> RLPList {
let mut start = RLPList { tail: Vec::new() };
for i in items {
start.push(i)
}
start
}
/// Add an item to the list
pub fn push<T: WriteRLP + ?Sized>(&mut self, item: &T) {
item.write_rlp(&mut self.tail);
}
}
impl Default for RLPList {
fn default() -> RLPList {
RLPList { tail: Vec::new() }
}
}
impl Into<Vec<u8>> for RLPList {
fn into(self) -> Vec<u8> {
let mut res: Vec<u8> = Vec::new();
match self.tail.len() {
s @ 0..=55 => {
res.push((s + 192) as u8);
res.extend(self.tail.as_slice());
}
v => {
let sb = to_bytes(v as u64, 8);
let size_arr = trim_bytes(&sb);
res.push((size_arr.len() + 247) as u8);
res.extend(size_arr);
res.extend(self.tail.as_slice());
}
}
res
}
}
impl WriteRLP for str {
fn write_rlp(&self, buf: &mut Vec<u8>) {
let bytes = self.as_bytes();
if self.len() == 1 && bytes[0] <= 0x7f {
buf.push(bytes[0]);
} else {
bytes.write_rlp(buf);
}
}
}
impl WriteRLP for String {
fn write_rlp(&self, buf: &mut Vec<u8>) {
let bytes = self.as_bytes();
if self.len() == 1 && bytes[0] <= 0x7f {
buf.push(bytes[0]);
} else {
bytes.write_rlp(buf);
}
}
}
impl WriteRLP for u8 {
fn write_rlp(&self, buf: &mut Vec<u8>) {
if *self == 0 {
buf.push(0x80);
} else if *self <= 0x7f {
buf.push(*self);
} else {
trim_bytes(&to_bytes(u64::from(*self), 1)).write_rlp(buf);
}
}
}
impl WriteRLP for u16 {
fn write_rlp(&self, buf: &mut Vec<u8>) {
if *self == 0 {
buf.push(0x80);
} else if *self <= 0x7f {
buf.push(*self as u8);
} else {
trim_bytes(&to_bytes(u64::from(*self), 2)).write_rlp(buf);
}
}
}
impl WriteRLP for u32 {
fn write_rlp(&self, buf: &mut Vec<u8>) {
if *self == 0 {
buf.push(0x80);
} else if *self <= 0x7f {
buf.push(*self as u8);
} else {
trim_bytes(&to_bytes(u64::from(*self), 4)).write_rlp(buf);
}
}
}
impl WriteRLP for u64 {
fn write_rlp(&self, buf: &mut Vec<u8>) {
if *self == 0 {
buf.push(0x80);
} else if *self <= 0x7f {
buf.push(*self as u8);
} else {
trim_bytes(&to_bytes(*self, 8)).write_rlp(buf);
}
}
}
impl<'a, T: WriteRLP + ?Sized> WriteRLP for Option<&'a T> {
fn write_rlp(&self, buf: &mut Vec<u8>) {
match *self {
Some(x) => x.write_rlp(buf),
None => [].write_rlp(buf),
};
}
}
impl<T: WriteRLP> WriteRLP for Vec<T> {
fn write_rlp(&self, buf: &mut Vec<u8>) {
RLPList::from_slice(self).write_rlp(buf);
}
}
impl WriteRLP for [u8] {
fn write_rlp(&self, buf: &mut Vec<u8>) {
let len = self.len();
if len <= 55 {
// Otherwise, if a string is 0-55 bytes long, the RLP encoding consists of a single byte
// with value 0x80 plus the length of the string followed by the string. The range of
// the first byte is thus [0x80, 0xb7].
buf.push(0x80 + len as u8);
buf.extend_from_slice(self);
} else {
// If a string is more than 55 bytes long, the RLP encoding consists of a single byte
// with value 0xb7 plus the length in bytes of the length of the string in binary form,
// followed by the length of the string, followed by the string. For example, a
// length-1024 string would be encoded as \xb9\x04\x00 followed by the string. The
// range of the first byte is thus [0xb8, 0xbf].
let len_bytes = bytes_count(len);
buf.push(0xb7 + len_bytes);
buf.extend_from_slice(&to_bytes(len as u64, len_bytes));
buf.extend_from_slice(self);
}
}
}
impl WriteRLP for RLPList {
fn write_rlp(&self, buf: &mut Vec<u8>) {
let len = self.tail.len();
if len <= 55 {
// If the total payload of a list (i.e. the combined length of all its items) is 0-55
// bytes long, the RLP encoding consists of a single byte with value 0xc0 plus the
// length of the list followed by the concatenation of the RLP encodings of the items.
// The range of the first byte is thus [0xc0, 0xf7].
buf.push((0xc0 + len) as u8);
} else {
// If the total payload of a list is more than 55 bytes long, the RLP encoding consists
// of a single byte with value 0xf7 plus the length in bytes of the length of the
// payload in binary form, followed by the length of the payload, followed by the
// concatenation of the RLP encodings of the items. The range of the first byte is
// thus [0xf8, 0xff].
let len_bytes = bytes_count(len);
buf.push(0xf7 + len_bytes);
buf.extend_from_slice(&to_bytes(len as u64, len_bytes));
}
buf.extend_from_slice(&self.tail);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::tests::*;
#[test]
fn encode_zero() {
let mut buf = Vec::new();
0u8.write_rlp(&mut buf);
assert_eq!([0x80], buf.as_slice());
}
#[test]
fn encode_smallint() {
let mut buf = Vec::new();
1u8.write_rlp(&mut buf);
assert_eq!([0x01], buf.as_slice());
}
#[test]
fn encode_smallint2() {
let mut buf = Vec::new();
16u8.write_rlp(&mut buf);
assert_eq!([0x10], buf.as_slice());
}
#[test]
fn encode_smallint3() {
let mut buf = Vec::new();
79u8.write_rlp(&mut buf);
assert_eq!([0x4f], buf.as_slice());
}
#[test]
fn encode_smallint4() {
let mut buf = Vec::new();
127u8.write_rlp(&mut buf);
assert_eq!([0x7f], buf.as_slice());
}
#[test]
fn encode_mediumint1() {
let mut buf = Vec::new();
128u16.write_rlp(&mut buf);
assert_eq!([0x81, 0x80], buf.as_slice());
}
#[test]
fn encode_mediumint2() {
let mut buf = Vec::new();
1000u16.write_rlp(&mut buf);
assert_eq!([0x82, 0x03, 0xe8], buf.as_slice());
}
#[test]
fn encode_mediumint3() {
let mut buf = Vec::new();
100000u32.write_rlp(&mut buf);
assert_eq!([0x83, 0x01, 0x86, 0xa0], buf.as_slice());
}
#[test]
fn encode_mediumint4() {
let mut buf = Vec::new();
Vec::from_hex("102030405060708090a0b0c0d0e0f2")
.unwrap()
.as_slice()
.write_rlp(&mut buf);
assert_eq!("8f102030405060708090a0b0c0d0e0f2", hex::encode(buf));
}
#[test]
fn encode_mediumint5() {
let mut buf = Vec::new();
hex::decode("0100020003000400050006000700080009000a000b000c000d000e01")
.unwrap()
.as_slice()
.write_rlp(&mut buf);
assert_eq!(
"9c0100020003000400050006000700080009000a000b000c000d000e01",
hex::encode(buf)
);
}
#[test]
fn encode_empty_str() {
let mut buf = Vec::new();
"".write_rlp(&mut buf);
assert_eq!([0x80], buf.as_slice());
}
#[test]
fn encode_short_str() {
let mut buf = Vec::new();
"dog".write_rlp(&mut buf);
assert_eq!([0x83, b'd', b'o', b'g'], buf.as_slice());
}
#[test]
fn encode_normal_str() {
let mut buf = Vec::new();
"Lorem ipsum dolor sit amet, consectetur adipisicing eli".write_rlp(&mut buf);
assert_eq!(
"b74c6f72656d20697073756d20646f6c6f722073697420616d65742c20636f6e\
7365637465747572206164697069736963696e6720656c69",
hex::encode(buf)
);
}
#[test]
fn encode_long_str() {
let mut buf = Vec::new();
"Lorem ipsum dolor sit amet, consectetur adipisicing elit".write_rlp(&mut buf);
assert_eq!(
"b8384c6f72656d20697073756d20646f6c6f722073697420616d65742c20636f\
6e7365637465747572206164697069736963696e6720656c6974",
hex::encode(buf)
);
}
#[test]
fn encode_extra_long_str() {
let mut buf = Vec::new();
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur mauris magna, \
suscipit sed vehicula non, iaculis faucibus tortor. Proin suscipit ultricies malesuada. \
Duis tortor elit, dictum quis tristique eu, ultrices at risus. Morbi a est imperdiet mi \
ullamcorper aliquet suscipit nec lorem. Aenean quis leo mollis, vulputate elit varius, \
consequat enim. Nulla ultrices turpis justo, et posuere urna consectetur nec. Proin non \
convallis metus. Donec tempor ipsum in mauris congue sollicitudin. Vestibulum ante ipsum \
primis in faucibus orci luctus et ultrices posuere cubilia Curae; Suspendisse convallis \
sem vel massa faucibus, eget lacinia lacus tempor. Nulla quis ultricies purus. Proin \
auctor rhoncus nibh condimentum mollis. Aliquam consequat enim at metus luctus, a \
eleifend purus egestas. Curabitur at nibh metus. Nam bibendum, neque at auctor \
tristique, lorem libero aliquet arcu, non interdum tellus lectus sit amet eros. Cras \
rhoncus, metus ac ornare cursus, dolor justo ultrices metus, at ullamcorper volutpat"
.write_rlp(&mut buf);
assert_eq!(
"b904004c6f72656d20697073756d20646f6c6f722073697420616d65742c2063\
6f6e73656374657475722061646970697363696e6720656c69742e2043757261\
6269747572206d6175726973206d61676e612c20737573636970697420736564\
207665686963756c61206e6f6e2c20696163756c697320666175636962757320\
746f72746f722e2050726f696e20737573636970697420756c74726963696573\
206d616c6573756164612e204475697320746f72746f7220656c69742c206469\
6374756d2071756973207472697374697175652065752c20756c747269636573\
2061742072697375732e204d6f72626920612065737420696d70657264696574\
206d6920756c6c616d636f7270657220616c6971756574207375736369706974\
206e6563206c6f72656d2e2041656e65616e2071756973206c656f206d6f6c6c\
69732c2076756c70757461746520656c6974207661726975732c20636f6e7365\
7175617420656e696d2e204e756c6c6120756c74726963657320747572706973\
206a7573746f2c20657420706f73756572652075726e6120636f6e7365637465\
747572206e65632e2050726f696e206e6f6e20636f6e76616c6c6973206d6574\
75732e20446f6e65632074656d706f7220697073756d20696e206d6175726973\
20636f6e67756520736f6c6c696369747564696e2e20566573746962756c756d\
20616e746520697073756d207072696d697320696e206661756369627573206f\
726369206c756374757320657420756c74726963657320706f73756572652063\
7562696c69612043757261653b2053757370656e646973736520636f6e76616c\
6c69732073656d2076656c206d617373612066617563696275732c2065676574\
206c6163696e6961206c616375732074656d706f722e204e756c6c6120717569\
7320756c747269636965732070757275732e2050726f696e20617563746f7220\
72686f6e637573206e69626820636f6e64696d656e74756d206d6f6c6c69732e\
20416c697175616d20636f6e73657175617420656e696d206174206d65747573\
206c75637475732c206120656c656966656e6420707572757320656765737461\
732e20437572616269747572206174206e696268206d657475732e204e616d20\
626962656e64756d2c206e6571756520617420617563746f7220747269737469\
7175652c206c6f72656d206c696265726f20616c697175657420617263752c20\
6e6f6e20696e74657264756d2074656c6c7573206c6563747573207369742061\
6d65742065726f732e20437261732072686f6e6375732c206d65747573206163\
206f726e617265206375727375732c20646f6c6f72206a7573746f20756c7472\
69636573206d657475732c20617420756c6c616d636f7270657220766f6c7574\
706174",
hex::encode(buf)
);
}
#[test]
fn encode_bytearray() {
let mut buf = Vec::new();
[].write_rlp(&mut buf);
assert_eq!([0x80], buf.as_slice());
}
#[test]
fn encode_single_bytearray() {
let mut buf = Vec::new();
[0].write_rlp(&mut buf);
assert_eq!([0x81, 0x00], buf.as_slice());
}
#[test]
fn encode_bytestring00() {
let mut buf = Vec::new();
"\u{0000}".write_rlp(&mut buf);
assert_eq!([0x00], buf.as_slice());
}
#[test]
fn encode_bytestring01() {
let mut buf = Vec::new();
"\u{0001}".write_rlp(&mut buf);
assert_eq!([0x01], buf.as_slice());
}
#[test]
fn encode_bytestring7f() {
let mut buf = Vec::new();
"\u{007f}".write_rlp(&mut buf);
assert_eq!([0x7f], buf.as_slice());
}
#[test]
fn encode_empty_option() {
let mut buf = Vec::new();
let val: Option<&str> = None;
val.write_rlp(&mut buf);
assert_eq!([0x80], buf.as_slice())
}
#[test]
fn encode_empty_list() {
let mut buf = Vec::new();
let list: Vec<u8> = vec![];
list.write_rlp(&mut buf);
assert_eq!([0xc0], buf.as_slice());
}
#[test]
fn encode_simple_list() {
let mut buf = Vec::new();
let list = vec!["cat".to_string(), "dog".to_string()];
list.write_rlp(&mut buf);
assert_eq!(
[0xc8, 0x83, b'c', b'a', b't', 0x83, b'd', b'o', b'g'],
buf.as_slice()
);
}
#[test]
fn encode_nested_lists() {
// [ [], [[]], [ [], [[]] ] ]
let mut buf = Vec::new();
let mut list = RLPList::default();
list.push(&RLPList::default());
let mut item1 = RLPList::default();
item1.push(&RLPList::default());
list.push(&item1);
let mut item2 = RLPList::default();
item2.push(&RLPList::default());
let mut item21 = RLPList::default();
item21.push(&RLPList::default());
item2.push(&item21);
list.push(&item2);
list.write_rlp(&mut buf);
assert_eq!(
[0xc7, 0xc0, 0xc1, 0xc0, 0xc3, 0xc0, 0xc1, 0xc0],
buf.as_slice()
);
}
}
| true
|
8d13cc0f5b545e66b929e4da0d385db4d0d5543d
|
Rust
|
voximity/omegga-discord-lite
|
/src/format.rs
|
UTF-8
| 2,276
| 3.234375
| 3
|
[] |
no_license
|
use lazy_static::lazy_static;
use regex::Regex;
#[derive(Debug, Clone)]
pub struct Formatter {
pub key: &'static str,
pub value: String,
}
impl Formatter {
pub fn format(&self, source: String) -> String {
source.replace(&format!("${}", self.key), self.value.as_str())
}
}
/// Compose a Vec<T> from a bunch of other Vec<T>s in one big Vec<Vec<T>>.
pub fn compose_vec<T>(vecs: Vec<Vec<T>>) -> Vec<T> {
let mut vec = vec![];
for v in vecs.into_iter() {
vec.extend(v.into_iter());
}
vec
}
/// Format some text with the formatters provided.
pub fn format_content(text: String, formatters: &[Formatter]) -> String {
let mut buf = text;
for formatter in formatters.iter() {
buf = formatter.format(buf);
}
buf
}
/// With a list of roles, determine the highest role list string.
pub fn role_text(roles: &[String], list: &[String]) -> String {
let list = list
.iter()
.filter_map(|s| s.split_once(':'))
.collect::<Vec<_>>();
for role in roles.iter() {
if let Some((_, m)) = list.iter().find(|(r, _)| r == role) {
return String::from(*m);
}
}
if let Some((_, m)) = list.iter().find(|(r, _)| *r == "default") {
return String::from(*m);
}
String::new()
}
/// Convert a Discord MD formatted message to Brickadia's chat codes.
pub fn format_to_game(source: String) -> String {
lazy_static! {
static ref REGEXES: Vec<(Regex, &'static str)> = vec![
(
Regex::new("<:br_([A-Za-z_]+):\\d+>").unwrap(),
"<emoji>$1</>"
),
(
Regex::new("<@!(\\d+)>").unwrap(),
"<link=\"https://discord.com/users/$1\">@mentioned</>"
),
(Regex::new("`(.+)`").unwrap(), "<code>$1</>"),
(Regex::new("\\*\\*(.+)\\*\\*").unwrap(), "<b>$1</>"),
(Regex::new("\\*(.+)\\*").unwrap(), "<i>$1</>"),
(Regex::new("__(.+)__").unwrap(), "<u>$1</>"),
(Regex::new("_(.+)_").unwrap(), "<i>$1</>"),
];
}
let mut source = source;
for (regex, replacement) in REGEXES.iter() {
source = regex.replace_all(&source, *replacement).to_string();
}
source
}
| true
|
074ab67a2e492ef6b68bef372008d94bec85a414
|
Rust
|
PaulRaUnite/RME
|
/src/urm.rs
|
UTF-8
| 7,356
| 3.078125
| 3
|
[
"MIT"
] |
permissive
|
use std::fmt;
use std::fmt::{Debug, Formatter};
use std::ops::{Index, IndexMut};
use itertools::{enumerate, Itertools};
use pest::Parser;
use std::collections::HashMap;
#[derive(Debug)]
pub enum Instruction {
Zero(usize),
Increase(usize),
Translate {
from: usize,
to: usize,
},
Jump {
reg1: usize,
reg2: usize,
goto: usize,
},
}
#[derive(Debug)]
pub struct Memory(Vec<u64>);
pub struct Program(Vec<Instruction>);
impl Memory {
pub fn from_size(size: usize) -> Self {
Memory(vec![0; size])
}
}
impl Program {
fn compress(mut self) -> (Self, usize) {
let len = self.memory_len();
let used_registers = self.iter_registers().count();
let ratio: f64 = (used_registers as f64) / (len as f64);
if ratio > 0.70 {
return (self, len);
}
let mut mapping = HashMap::new();
let mut counter = 1usize..;
let mut remap_register = |reg: usize| -> usize {
if reg == 0 {
return 0;
}
*mapping
.entry(reg)
.or_insert_with(|| counter.next().unwrap())
};
self.0.iter_mut().for_each(|i| match i {
Instruction::Zero(reg) | Instruction::Increase(reg) => *reg = remap_register(*reg),
Instruction::Translate {
from: reg1,
to: reg2,
}
| Instruction::Jump { reg1, reg2, .. } => {
*reg1 = remap_register(*reg1);
*reg2 = remap_register(*reg2);
}
});
let len = self.memory_len();
(self, len)
}
pub fn memory_len(&self) -> usize {
self.iter_registers().max().map_or(0, |x| *x) + 1
}
}
#[derive(Debug)]
pub struct Application {
memory: Memory,
program: Program,
}
impl Application {
pub fn new(program: Program) -> Self {
let (program, memory_len) = program.compress();
Application {
memory: Memory::from_size(memory_len),
program,
}
}
pub fn from_str(content: &str) -> Result<Application, Box<dyn std::error::Error>> {
Ok(Application::new(parse(content)?))
}
pub fn run(&mut self, arguments: &[u64]) -> Result<u64, Box<dyn std::error::Error>> {
self.memory.0[1..arguments.len() + 1].copy_from_slice(arguments);
let mut line_index = 1usize;
let program_len = self.program.0.len();
while 0 < line_index && line_index < program_len + 1 {
let new_line = match self.program[line_index - 1] {
Instruction::Increase(register) => {
self.memory[register] += 1;
None
}
Instruction::Zero(register) => {
self.memory[register] = 0;
None
}
Instruction::Translate { from, to } => {
self.memory[to] = self.memory[from];
None
}
Instruction::Jump { reg1, reg2, goto } => {
if self.memory[reg1] == self.memory[reg2] {
Some(goto)
} else {
None
}
}
};
if let Some(line) = new_line {
line_index = line;
} else {
line_index += 1
}
}
Ok(self.memory[0])
}
}
impl Index<usize> for Program {
type Output = Instruction;
fn index(&self, index: usize) -> &Self::Output {
self.0.index(index)
}
}
impl Index<usize> for Memory {
type Output = u64;
fn index(&self, index: usize) -> &Self::Output {
self.0.index(index)
}
}
impl IndexMut<usize> for Memory {
fn index_mut(&mut self, index: usize) -> &mut Self::Output {
self.0.index_mut(index)
}
}
#[derive(Parser)]
#[grammar = "urm.pest"]
struct URMParser;
pub fn parse(program: &str) -> Result<Program, Box<dyn std::error::Error>> {
let pairs = URMParser::parse(Rule::program, program)?
.next()
.ok_or("no input")?
.into_inner();
let mut instructions = Vec::with_capacity(program.lines().count());
for pair in pairs {
instructions.push(match pair.as_rule() {
Rule::jump => {
let (first, second, goto) = pair
.into_inner()
.map(|x| x.as_str().parse().unwrap())
.next_tuple()
.unwrap();
Instruction::Jump {
reg1: first,
reg2: second,
goto,
}
}
Rule::succ => {
let register = pair
.into_inner()
.map(|x| x.as_str().parse().unwrap())
.next()
.unwrap();
Instruction::Increase(register)
}
Rule::zero => {
let register = pair
.into_inner()
.map(|x| x.as_str().parse().unwrap())
.next()
.unwrap();
Instruction::Zero(register)
}
Rule::tran => {
let (reg1, reg2) = pair
.into_inner()
.map(|x| x.as_str().parse().unwrap())
.next_tuple()
.unwrap();
Instruction::Translate {
from: reg1,
to: reg2,
}
}
Rule::num => panic!("should not be in the context"),
Rule::EOI | Rule::program | Rule::WHITESPACE => continue,
});
}
Ok(Program(instructions))
}
impl fmt::Debug for Program {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
let last_elem = self.0.len() - 1;
for (index, instr) in enumerate(self.0.iter()) {
write!(f, "{:?}", instr)?;
if index != last_elem {
writeln!(f)?
}
}
Ok(())
}
}
impl Program {
pub fn iter_registers(&self) -> impl Iterator<Item = &usize> {
self.0.iter().flat_map(|i| i.iter_registers())
}
}
impl Instruction {
pub fn iter_registers(&self) -> impl Iterator<Item = &usize> {
InstructionRegisters {
instruction: self,
index: 0,
}
}
}
struct InstructionRegisters<'a> {
instruction: &'a Instruction,
index: u8,
}
impl<'a> Iterator for InstructionRegisters<'a> {
type Item = &'a usize;
fn next(&mut self) -> Option<Self::Item> {
let result = match self.instruction {
Instruction::Increase(register) | Instruction::Zero(register) => match self.index {
0 => Some(register),
_ => None,
},
Instruction::Translate {
from: reg1,
to: reg2,
}
| Instruction::Jump { reg1, reg2, .. } => match self.index {
0 => Some(reg1),
1 => Some(reg2),
_ => None,
},
};
if result.is_some() {
self.index += 1
}
result
}
}
| true
|
b4ba76f8e547f2094c61c52f53235e9f68bb340c
|
Rust
|
bailion/ophelia
|
/logic/src/parse/template.rs
|
UTF-8
| 1,649
| 2.84375
| 3
|
[] |
no_license
|
use std::{fmt::Display, path::PathBuf};
use super::{block::Block, Parse, ParseResult};
#[derive(Debug, Clone, PartialEq)]
pub struct Template<'i> {
path: Option<PathBuf>,
expressions: Vec<Block<'i>>,
}
impl<'i> Parse<'i> for Template<'i> {
fn parse(mut input: &'i str) -> super::ParseResult<Self> {
let (expressions, left_over) = {
let mut output = vec![];
while !input.is_empty() {
let (out, left_over) = Block::parse(input)?;
input = left_over;
output.push(out);
}
(output, input)
};
Ok((
Self {
path: None,
expressions,
},
left_over,
))
}
fn parse_optional(mut input: &'i str) -> ParseResult<Option<Self>> {
let (expressions, left_over) = {
let mut output = vec![];
while !input.is_empty() {
let (out, left_over) = Block::parse_optional(input)?;
let out = match out {
Some(out) => out,
None => return Ok((None, left_over)),
};
input = left_over;
output.push(out);
}
(output, input)
};
Ok((
Some(Self {
path: None,
expressions,
}),
left_over,
))
}
}
impl Display for Template<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
for ast in &self.expressions {
ast.fmt(f)?;
}
Ok(())
}
}
| true
|
9b766e990672edd0852912efc8e9fe340ae9dd15
|
Rust
|
concurrentes/tp2
|
/src/main.rs
|
UTF-8
| 11,153
| 2.515625
| 3
|
[] |
no_license
|
#[macro_use]
extern crate log;
extern crate fern;
extern crate chrono;
extern crate libc;
mod configuration;
use configuration::ServerData;
use configuration::ClientData;
use std::sync::mpsc;
use std::thread;
use std::time;
use std::time::SystemTime;
use std::env;
/*==============================================================================
* Loggers
*------------------------------------------------------------------------------
*
*/
fn setup_terminal_logging() -> Result<(), fern::InitError> {
fern::Dispatch::new()
.format(|out, message, record| unsafe {
out.finish(format_args!(
"{}[{}] {}",
chrono::Local::now().format("[%Y-%m-%d][%H:%M:%S]"),
libc::pthread_self(),
message
))
})
.level(log::LevelFilter::Info)
.chain(std::io::stdout())
.apply()?;
Ok(())
}
fn setup_file_logging() -> Result<(), fern::InitError> {
fern::Dispatch::new()
.format(|out, message, record| unsafe {
out.finish(format_args!(
"{}[{}] {}",
chrono::Local::now().format("[%Y-%m-%d][%H:%M:%S]"),
libc::pthread_self(),
message
))
})
.level(log::LevelFilter::Info)
.chain(fern::log_file("output.log")?)
.apply()?;
Ok(())
}
/*==============================================================================
* Packet
*------------------------------------------------------------------------------
*
*/
struct Packet {
from: VirtualLink,
workload: u64,
origin: u32,
timestamp: SystemTime,
}
impl Packet {
fn from_iface(iface: &NetworkInterface, workload: u64, origin: u32) -> Packet {
Packet {
from: (*iface).get_virtual_link(),
workload: workload,
origin: origin,
timestamp: SystemTime::now(),
}
}
fn answer_me_at(tx: &mpsc::Sender<Packet>, workload: u64, origin: u32, timestamp: SystemTime) -> Packet {
Packet {
from: VirtualLink::linked_to(tx),
workload: workload,
origin: origin,
timestamp: timestamp,
}
}
}
/*==============================================================================
* VirtualLink
*------------------------------------------------------------------------------
*
*/
struct VirtualLink {
s: mpsc::Sender<Packet>
}
impl VirtualLink {
fn to_iface(interface: &NetworkInterface) -> VirtualLink {
VirtualLink {
s: (*interface).s.clone()
}
}
fn linked_to(tx: &mpsc::Sender<Packet>) -> VirtualLink {
VirtualLink {
s: (*tx).clone()
}
}
fn send_through(&self, packet: Packet) {
self.s.send(packet).unwrap()
}
}
/*==============================================================================
* Network Interface
*------------------------------------------------------------------------------
*
*/
struct NetworkInterface {
s: mpsc::Sender<Packet>,
r: mpsc::Receiver<Packet>
}
impl NetworkInterface {
fn new() -> NetworkInterface {
let (tx, rx) = mpsc::channel();
NetworkInterface {
s: tx,
r: rx
}
}
fn read(&self) -> Packet {
self.r.recv().unwrap()
}
fn get_virtual_link(&self) -> VirtualLink {
VirtualLink::to_iface(self)
}
}
/*==============================================================================
* Host
*
*/
struct Host {
nic: NetworkInterface,
}
impl Host {
fn new() -> Host {
Host {
nic: NetworkInterface::new(),
}
}
fn get_virtual_link(&self) -> VirtualLink {
self.nic.get_virtual_link()
}
}
/*==============================================================================
* Stats
*
*/
struct Stats {
samples: u64,
total: u64,
}
impl Stats {
fn new() -> Stats {
Stats {
samples: 0,
total: 0,
}
}
fn update_stats(&mut self, new_sample_time: u64) {
self.samples += 1;
self.total += new_sample_time;
}
fn get_average(&self) -> f64 {
if self.samples == 0 {
return 0.0;
}
(self.total as f64) / (self.samples as f64)
}
}
/*==============================================================================
* Server
*
*/
struct Server {
id: u32,
host: Host,
processing_power: u64
}
impl Server {
fn new(id: u32, server_data: ServerData) -> Server {
Server {
id: id,
host: Host::new(),
processing_power: server_data.get_processing_power()
}
}
fn get_virtual_link(&self) -> VirtualLink {
self.host.get_virtual_link()
}
fn run(self) {
info!("[S{}] Ejecutando servidor {}", self.id, self.id);
let rx = self.host.nic.r;
let tx = self.host.nic.s;
for message in rx {
// Obtenemos la cantidad de cuadrantes a procesar.
let workload = message.workload;
info!("[S{}] Recibidas {} unidades de trabajo desde observatorio {}", self.id, workload, message.origin);
/*
* Procesamos los cuadrantes.
*
* El workload tiene unidades de trabajo. El poder de procesamiento
* tiene unidades de trabajo por segundo. El sleep time tiene unidades
* de milisegundos.
*
* Por ejemplo, un servidor recibe 5 unidades de trabajo desde el
* cliente. El servidor puede procesar dos unidades de trabajo por
* segundo. El hilo dormirá entonces 2500 milisegundos simulando
* el procesamiento de la carga. Para acelerar o relentizar
* la simulación, podemos ajustar el factor global de velocidad;
* por ejemplo, si el factor global es 2.0, en vez de dormir los 2500
* milisegundos dormiría 1250.
*
*/
let sleep_time = (1000*workload)/self.processing_power;
let sleep_time_scaled = ((sleep_time as f64)/GLOBAL_SPEED) as u64;
info!("[S{}] Tiempo estimado: {}ms (s: {}ms)", self.id, sleep_time, sleep_time_scaled);
thread::sleep(time::Duration::from_millis(sleep_time_scaled));
info!("[S{}] Procesamiento terminado; devolviendo ACK a observatorio {}", self.id, message.origin);
// Devolvemos el ACK.
let response = Packet::answer_me_at(&tx, 0, self.id, message.timestamp);
message.from.send_through(response);
}
}
}
/*==============================================================================
* Client
*
*/
struct Target {
virtual_link: VirtualLink,
weight: f64
}
struct Client {
id: u32,
host: Host,
distribution_scheme: Vec<Target>,
work_generation_rate: u64
}
impl Client {
fn new(id: u32, servers: &Vec<Server>, client_data: ClientData) -> Client {
let workshare: &Vec<f64> = client_data.get_workshare();
let mut distribution = Vec::new();
for i in 0..servers.len() {
distribution.push(Target {
virtual_link: servers[i].get_virtual_link(),
weight: workshare[i]
});
}
Client {
id: id,
host: Host::new(),
distribution_scheme: distribution,
work_generation_rate: client_data.get_work_generation_rate()
}
}
fn run(self) {
info!("[C{}] Ejecutando cliente {}", self.id, self.id);
/*
* Cada cierta cantidad de tiempo, el observatorio genera x cuadrantes.
* A partir de ahí itera por la lista de servidores distribuyendo los
* cuadrantes según los factores de distribución (e.g., si debe enviar
* una fracción p_k de los cuadrantes al servidor k, enviará p_k*x
* cuadrantes al servidor k).
*
* Habiendo enviado los mensajes, simplemente espera las respuestas.
* Suponiendo alternativamente que hay que seguir generando cuadrantes
* mientras se toman fotos, se pueden tener internamente dos threads,
* uno acumulando cuadrantes y otro tomando cuadrantes y distribuyendolos.
*
* Para medir el tiempo de respuesta del observatorio se puede ir
* calculando una media móvil, tomando el tiempo que tarda en responder
* cada servidor.
*/
let targets = &self.distribution_scheme;
let mut stats : Stats = Stats::new();
loop {
let x = self.work_generation_rate;
info!("[C{}] Generando {} unidades de trabajo", self.id, x);
// Distribuimos los x cuadrantes generados.
let mut sid = 0;
for target in targets {
sid += 1;
let workload = ((x as f64)*(target.weight)) as u64;
let packet = Packet::from_iface(&self.host.nic, workload, self.id);
info!("[C{}] Enviando {} unidades al servidor {}", self.id, workload, sid);
target.virtual_link.send_through(packet);
}
// Esperamos la respuesta de cada servidor.
info!("[C{}] Esperando respuestas", self.id);
for _d in targets {
let _response = self.host.nic.read();
// Cálculo de tiempo de respuesta
let response_time_duration = _response.timestamp.elapsed().unwrap();
let response_time_ms = response_time_duration.as_secs() + ((response_time_duration.subsec_millis() * 1000) as u64);
stats.update_stats(response_time_ms);
}
// Impresión de estadística hasta el momento
info!("[C{}] Promedio de respuesta parcial: {} ms", self.id, format!("{:.*}", 2, stats.get_average()));
info!("[C{}] Todos los servidores terminaron de procesar el bache", self.id);
let sleep_time = (3000.0/GLOBAL_SPEED) as u64;
thread::sleep(time::Duration::from_millis(sleep_time));
}
}
}
/*==============================================================================
* Main
*
*/
const GLOBAL_SPEED: f64 = 1.0;
fn main() {
let args : Vec<String> = env::args().collect();
if args.len() > 1 && args[1] == "--debug" {
setup_file_logging().expect("Couldn't set up logger");
} else {
setup_terminal_logging().expect("Couldn't set up logger");
}
/*
* Cargamos la configuración. La configuración es un archivo de texto con
* pares clave-valor. El objeto de configuración puede usarse como
*
* configuration.get("clave") // retorna el valor asociado a "clave".
*/
info!("[T0] Cargando configuración");
let mut configuration = configuration::Configuration::new();
configuration.load();
let mut threads = Vec::new();
let mut servers: Vec<Server> = Vec::new();
let mut clients: Vec<Client> = Vec::new();
info!("[T0] Inicializando servidores");
let server_data: Vec<ServerData> = configuration.get_server_dataset();
let mut server_count = 0;
for d in server_data {
server_count += 1;
servers.push(Server::new(server_count, d));
}
info!("[T0] Inicializando clientes");
let client_data: Vec<ClientData> = configuration.get_client_dataset();
let mut client_count = 0;
for c in client_data {
client_count += 1;
clients.push(Client::new(client_count, &servers, c));
}
info!("[T0] Lanzando hilos servidores");
for server in servers {
let th = thread::spawn(move || {
server.run();
});
threads.push(th);
}
info!("[T0] Lanzando hilos clientes");
for client in clients {
let th = thread::spawn(move || {
client.run();
});
threads.push(th);
}
info!("[T0] Esperando la finalización del programa");
for th in threads {
th.join().unwrap();
}
}
| true
|
faf99213b2e8fb23a45f56db715651501819f87e
|
Rust
|
pjohansson/advent_of_code
|
/src/day2.rs
|
UTF-8
| 3,028
| 3.875
| 4
|
[] |
no_license
|
struct Rectangle {
x: i32,
y: i32,
z: i32
}
// Lesson learned: How to implement methods
impl Rectangle {
fn new(input: &str) -> Rectangle {
let mut sides = Vec::new();
let input_split: Vec<&str> = input.split('x').collect();
for cs in input_split {
// Lesson learned: `unwrap` returns Ok(result) from an `Option`
sides.push(cs.parse::<i32>().unwrap())
}
Rectangle { x: sides[0], y: sides[1], z: sides[2] }
}
fn area(&self) -> i32 {
2*(self.x * self.y + self.x * self.z + self.y * self.z)
}
fn get_areas(&self) -> [i32; 3] {
[ self.x * self.y, self.x * self.z, self.y * self.z ]
}
fn get_perimeters(&self) -> [i32; 3] {
[ 2*(self.x + self.y), 2*(self.x + self.z), 2*(self.y + self.z) ]
}
fn volume(&self) -> i32 {
self.x * self.y * self.z
}
}
// Lesson learned: This is another way to pass an array (specifially Vec) to a function
fn min_array(array: [i32; 3]) -> i32 {
// Lesson learned: `min` functions only on an iterator, and maybe not for floats
match array.iter().min() {
Some(&i) => i, // Lesson learned: `min` returns wrapped reference
_ => 0,
}
}
pub fn main(input: &String) -> i32 {
// Lesson learned: `sum` still not stable which is totally weird
// input.lines().map(|line| area_one_box(&line.to_string())).sum()
// Lesson learned: using a `fold` to accumulate values instead of `sum`
input.lines().fold(0, |acc, line| acc + wrap_area(&line.to_string()))
}
fn wrap_area(dim_string: &String) -> i32 {
let rectangle = Rectangle::new(dim_string);
rectangle.area() + min_array(rectangle.get_areas())
}
pub fn extra(input: &String) -> i32 {
input.lines().fold(0, |acc, line| acc + ribbon_length(&line.to_string()))
}
fn ribbon_length(dim_string: &String) -> i32 {
let rectangle = Rectangle::new(dim_string);
rectangle.volume() + min_array(rectangle.get_perimeters())
}
#[cfg(test)]
pub mod tests {
// Lesson learned: Import with easy access from tests
use utils::tests::*;
use super::*;
#[test]
fn day2a() {
let expected_answers = [
Expected { input: "2x3x4", result: 58 },
Expected { input: "1x1x10", result: 43 },
];
let expected_double = Expected { input: "2x3x4\n1x1x10\n", result: 58+43 };
// Lesson learned: Access private functions in `super` module by explicit signature
assert_all_expected(&expected_answers, super::wrap_area);
assert_one_expected(&expected_double, main);
}
#[test]
fn day2b() {
let expected_answers = [
Expected { input: "2x3x4", result: 34 },
Expected { input: "1x1x10", result: 14 },
];
let expected_double = Expected { input: "2x3x4\n1x1x10\n", result: 34+14 };
assert_all_expected(&expected_answers, super::ribbon_length);
assert_one_expected(&expected_double, extra);
}
}
| true
|
897717cc051f962e36f359fe895508a1b5c415d0
|
Rust
|
CGF95/WindWakerDebugMenu
|
/src/src/utils.rs
|
UTF-8
| 2,010
| 2.890625
| 3
|
[
"MIT"
] |
permissive
|
use libtww::prelude::*;
use libtww::Link;
use libtww::link::CollisionType;
use libtww::game::Console;
use main_menu;
use warp_menu;
use flag_menu;
use inventory_menu;
use cheat_menu;
use controller;
use spawn_menu;
pub fn clear_menu() {
let console = Console::get();
let mut lines = &mut console.lines;
for line in lines.into_iter().skip(3) {
line.clear();
}
}
pub fn transition(state: MenuState) {
clear_menu();
unsafe {
menu_state = state;
}
match state {
MenuState::MainMenu => main_menu::transition_into(),
MenuState::WarpMenu => warp_menu::transition_into(),
MenuState::FlagMenu => flag_menu::transition_into(),
MenuState::InventoryMenu => inventory_menu::transition_into(),
MenuState::CheatMenu => cheat_menu::transition_into(),
MenuState::SpawnMenu => spawn_menu::transition_into(),
}
}
pub fn move_cursor(len: usize, cursor: &mut usize) {
let console = Console::get();
let lines = &mut console.lines;
if controller::DPAD_UP.is_pressed() && *cursor > 0 {
*cursor -= 1;
while lines[*cursor + 3].len() < 3 {
*cursor -= 1;
}
} else if controller::DPAD_DOWN.is_pressed() && *cursor + 1 < len {
*cursor += 1;
while lines[*cursor + 3].len() < 3 {
*cursor += 1;
}
}
}
pub fn next_collision() {
let collision = Link::collision();
let collision = match collision {
CollisionType::Default => CollisionType::ChestStorage,
CollisionType::ChestStorage => CollisionType::DoorCancel,
CollisionType::DoorCancel => CollisionType::Default,
};
Link::set_collision(collision);
}
pub fn bool_to_text(b: bool) -> &'static str {
if b {
"on"
} else {
"off"
}
}
#[derive(Copy, Clone)]
pub enum MenuState {
MainMenu,
WarpMenu,
FlagMenu,
InventoryMenu,
CheatMenu,
SpawnMenu,
}
pub static mut menu_state: MenuState = MenuState::MainMenu;
| true
|
1b06a42bceb7ec7f35a65d170428e5baf80fe1f6
|
Rust
|
iprs-dev/iprs
|
/src/peer_id.rs
|
UTF-8
| 8,369
| 2.765625
| 3
|
[
"MIT"
] |
permissive
|
//! Module implement Peer ID for libp2p network. _Refer [peer-id] spec
//! for details.
//!
//! [peer-id]: https://github.com/libp2p/specs/blob/master/peer-ids/peer-ids.md
use bs58;
use multibase::Base;
use rand::Rng;
use std::{fmt, hash};
use crate::{
identity::PublicKey,
multibase::Multibase,
multicodec::{self, Multicodec},
multihash::Multihash,
Error, Result,
};
/// Keys that serialize to more than 42 bytes must be hashed using
/// sha256 multihash, keys that serialize to at most 42 bytes must
/// be hashed using the "identity" multihash codec.
const MAX_INLINE_KEY_LENGTH: usize = 42;
/// Unique identifier of a peer in the network.
///
/// Peer IDs are derived by hashing the encoded public-key with multihash.
///
/// PublicKey to PeerId:
///
/// * Encode the public key as described in the [keys section].
/// * If the length of the serialized bytes is less than or equal to 42,
/// compute the "identity" multihash of the serialized bytes. In other
/// words, no hashing is performed, but the multihash format is still
/// followed. The idea here is that if the serialized byte array is
/// short enough, we can fit it in a multihash verbatim without having
/// to condense it using a hash function.
/// * If the length is greater than 42, then hash it using it using the
/// SHA256 multihash.
///
/// [keys section]: https://github.com/libp2p/specs/blob/master/peer-ids/peer-ids.md#keys
#[derive(Clone, Eq)]
pub struct PeerId {
mh: Multihash,
}
impl fmt::Debug for PeerId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("PeerId").field(&self.to_base58btc()).finish()
}
}
impl fmt::Display for PeerId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.to_base58btc() {
Ok(val) => val.fmt(f),
Err(_) => Err(fmt::Error),
}
}
}
impl hash::Hash for PeerId {
fn hash<H>(&self, state: &mut H)
where
H: hash::Hasher,
{
hash::Hash::hash(&self.mh.encode().unwrap(), state)
}
}
impl PartialEq<PeerId> for PeerId {
fn eq(&self, other: &PeerId) -> bool {
self.mh == other.mh
}
}
impl From<Multihash> for PeerId {
fn from(mh: Multihash) -> Self {
PeerId { mh }
}
}
impl From<PeerId> for Multihash {
fn from(peer_id: PeerId) -> Self {
peer_id.mh
}
}
impl PeerId {
/// Builds a `PeerId` from a public key.
pub fn from_public_key(key: PublicKey) -> Result<PeerId> {
let enc_buf = key.into_protobuf_encoding()?;
let codec: Multicodec = match enc_buf.len() <= MAX_INLINE_KEY_LENGTH {
true => multicodec::IDENTITY.into(),
false => multicodec::SHA2_256.into(),
};
let mh = Multihash::new(codec, &enc_buf)?;
Ok(PeerId { mh })
}
/// Generates a random peer ID from a cryptographically secure PRNG.
///
/// This is useful for randomly walking on a DHT, or for testing purposes.
pub fn generate() -> Result<PeerId> {
let (bytes, codec) = match rand::thread_rng().gen::<bool>() {
true => {
let codec: Multicodec = multicodec::IDENTITY.into();
let bytes = rand::thread_rng().gen::<[u8; 32]>().to_vec();
(bytes, codec)
}
false => {
let codec: Multicodec = multicodec::SHA2_256.into();
let bytes = {
let mut data = vec![];
data.extend_from_slice(&rand::thread_rng().gen::<[u8; 32]>());
data.extend_from_slice(&rand::thread_rng().gen::<[u8; 32]>());
data
};
(bytes, codec)
}
};
let mh = Multihash::new(codec, &bytes)?;
Ok(PeerId { mh })
}
/// Decode a base encoded PeerId, human readable text. Peerid format
/// can either be in legacy format (base58btc) or multi-base encoded
/// CID format.
pub fn from_text(text: &str) -> Result<PeerId> {
let mut chars = text.chars();
let peer_id = match (chars.next(), chars.next()) {
(Some('Q'), Some('m')) | (Some('1'), Some(_)) => {
// legacy format base58btc.
let bytes = err_at!(BadInput, bs58::decode(text.as_bytes()).into_vec())?;
let (mh, _) = Multihash::decode(&bytes)?;
PeerId { mh }
}
_ => {
let bytes = {
let mb = Multibase::from_text(text)?;
match mb.to_bytes() {
Some(bytes) => bytes,
None => err_at!(BadInput, msg: "{}", text)?,
}
};
// <multicodec-cidv1><libp2p-key-codec><multihash>
let (codec, bytes) = Multicodec::decode(&bytes)?;
match codec.to_code() {
multicodec::CID_V1 => (),
_ => err_at!(BadInput, msg: "CID {}", codec)?,
}
let (codec, bytes) = Multicodec::decode(bytes)?;
match codec.to_code() {
multicodec::LIBP2P_KEY => (),
_ => err_at!(BadInput, msg: "codec {}", codec)?,
}
let (mh, _) = Multihash::decode(bytes)?;
PeerId { mh }
}
};
Ok(peer_id)
}
/// Encode peer-id to base58btc format.
pub fn to_base58btc(&self) -> Result<String> {
Ok(bs58::encode(self.mh.encode()?).into_string())
}
/// Encode peer-id to multi-base encoded CID format.
pub fn to_base_text(&self, base: Base) -> Result<String> {
let mut data = {
let codec = Multicodec::from_code(multicodec::CID_V1)?;
codec.encode()?
};
{
let codec = Multicodec::from_code(multicodec::LIBP2P_KEY)?;
data.extend_from_slice(&codec.encode()?);
};
data.extend_from_slice(&self.mh.encode()?);
Ok(Multibase::with_base(base.clone(), &data)?.to_text()?)
}
/// Encode PeerId into multihash-binary-format.
///
/// **NOTE:** This byte representation is not necessarily consistent
/// with equality of peer IDs. That is, two peer IDs may be considered
/// equal while having a different byte representation.
pub fn encode(&self) -> Result<Vec<u8>> {
self.mh.encode()
}
/// Decode PeerId from multihash-binary-format.
pub fn decode(buf: &[u8]) -> Result<(PeerId, &[u8])> {
let (mh, rem) = Multihash::decode(buf)?;
Ok((PeerId { mh }, rem))
}
/// Checks whether the public key passed as parameter matches the
/// public key of this `PeerId`.
///
/// Returns `None` if this `PeerId`s hash algorithm is not supported
/// when encoding the given public key, otherwise `Some` boolean as the
/// result of an equality check.
pub fn is_public_key(&self, public_key: &PublicKey) -> Option<bool> {
let other = PeerId::from_public_key(public_key.clone()).ok()?;
Some(self.mh == other.mh)
}
/// Return the peer-id as condensed version of PeerID::to_string().
pub fn to_short_string(&self) -> String {
use std::iter::FromIterator;
let s = self.to_string();
let chars: Vec<char> = s.chars().collect();
if chars.len() <= 10 {
String::from_iter(chars.into_iter())
} else {
let mut short = chars[..2].to_vec();
short.push('*');
short.extend_from_slice(&chars[(chars.len() - 6)..]);
String::from_iter(short.into_iter())
}
}
/// Sometimes PeerID could be encoded using IDENTITY hash. Which means,
/// unlike when it is encoded as public-key's hash, it is possible to
/// extract the public-key from the peer-id.
pub fn to_public_key(&self) -> Result<Option<PublicKey>> {
let (codec, digest) = self.mh.clone().unwrap()?;
let public_key = match codec.to_code() {
multicodec::IDENTITY => {
let public_key = PublicKey::from_protobuf_encoding(&digest)?;
Some(public_key)
}
_ => None,
};
Ok(public_key)
}
}
#[cfg(test)]
#[path = "peer_id_test.rs"]
mod peer_id_test;
| true
|
855764f02539ba7bba91c9f7d0765122728e75b8
|
Rust
|
wtommyw/haste-cli
|
/src/haste/options.rs
|
UTF-8
| 7,711
| 3.5625
| 4
|
[
"MIT"
] |
permissive
|
use regex::Regex;
pub struct Options {
pub filename: String,
pub url: String,
pub mode: Mode
}
pub enum Mode {
Upload,
Download
}
impl Options {
pub fn new(args: &[String]) -> Result<Options, &'static str> {
if args.len() < 2 {
return Err("Missing arguments");
}
let (filename, url, mode);
if Options::is_url(&args[1]) {
mode = Mode::Download;
let parsed_url = Options::convert_to_raw_url(&args[1]);
if parsed_url.is_err() {
return Err("Invalid URL provided");
}
url = parsed_url.unwrap();
if args.len() < 3 {
return Err("Missing filename");
} else {
filename = args[2].clone();
}
} else {
mode = Mode::Upload;
filename = args[1].clone();
if args.len() < 3 {
url = String::from("https://pastie.io/documents")
} else {
url = args[2].clone();
}
}
Ok(Options{ filename, url, mode })
}
fn is_url(str: &String) -> bool {
let regex = Regex::new(r"(https|http)(://)[\w]*(\.)[\w]*").unwrap_or_else(|e| {
panic!("Could not compile regex: {}", e)
});
match regex.find(str) {
Some(_) => return true,
None => return false
};
}
fn convert_to_raw_url(url: &String) -> Result<String, &'static str> {
let url_regex = Regex::new(r"(https|http)(://)[\w]*(\.)[\w]*").unwrap_or_else(|e| {
panic!("Could not compile regex: {}", e)
});
let key_regex = Regex::new(r"[\w]+$").unwrap_or_else(|e| {
panic!("Could not compile regex: {}", e)
});
let base_url_result = url_regex.find(url);
if base_url_result == None {
return Err("Invalid URL provided");
}
let base_url = String::from(base_url_result.unwrap().as_str());
let key_result = key_regex.find(url);
if key_result == None {
return Err("Invalid URL provided");
}
let key = String::from(key_result.unwrap().as_str());
Ok(format!("{}/raw/{}", base_url, key))
}
}
#[cfg(test)]
mod tests {
use super::*;
static DEFAULT_URL: &str = "https://pastie.io/documents";
static DEFAULT_URL_HTTP: &str = "https://pastie.io/documents";
fn create_upload_start_arguments() -> [String; 2] {
[String::from("command"), String::from("./test-data/test.txt")]
}
fn create_custom_upload_start_arguments(url: &String) -> [String; 3] {
[String::from("command"), String::from("./test-data/test.txt"), url.clone()]
}
fn create_download_start_arguments() -> [String; 3] {
[String::from("command"), String::from(DEFAULT_URL), String::from("./test-data/test.txt")]
}
#[test]
fn is_url_returns_true_on_https_url() {
let url = String::from(DEFAULT_URL);
assert_eq!(Options::is_url(&url), true);
}
#[test]
fn is_url_returns_true_on_http_url() {
let url = String::from(DEFAULT_URL_HTTP);
assert_eq!(Options::is_url(&url), true);
}
#[test]
fn is_url_returns_false_on_filename() {
let filename = String::from("./test-data/test.txt");
assert_eq!(Options::is_url(&filename), false);
}
#[test]
fn convert_to_raw_url_inserts_raw_after_url() {
let url = String::from("https://pastie.io/rAnd0m");
let raw_url = String::from("https://pastie.io/raw/rAnd0m");
let converted_url = Options::convert_to_raw_url(&url);
assert!(converted_url.is_ok(), "URL conversion should have succeeded");
assert_eq!(converted_url.unwrap(), raw_url);
}
#[test]
fn convert_to_raw_url_inserts_raw_after_url_even_if_already_raw() {
let url = String::from("https://pastie.io/raw/rAnd0m");
let raw_url = String::from("https://pastie.io/raw/rAnd0m");
let converted_url = Options::convert_to_raw_url(&url);
assert!(converted_url.is_ok(), "URL conversion should have succeeded");
assert_eq!(converted_url.unwrap(), raw_url);
}
#[test]
fn options_constructor_gives_error_no_arguments() {
let args: [String; 1] = [String::from("PogramName")];
match Options::new(&args) {
Ok(_) => assert!(false, "Only 1 arg (program name) was given, an error should be returned."),
Err(_) => assert!(true)
}
}
#[test]
fn options_constructor_returns_options () {
let filename = String::from("./test-data/test.txt");
let args: [String; 2] = create_upload_start_arguments();
match Options::new(&args) {
Ok(options) => assert_eq!(options.filename, filename),
Err(_) => assert!(false, "All arguments were given, method should not fail.")
}
}
#[test]
fn options_constructor_set_upload_mode_when_given_filename() {
let args: [String; 2] = create_upload_start_arguments();
match Options::new(&args) {
Ok(options) => match options.mode {
Mode::Download => assert!(false, "Filename was given, method should be upload"),
Mode::Upload => assert!(true)
},
Err(_) => assert!(false, "All arguments were given, method should not fail.")
}
}
#[test]
fn options_constructor_uses_default_upload_url_when_not_give() {
let args: [String; 2] = create_upload_start_arguments();
match Options::new(&args) {
Ok(options) => assert_eq!(options.url, DEFAULT_URL),
Err(_) => assert!(false, "All arguments were given, method should not fail.")
}
}
#[test]
fn options_constructor_uses_custom_upload_url() {
let custom_url = String::from("https://hasteb.in/documents");
let args: [String; 3] = create_custom_upload_start_arguments(&custom_url);
match Options::new(&args) {
Ok(options) => assert_eq!(options.url, custom_url),
Err(_) => assert!(false, "All arguments were given, method should not fail.")
}
}
#[test]
fn options_constructor_set_download_mode_when_given_url() {
let args: [String; 3] = create_download_start_arguments();
match Options::new(&args) {
Ok(options) => match options.mode {
Mode::Download => assert!(true),
Mode::Upload => assert!(false, "URL was given, method should be download")
},
Err(_) => assert!(false, "All arguments were given, method should not fail.")
}
}
#[test]
fn options_constructor_returns_error_on_missing_filename_when_downlaoding() {
let args: [String; 2] = [String::from("command"), String::from(DEFAULT_URL)];
match Options::new(&args) {
Ok(_options) => {
assert!(false)
}
Err(_) => assert!(true, "The only argument was an URL, method should fail")
}
}
#[test]
fn convert_to_raw_url_fails_on_invalid_url() {
let url = String::from("this is 100% not a URL");
let raw_url = Options::convert_to_raw_url(&url);
assert!(raw_url.is_err(), "An invalid URL was given so an Error was excpected");
}
#[test]
fn convert_to_raw_url_fails_on_valid_url_wihout_key() {
let url = String::from("https://google.com/");
let raw_url = Options::convert_to_raw_url(&url);
assert!(raw_url.is_err(), "An URL without a key was given so an Error was excpected");
}
}
| true
|
fc0f77bbc221ebc7d4dbc1628c435955bc5440a0
|
Rust
|
ouranoshong/rust_by_example
|
/scope_borrow_ref/src/main.rs
|
UTF-8
| 956
| 3.71875
| 4
|
[] |
no_license
|
#[derive(Clone, Copy)]
struct Point{ x: i32, y: i32 }
fn main() {
// println!("Hello, world!");
let c = 'Q';
let ref ref_c1 = c;
let ref_c2 = &c;
println!("ref_c1 equals ref_c2: {}", *ref_c1 == *ref_c2);
let point = Point {x: 0, y: 0};
let _copy_of_x = {
let Point {x: ref ref_to_x, y: _} = point;
*ref_to_x
};
let mut mutable_point = point;
{
let Point {x: _, y: ref mut mut_ref_y } = mutable_point;
* mut_ref_y = 1;
}
println!("point is ({}, {})", point.x, point.y);
println!("mutable_point is ({}, {})", mutable_point.x, mutable_point.y);
// A mutable tuple that includes a pointer
let mut mutable_tuple = (Box::new(5u32), 3u32);
{
// Destructure `mutable_tuple` to change the value of `last`.
let (_, ref mut last) = mutable_tuple;
*last = 2u32;
}
println!("tuple is {:?}", mutable_tuple);
}
| true
|
f6bf82fad8fdf8a06378e2a79d3b73a90e82f6c0
|
Rust
|
ayourtch/pachev_ftp
|
/ftp_server/src/main_commands.rs
|
UTF-8
| 13,524
| 2.578125
| 3
|
[
"MIT"
] |
permissive
|
use rand::Rng;
use rand;
use std::fs::OpenOptions;
use std::io::BufReader;
use std::string::String;
use std::net::{TcpStream, TcpListener, Shutdown};
use std::path::Path;
use std::fs;
use std::fs::File;
use user::User;
use server::FtpMode;
use server;
/// # The FTP List command
/// This function implements the list command server side
///
/// # Arguements
///
/// - client
/// - user
/// - mode
/// - args
/// - data_port
/// - listener
pub fn list(client: &mut BufReader<TcpStream>,
user: &User,
mode: FtpMode,
args: &str,
data_port: &i32,
listener: &TcpListener) {
match mode {
FtpMode::Passive => {
info!("{} in passive mode requesting LIST command", user.name);
//getting a head start here in order to prvent slow connection
let (stream, _) = listener.accept().expect("Could not accept connection");
server::write_response(client,
&format!("{} Openning ASCII mode data for file list\r\n",
server::OPENNING_DATA_CONNECTION));
let mut data_stream = stream;
server::ftp_ls(&user, &mut data_stream, args);
server::write_response(client,
&format!("{} Transfer Complete\r\n",
server::CLOSING_DATA_CONNECTION));
data_stream.shutdown(Shutdown::Both).expect("Could not shutdownd data stram");
}
FtpMode::Active(addr) => {
info!("{} in passive mode requesting LIST command", user.name);
server::write_response(client,
&format!("{} Openning ASCII mode data for file list\r\n",
server::OPENNING_DATA_CONNECTION));
let mut stream = TcpStream::connect(addr).expect("Could not connect to addr");
server::ftp_ls(&user, &mut stream, args);
server::write_response(client,
&format!("{} Transfer Complete\r\n",
server::CLOSING_DATA_CONNECTION));
}
}
}
pub fn stor(mut client: &mut BufReader<TcpStream>,
user: &User,
mode: FtpMode,
args: &str,
listener: &TcpListener) {
match mode {
FtpMode::Passive => {
info!("{} in passive mode requesting STOR command", user.name);
let (stream, _) = listener.accept().expect("Could not accept connection");
let mut data_stream = stream;
stor_file(&mut client, user, &mut data_stream, args);
data_stream.shutdown(Shutdown::Both).expect("Could not shutdownd data stram");
}
FtpMode::Active(addr) => {
info!("{} in active mode requesting STOR command", user.name);
let mut data_stream = TcpStream::connect(addr).expect("Could not connect to addr");
stor_file(&mut client, user, &mut data_stream, args);
data_stream.shutdown(Shutdown::Both).expect("Could not shutdownd data stram");
}
}
}
pub fn retr(mut client: &mut BufReader<TcpStream>,
user: &User,
mode: FtpMode,
args: &str,
listener: &TcpListener) {
//getting a head start here in order to prvent slow connection
match mode {
FtpMode::Passive => {
info!("{} in passive mode requesting RETR command", user.name);
let (stream, _) = listener.accept().expect("Could not accept connection");
let mut data_stream = stream;
retr_file(&mut client, user, &mut data_stream, args);
data_stream.shutdown(Shutdown::Both).expect("Could not shutdownd data stram");
}
FtpMode::Active(addr) => {
info!("{} in active mode requesting RETR command", user.name);
let mut data_stream = TcpStream::connect(addr).expect("Could not connect to addr");
retr_file(&mut client, user, &mut data_stream, args);
data_stream.shutdown(Shutdown::Both).expect("Could not shutdownd data stram");
}
}
}
pub fn stou(mut client: &mut BufReader<TcpStream>,
user: &User,
mode: FtpMode,
args: &str,
listener: &TcpListener) {
//This is in case the file name is not unique
let mut rng = rand::thread_rng();
let full_path = format!("{}/{}", user.cur_dir, args);
let s = rng.gen_ascii_chars().take(8).collect::<String>();
let remote = Path::new(&full_path);
match mode {
FtpMode::Passive => {
info!("{} in passive mode requesting STOU command", user.name);
let (stream, _) = listener.accept().expect("Could not accept connection");
let mut data_stream = stream;
if remote.exists() {
stor_file(&mut client, user, &mut data_stream, &s);
} else {
stor_file(&mut client, user, &mut data_stream, args);
}
data_stream.shutdown(Shutdown::Both).expect("Could not shutdownd data stream");
}
FtpMode::Active(addr) => {
info!("{} in active mode requesting STOU command", user.name);
let mut data_stream = TcpStream::connect(addr).expect("Could not connect to addr");
if remote.exists() {
stor_file(&mut client, user, &mut data_stream, &s);
} else {
stor_file(&mut client, user, &mut data_stream, args);
}
data_stream.shutdown(Shutdown::Both).expect("Could not shutdownd data stream");
}
}
}
pub fn appe(client: &mut BufReader<TcpStream>,
user: &User,
mode: FtpMode,
args: &str,
listener: &TcpListener) {
match mode {
FtpMode::Passive => {
//Waits for clinet to connect to data port
let (stream, _) = listener.accept().expect("Could not accept connection");
let mut data_stream = stream;
let full_path = format!("{}/{}", user.cur_dir, args);
let remote = Path::new(&full_path);
if !remote.is_dir() {
let mut file = match OpenOptions::new().append(true).open(remote) {
Ok(file) => file,
Err(_) => {
let file = File::create(remote)
.expect("Could not create remote file for append");
file
}
};
server::write_to_file(&mut file, &mut data_stream);
//TODO: Add how long it took to transfer file
server::write_response(client,
&format!("{} Transfer Complete\r\n",
server::CLOSING_DATA_CONNECTION));
} else {
server::write_response(client,
&format!("{} No Such File or Dir\r\n", server::NO_ACCESS));
}
data_stream.shutdown(Shutdown::Both).expect("Could not shutdownd data stram");
}
FtpMode::Active(_) => {
println!("mode not yet implemented");
}
}
}
pub fn rnfr(mut client: &mut BufReader<TcpStream>, user: &User, args: &str) {
let full_path = format!("{}/{}", user.cur_dir, args);
let remote = Path::new(&full_path);
if remote.exists() {
server::write_response(client,
&format!("{} File or Directory Exists, Ready for Desitination\r\n",
server::ITEM_EXISTS));
//REFRACTOR: Consider adding a function that reads a message and parses cmd/args
let response = server::read_message(&mut client);
let line = response.trim();
let (cmd, new_name) = match line.find(' ') {
Some(pos) => (&line[0..pos], &line[pos + 1..]),
None => (line, "".as_ref()),
};
match cmd.to_lowercase().as_ref() {
"rnto" => {
let from_path = format!("{}/{}", user.cur_dir, args);
let to_path = format!("{}/{}", user.cur_dir, new_name);
let from = Path::new(&from_path);
let to = Path::new(&to_path);
println!("Curr {}\nTo: {}", from_path, to_path);
match fs::rename(from, to) {
Ok(_) => {
server::write_response(client,
&format!("{} Success Renaming\r\n",
server::CWD_CONFIRMED));
}
Err(_) => {
server::write_response(client,
&format!("{} Could Not Rename File\r\n",
server::BAD_SEQUENCE));
}
}
}
_ => {
server::write_response(client,
&format!("{} {} Bad Sequence of Commands \r\n",
server::BAD_SEQUENCE,
cmd));
}
}
} else {
server::write_response(client,
&format!("{} No Such File or Dir\r\n", server::NO_ACCESS));
}
}
pub fn dele(mut client: &mut BufReader<TcpStream>, user: &User, args: &str) {
let full_path = format!("{}/{}", user.cur_dir, args);
let remote = Path::new(&full_path);
info!("{} being deleted form serve", args);
if remote.exists() && !remote.is_dir() {
match fs::remove_file(remote) {
Ok(_) => {
server::write_response(client,
&format!("{} Success Deleting Filer\n",
server::OPERATION_SUCCESS));
}
Err(_) => {
server::write_response(client,
&format!("{} File could not be deleted\r\n",
server::NO_ACCESS));
}
}
} else {
server::write_response(client,
&format!("{} No Such File or Dir\r\n", server::NO_ACCESS));
}
}
pub fn rmd(mut client: &mut BufReader<TcpStream>, user: &User, args: &str) {
let full_path = format!("{}/{}", user.cur_dir, args);
let mut remote = Path::new(&full_path);
if remote.exists() && remote.is_dir() {
match fs::remove_dir(remote) {
Ok(_) => {
server::write_response(client,
&format!("{} Success Deleting Directory\r\n",
server::CWD_CONFIRMED));
}
Err(_) => {
server::write_response(client,
&format!("{} Directory is not empty\r\n",
server::NO_ACCESS));
}
}
} else {
server::write_response(client,
&format!("{} No Such File or Dir\r\n", server::NO_ACCESS));
}
}
fn stor_file(client: &mut BufReader<TcpStream>, user: &User, stream: &mut TcpStream, args: &str) {
server::write_response(client,
&format!("{} Opening binary mode to receive {}\r\n",
server::OPENNING_DATA_CONNECTION,
args));
let mut data_stream = stream;
let full_path = format!("{}/{}", user.cur_dir, args);
let remote = Path::new(&full_path);
if !remote.is_dir() {
let mut file = File::create(remote).expect("Could not create file to store");
server::write_to_file(&mut file, &mut data_stream);
//TODO: Add how long it took to transfer file
server::write_response(client,
&format!("{} Transfer Complete\r\n",
server::CLOSING_DATA_CONNECTION));
} else {
server::write_response(client,
&format!("{} No Such File or Dir\r\n", server::NO_ACCESS));
}
}
fn retr_file(client: &mut BufReader<TcpStream>, user: &User, stream: &mut TcpStream, args: &str) {
server::write_response(client,
&format!("{} Openning binary mode to transfer {}\r\n",
server::OPENNING_DATA_CONNECTION,
args));
let full_path = format!("{}/{}", user.cur_dir, args);
println!("{} requested file", full_path);
let mut data_stream = stream;
let local = Path::new(&full_path);
if !local.is_dir() && local.exists() {
let mut file = File::open(local).expect("Could not create file to store");
server::write_to_stream(&mut file, &mut data_stream);
server::write_response(client,
&format!("{} Transfer Complete\r\n",
server::CLOSING_DATA_CONNECTION));
} else {
server::write_response(client,
&format!("{} No Such File or Dir\r\n", server::NO_ACCESS));
}
}
| true
|
e98c930a124d60a0afdfdd7d87f26ce5e4df4f3e
|
Rust
|
toumorokoshi/disp
|
/src/function_loader/mod.rs
|
UTF-8
| 4,193
| 3.15625
| 3
|
[] |
no_license
|
use super::{parse_macro, Compiler, DispError, DispResult, MacroMap, Token};
use std::collections::HashMap;
use std::rc::Rc;
#[derive(Debug)]
pub struct UnparsedFunction {
pub args: Vec<String>,
pub body: Token,
}
impl UnparsedFunction {
pub fn new(args: Vec<String>, body: Token) -> UnparsedFunction {
return UnparsedFunction { args, body };
}
}
/// A FunctionMap of string to unparsed functions.
/// The UnparsedFunction is reference counted because it
/// is eventually spread across multiple specialized functions
/// definitions in the future.
pub type FunctionMap = HashMap<String, Rc<UnparsedFunction>>;
/// consume tokens, subdividing them into function and macro declarations.
pub fn parse_functions_and_macros(
_compiler: &mut Compiler,
parent_token: Token,
) -> DispResult<(FunctionMap, MacroMap)> {
let mut function_map = HashMap::new();
let mut macro_map = MacroMap::new();
// instructions that are not a part of any function
// are automatically added to the main function.
let mut main_function_body = vec![];
if let Token::Block(tokens) = parent_token {
for token in tokens {
match token {
// the only token we really need to parse out is the expression,
// since that's the only thing that can define a top-level function.
// everything else is part of the main function.
Token::Expression(e) => match e[0].clone() {
Token::Symbol(ref s) => {
if **s == "fn" {
let (name, function) = parse_function(e)?;
function_map.insert(name, function);
} else {
main_function_body.push(Token::Expression(e));
}
}
Token::BangSymbol(ref s) => {
if **s == "macro" {
let (name, macro_instance) = parse_macro(e)?;
macro_map.insert(name, macro_instance);
} else {
main_function_body.push(Token::Expression(e));
}
}
_ => main_function_body.push(Token::Expression(e)),
},
t => main_function_body.push(t),
}
}
}
function_map.insert(
String::from("main"),
Rc::new(UnparsedFunction::new(
vec![],
Token::Block(main_function_body),
)),
);
Ok((function_map, macro_map))
}
fn parse_function(tokens: Vec<Token>) -> DispResult<(String, Rc<UnparsedFunction>)> {
if tokens.len() != 4 {
return Err(DispError::new(&format!(
"A function declaration should have 4 tokens: fn <name> <args> <body>. found {} for {:?}",
tokens.len(),
tokens
)));
}
let name = {
if let Token::Symbol(ref s) = tokens[1] {
s.clone()
} else {
return Err(DispError::new(&format!(
"function name must be a symbol, found {}",
&tokens[1]
)));
}
};
if cfg!(feature = "debug") {
println!("parse function: {}", &name);
}
if *name == "main" {
return Err(DispError::new("unable to name function main"));
}
let args = {
if let Token::List(ref raw_list) = tokens[2] {
let mut args = vec![];
for arg in raw_list {
match arg {
Token::Symbol(s) => {
args.push((**s).clone());
}
_ => {
return Err(DispError::new("argument parameter should be a string"));
}
}
}
args
} else {
return Err(DispError::new(&format!(
"function args must be a list of symbols, found {}",
&tokens[2]
)));
}
};
return Ok((
*name,
Rc::new(UnparsedFunction::new(args, tokens[3].clone())),
));
}
| true
|
3127a80bf26d0c96f3d207b4df584ebedebbd25c
|
Rust
|
buratina/Network-Programming-with-Rust
|
/Chapter07/futures-ping-pong/src/main.rs
|
UTF-8
| 846
| 2.75
| 3
|
[
"MIT"
] |
permissive
|
extern crate futures;
extern crate rand;
extern crate tokio_core;
use std::thread;
use std::fmt::Debug;
use std::time::Duration;
use futures::Future;
use rand::{thread_rng, Rng};
use futures::sync::mpsc;
use futures::{Sink, Stream};
use futures::sync::mpsc::Receiver;
fn sender() -> &'static str {
let mut d = thread_rng();
thread::sleep(Duration::from_secs(d.gen_range::<u64>(1, 5)));
d.choose(&["ping", "pong"]).unwrap()
}
fn receiver<T: Debug>(recv: Receiver<T>) {
let f = recv.for_each(|item| {
println!("{:?}", item);
Ok(())
});
f.wait().ok();
}
fn main() {
let (tx, rx) = mpsc::channel(100);
let h1 = thread::spawn(|| {
tx.send(sender()).wait().ok();
});
let h2 = thread::spawn(|| {
receiver::<&str>(rx);
});
h1.join().unwrap();
h2.join().unwrap();
}
| true
|
31d9d7324d990e2ce8aff64560e5a7af6ff872ba
|
Rust
|
ZorinArsenij/nginx
|
/src/pool/pool.rs
|
UTF-8
| 713
| 2.671875
| 3
|
[] |
no_license
|
use super::worker::Worker;
use std::net;
use std::sync::{mpsc, Arc, Mutex};
pub struct Pool {
_workers: Vec<Worker>,
sender: mpsc::Sender<net::TcpStream>,
}
impl Pool {
pub fn new(root: String, cap: usize) -> Pool {
let (s, r) = mpsc::channel();
let receiver = Arc::new(Mutex::new(r));
let mut workers: Vec<Worker> = Vec::with_capacity(cap);
for id in 0..cap {
let r = root.clone();
workers.push(Worker::new(id, r, Arc::clone(&receiver)));
}
Pool {
_workers: workers,
sender: s,
}
}
pub fn process_request(&self, conn: net::TcpStream) {
self.sender.send(conn).unwrap();
}
}
| true
|
29af68e1abf94652267a60f5537cbd4eefc635c4
|
Rust
|
richo/rs-beef
|
/src/parser.rs
|
UTF-8
| 1,457
| 3.390625
| 3
|
[] |
no_license
|
use std::io::Read;
use std::fs::File;
pub type Program = Vec<OpCode>;
#[derive(Debug)]
pub enum OpCode {
Lshift,
Rshift,
Putc,
Getc,
Inc,
Dec,
Loop(Vec<OpCode>),
}
pub fn parse_file(filename: &str) -> Option<Program> {
let mut program: Program = vec!();
let mut loop_stack: Vec<Vec<OpCode>> = vec!();
let mut file = match File::open(filename) {
Ok(file) => file,
Err(err) => panic!(err),
};
macro_rules! push {
($op:expr) => (
match loop_stack.pop() { // Oh god why
Some(mut v) => {
v.push($op);
loop_stack.push(v);
},
None => program.push($op)
}
);
}
for c in file.chars() {
match c.unwrap() {
'<' => push!(OpCode::Lshift),
'>' => push!(OpCode::Rshift),
'.' => push!(OpCode::Putc),
',' => push!(OpCode::Getc),
'+' => push!(OpCode::Inc),
'-' => push!(OpCode::Dec),
// Deal with loops at "compile" time
'[' => {
loop_stack.push(vec!());
},
']' => {
match loop_stack.pop() {
Some(code) => push!(OpCode::Loop(code)),
None => panic!("Unbalanced braces"),
}
}
_ => {}
}
}
Some(program)
}
| true
|
fa367de9f388259ac550b0c5dce4cfd12088df6b
|
Rust
|
KodrAus/fluent_builder
|
/src/lib.rs
|
UTF-8
| 7,055
| 4.1875
| 4
|
[
"MIT"
] |
permissive
|
/*!
A simple builder for constructing or mutating values.
This crate provides a simple `FluentBuilder` structure.
It offers some standard behaviour for constructing values from a given source, or by mutating a default that's supplied later.
This crate is intended to be used within other builders rather than consumed by your users directly.
It's especially useful for managing the complexity of keeping builders ergonomic when they're nested within other builders.
This crate is currently designed around builders that take self by-value instead of by-reference.
# Usage
Create a `FluentBuilder` and construct a default value:
```
use fluent_builder::FluentBuilder;
let value = FluentBuilder::<String>::default()
.into_value(|| "A default value".to_owned());
assert_eq!("A default value", value);
```
Values can be supplied to the builder directly.
In this case that value will be used instead of constructing the default:
```
# use fluent_builder::FluentBuilder;
let value = FluentBuilder::<String>::default()
.value("A value".to_owned())
.into_value(|| "A default value".to_owned());
assert_eq!("A value", value);
```
Mutating methods will either be applied to a concrete value, or the constructed default:
```
# use fluent_builder::FluentBuilder;
let value = FluentBuilder::<String>::default()
.fluent_mut(|s| s.push_str(" fluent2"))
.into_value(|| "A default value".to_owned());
assert_eq!("A default value fluent2", value);
```
## Stacking fluent methods
Fluent methods are overriden by default each time `.fluent` is called, but can be configured to maintain state across calls using a generic parameter:
```
use fluent_builder::{FluentBuilder, Stack};
let value = FluentBuilder::<String, Stack>::default()
.fluent_mut(|s| s.push_str(" fluent1"))
.fluent_mut(|s| s.push_str(" fluent2"))
.into_value(|| "A default value".to_owned());
assert_eq!("A default value fluent1 fluent2", value);
```
Which option is best depends on the use-case.
For collection-like values it might make more sense to use stacking builders.
For other kinds of values it probably makes more sense to use overriding builders, so they're the default choice.
Using a generic parameter instead of some value to control whether or not fluent methods are stacked means you can enforce a particular style through Rust's type system.
## Stateful builders
Fluent builders can also be used to thread required state through construction:
```
use fluent_builder::StatefulFluentBuilder;
#[derive(Debug, PartialEq, Eq)]
struct Builder {
required: String,
optional: Option<String>,
}
let value = StatefulFluentBuilder::<String, Builder>::from_seed("A required value".to_owned())
.fluent_mut("A required value".to_owned(), |b| {
if let Some(ref mut optional) = b.optional.as_mut() {
optional.push_str(" fluent1");
}
})
.into_value(|s| Builder {
required: s,
optional: Some("A default value".to_owned())
});
assert_eq!("A required value", value.required);
assert_eq!("A default value fluent1", value.optional.unwrap());
```
Stateful builders can also stack fluent methods instead of overriding them.
The API requires each invocation of `fluent` deals with the required state:
```
# #[derive(Debug, PartialEq, Eq)]
# struct Builder {
# required: String,
# optional: Option<String>,
# }
use fluent_builder::{StatefulFluentBuilder, Stack};
let value = StatefulFluentBuilder::<String, Builder, Stack>::from_seed("A required value".to_owned())
.fluent_mut("A required value".to_owned(), |s, b| {
b.required = s;
if let Some(ref mut optional) = b.optional.as_mut() {
optional.push_str(" fluent1");
}
})
.fluent_mut("A required value".to_owned(), |s, b| {
b.required = s;
if let Some(ref mut optional) = b.optional.as_mut() {
optional.push_str(" fluent2");
}
})
.into_value(|s| Builder {
required: s,
optional: Some("A default value".to_owned())
});
assert_eq!("A required value", value.required);
assert_eq!("A default value fluent1 fluent2", value.optional.unwrap());
```
## Within other builders
The `FluentBuilder` and `StatefulFluentBuilder` types are designed to be used within other builders rather than directly.
They just provide some consistent underlying behaviour with respect to assigning and mutating inner builders:
```rust
use fluent_builder::{BoxedFluentBuilder, Stack};
#[derive(Default)]
struct RequestBuilder {
// Use a `FluentBuilder` to manage the inner `BodyBuilder`
body: BoxedFluentBuilder<BodyBuilder, Stack>,
}
#[derive(Default)]
struct BodyBuilder {
bytes: Vec<u8>,
}
impl<B> From<B> for BodyBuilder
where
B: AsRef<[u8]>
{
fn from(bytes: B) -> Self {
BodyBuilder {
bytes: bytes.as_ref().to_vec()
}
}
}
struct Request {
body: Body
}
struct Body(Vec<u8>);
impl RequestBuilder {
fn new() -> Self {
RequestBuilder {
body: BoxedFluentBuilder::default(),
}
}
// Accept any type that can be converted into a `BodyBuilder`
// This will override any previously stored state or default
fn body<B>(mut self, body: B) -> Self
where
B: Into<BodyBuilder>
{
self.body = self.body.value(body.into());
self
}
// Mutate some `BodyBuilder` without having to name its type
// If there's no previously supplied concrete value then some
// default will be given on `build`
fn body_fluent<F>(mut self, body: F) -> Self
where
F: Fn(BodyBuilder) -> BodyBuilder + 'static
{
self.body = self.body.fluent(body).boxed();
self
}
fn build(self) -> Request {
// Get a `Body` by converting the `FluentBuilder` into a `BodyBuilder`
let body = self.body.into_value(|| BodyBuilder::default()).build();
Request {
body: body
}
}
}
impl BodyBuilder {
fn append(mut self, bytes: &[u8]) -> Self {
self.bytes.extend(bytes);
self
}
fn build(self) -> Body {
Body(self.bytes)
}
}
// Use a builder to construct a request using fluent methods
let request1 = RequestBuilder::new()
.body_fluent(|b| b.append(b"some"))
.body_fluent(|b| b.append(b" bytes"))
.build();
// Use a builder to construct a request using a given value
let request2 = RequestBuilder::new()
.body(b"some bytes")
.build();
assert_eq!(request1.body.0, request2.body.0);
```
This seems like a lot of boilerplate, but comes in handy when you have a lot of potentially nested builders and need to keep them consistent.
There's nothing really special about the above builders besides the use of `FluentBuilder`.
*/
mod imp;
pub use self::imp::{
Boxed, BoxedFluentBuilder, BoxedStatefulFluentBuilder, DefaultStack, DefaultStorage,
FluentBuilder, Inline, Override, Shared, SharedFluentBuilder, SharedStatefulFluentBuilder,
Stack, StatefulFluentBuilder, TryIntoValue,
};
| true
|
1c50680d0969cfa8a5cd1f3b5d4efff70ccb48b3
|
Rust
|
carrotflakes/silver
|
/src/rng.rs
|
UTF-8
| 789
| 2.796875
| 3
|
[] |
no_license
|
use std::cell::UnsafeCell;
use rand::SeedableRng;
use rand_pcg::Lcg128Xsl64;
pub type MainRng = Lcg128Xsl64;
thread_local!(
pub static THREAD_RNG_KEY: UnsafeCell<MainRng> = {
let rng = SeedableRng::seed_from_u64(0);
UnsafeCell::new(rng)
}
);
#[inline]
pub fn with<F: FnOnce(&mut MainRng) -> R, R>(f: F) -> R {
THREAD_RNG_KEY.with(|rng| f(unsafe { &mut *rng.get() }))
}
pub fn reseed(seed: u64) {
THREAD_RNG_KEY.with(|rng| *unsafe { &mut *rng.get() } = SeedableRng::seed_from_u64(seed));
}
#[test]
fn test() {
use rand::Rng;
reseed(0);
let a = with(|rng| rng.gen::<usize>());
let b = with(|rng| rng.gen::<usize>());
reseed(0);
assert_eq!(with(|rng| rng.gen::<usize>()), a);
assert_eq!(with(|rng| rng.gen::<usize>()), b);
}
| true
|
365e2d9bed300ea99b2d32a38fabd26caa0e6470
|
Rust
|
imp/httptin
|
/src/get/origin.rs
|
UTF-8
| 962
| 2.71875
| 3
|
[
"Apache-2.0",
"MIT"
] |
permissive
|
use std::net::IpAddr;
use hyper::header::ContentType;
use hyper::server::{Request, Response};
use serde_json::to_string_pretty;
use makeresponse::MakeResponse;
#[derive(Serialize)]
pub struct Origin {
ip: IpAddr,
port: u16,
ipv4: bool,
ipv6: bool,
}
impl Origin {
pub fn from_request(request: &Request) -> Self {
Origin {
ip: request.remote_addr.ip(),
port: request.remote_addr.port(),
ipv4: request.remote_addr.is_ipv4(),
ipv6: request.remote_addr.is_ipv6(),
}
}
}
impl MakeResponse for Origin {
fn content_type(&self) -> ContentType {
ContentType::json()
}
fn make_response(&self, mut response: Response) {
*response.status_mut() = self.status();
response.headers_mut().set(self.content_type());
let body = to_string_pretty(self).unwrap_or_else(|_| String::new());
response.send(body.as_bytes()).unwrap();
}
}
| true
|
9da16a6716c09ce88cc2750a548572a732d50ad9
|
Rust
|
shaipe/rust-tools
|
/crawler/examples/req.rs
|
UTF-8
| 1,773
| 3.140625
| 3
|
[] |
no_license
|
extern crate reqwest;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate serde_json;
use std::env;
use reqwest::Client;
use reqwest::Error;
use std::time::Duration;
use reqwest::ClientBuilder;
fn main() -> Result<(), Error> {
let _ = run1();
let _ = run();
Ok(())
}
fn run1() -> Result<(), Error> {
let user = "shaipe";
let request_url = format!("https://api.github.com/users/{}", user);
println!("{}", request_url);
let timeout = Duration::new(5, 0);
let client = ClientBuilder::new().timeout(timeout).build()?;
let response = client.head(&request_url).send()?;
if response.status().is_success() {
println!("{} is a user!", user);
} else {
println!("{} is not a user!", user);
}
Ok(())
}
#[derive(Deserialize, Debug)]
struct Gist {
id: String,
html_url: String,
}
fn run() -> Result<(), Error> {
let gh_user = "ss";
let gh_pass = "ps";
let gist_body = json!({
"description": "the description for this gist",
"public": true,
"files": {
"main.rs": {
"content": r#"fn main() { println!("hello world!");}"#
}
}});
let request_url = "https://api.github.com/gists";
let mut response = Client::new()
.post(request_url)
.basic_auth(gh_user.clone(), Some(gh_pass.clone()))
.json(&gist_body)
.send()?;
let gist: Gist = response.json()?;
println!("Created {:?}", gist);
let request_url = format!("{}/{}",request_url, gist.id);
let response = Client::new()
.delete(&request_url)
.basic_auth(gh_user, Some(gh_pass))
.send()?;
println!("Gist {} deleted! Status code: {}",gist.id, response.status());
Ok(())
}
| true
|
68333cb72f77f16be009b46cc5578bdd3323724a
|
Rust
|
wcpannell/kea-hal
|
/src/adc.rs
|
UTF-8
| 26,336
| 3.203125
| 3
|
[
"MIT"
] |
permissive
|
//! The ADC Interface
//!
//! The ADC is disabled at startup and must be enabled (by calling
//! [Adc<Disabled>::enable]) before any of its registers can be accessed
//! (read or write). Attempts to access these registers will trigger a hardware
//! generated HardFault, which by default resets the microcontroller.
//!
//! The ADC can be polled for conversion completion with [Adc::is_done].
//! Completion will trigger an ADC Interrupt if enabled. See
//! [Adc::into_interrupt]
//!
//! ## Input Modes
//!
//! The Adc peripheral can operate in either single input or FIFO modes. Single
//! input mode is the mode most commonly thought of when using an ADC. A
//! multiplexer (via Adc::set_channel) is used to connect a single channel to
//! the ADC, and when the conversion is complete the hardware makes the results
//! available in the results register. The software must call
//! [Adc::set_channel] again to either select a new channel or to restart the
//! conversion on the same channel.
//!
//! The FIFO mode sets up a hardware buffer of selectable depth (2-8 channels).
//! Once the buffer is filled the Adc peripheral shoves the buffer contents
//! into the multiplexer channel by channel. Likewise, as each conversion is
//! completed the results are buffered into the result register in the same
//! order as the channel select buffer.
//!
//! Note: FIFO mode is not yet implemented in this HAL
//!
//! ## Conversion Modes
//!
//! The Adc peripheral offers 2 conversion modes, OneShot and Continuous. In
//! OneShot mode, the conversion is started when the channel is selected (or
//! when the channel select buffer is filled in FIFO mode). After completion no
//! new conversion is started until the channel is set again, even if the same
//! channel is used.
//!
//! In Continuous mode a new conversion is started immediately
//! after the previous one is completed. Changing the channel interrupts the
//! conversion and immediately begins conversion on the new channel (unless the
//! new channel is [DummyDisable], then the conversion is allowed to complete,
//! but no new conversion is started). In FIFO mode the input FIFO is reloaded
//! after completion, in other words the same N values are converted on a loop.
//!
//! Note: Continuous mode is not yet implemented in this HAL
//!
//! ## Comparison Mode
//!
//! Note: Comparison mode is not yet implemented in this HAL
//!
//! Comparison mode is a hardware feature of the Adc Peripheral. If set, the
//! conversion result is compared to the comparison value. If the result
//! is greater than or less than (depending on configuration) the comparison
//! value the result is moved into the result register. Otherwise, the result
//! is discarded \[Note: Unsure if the conversion is restarted in OneShot
//! mode\].
//!
//! A common use case for comparison mode is to enter a low power state with
//! the Adc configured to use the asynchronous clock source and to generate an
//! interrupt on completion. When the input channel crosses the comparison
//! threshold the interrupt is triggered, waking the MCU.
//!
//! ## Clocking
//!
//! The ADC requires a clock signal (ADCK), which is generated from the bus
//! clock, the bus clock divided by 2, the output of the OSC peripheral
//! (OSC_OUT), or an internal asynchronous clock, which, when selected,
//! operates in wait and stop modes. With any of these clock sources a
//! multi-value divider is provided to further divide the incoming clock by 1
//! (i.e. 1:1), 2, 4, or 8.
//!
//! The clock frequency must fall within 400kHz to 8MHz (4MHz in low power
//! mode), This is the same for all KEA MCUs. Ideally, the HAL will only
//! present valid options, but that is not yet implemented (pending clocks
//! improvements to output frequencies). For now you are trusted to input the
//! correct frequency.
//!
//! *Note:* When using the FIFO mode with FIFO scan mode disabled, the bus
//! clock must be faster than half the ADC clock (ADCK). Bus clock >= ADCK / 2.
//!
//! ## Pin Control
//!
//! This functionality is implemented in the GPIO module. See [Analog]
//! for details.
//!
//! ## Conversion Width
//!
//! The ADC can be run in 8, 10, or 12 bit modes. These modes are enumerated in
//! [AdcResolution].
//!
//! ## Hardware Trigger
//!
//! The ADC conversions can be started by a hardware trigger. This is not
//! implemented in all KEA chips, so implementation here will be Delayed. Use
//! the PAC. Enable is ADC_SC2\[ADTRG\] = 1, and trigger is the ADHWT source.
//!
//! ## Usage
//!
//! ### AdcConfig struct
//!
//! [AdcConfig] offers public fields to allow for creation in-place. The
//! [AdcConfig::calculate_divisor] method allows the user to specify the
//! desired Adc Clock frequency (given the clock source frequency). The clock
//! divider which gets the closest to that frequency is chosen.
//!
//! The AdcConfig structure also implements the [Default] trait.
//!
//! ```rust
//! let config: AdcConfig = Default::default();
//!
//! config.calculate_divisor(20_u32.MHz(), 2_u32.MHz());
//! assert!(matches!(config.clock_divisor, ClockDivisor::_8));
//! ```
use crate::hal::adc::{Channel, OneShot};
use crate::{pac::ADC, HALExt};
use core::{convert::Infallible, marker::PhantomData};
use embedded_time::rate::*;
/// Error Enumeration for this module
#[derive(Debug)]
pub enum Error {
/// The Channel has already been moved
Moved,
}
/// Analog type state for a GPIO pin.
///
/// This mode "gives" the pin to the ADC hardware peripheral.
/// The ADC Peripheral can take the GPIO pins in any state. The Peripheral will
/// reconfigure the pin to turn off any output drivers, disable input buffers
/// (reading the pin after configuring as analog will return a zero), and
/// disable the pullup. Electrically, an Analog pin that is not currently under
/// conversion is effectively HighImpedence.
///
/// Once a pin is released from the ADC, it will return to its previous state.
/// The previous state includes output enabled, input enabled, pullup enabled,
/// and level (for outputs). Note to accomplish this the pin implements the
/// outof_analog method, which is semantically different from the other type
/// states.
///
/// For example, [crate::gpio::gpioa::PTA0] is configured to be a Output that is set high is
/// converted into the analog mode with the [crate::gpio::gpioa::PTA0::into_analog] method.
/// Once measurements from that pin are completed it will be returned to an
/// Output that is set high by calling the [Analog::outof_analog] method.
///
/// ```rust
/// let pta0 = gpioa.pta0.into_push_pull_output();
/// pta0.set_high();
/// let mut pta0 = pta0.into_analog(); // pta0 is hi-Z
/// let value = adc.read(&mut pta0).unwrap_or(0);
/// let pta0 = pta0.outof_analog(); // pta0 is push-pull output, set high.
/// ```
///
/// Note: This is a hardware feature that requires effectively no clock cycles
/// to complete. "Manually" reconfiguring the pins to HighImpedence before
/// calling into_analog() is discouraged, but it would not hurt anything.
pub struct Analog<Pin> {
pin: Pin,
}
/// Interface for ADC Peripheral.
///
/// Returned by calling [HALExt::split] on the pac [ADC] structure. Holds state
/// of peripheral.
pub struct Adc<State> {
peripheral: ADC,
_state: PhantomData<State>,
/// Contains the On-Chip ADC Channels, like the MCU's temperature sensor.
pub onchip_channels: OnChipChannels,
}
impl HALExt for ADC {
type T = Adc<Disabled>;
fn split(self) -> Adc<Disabled> {
Adc {
peripheral: self,
_state: PhantomData,
onchip_channels: OnChipChannels {
vss: Some(Analog {
pin: Vss::<Input> { _mode: PhantomData },
}),
temp_sense: Some(Analog {
pin: TempSense::<Input> { _mode: PhantomData },
}),
bandgap: Some(Analog {
pin: Bandgap::<Input> { _mode: PhantomData },
}),
vref_h: Some(Analog {
pin: VrefH::<Input> { _mode: PhantomData },
}),
vref_l: Some(Analog {
pin: VrefL::<Input> { _mode: PhantomData },
}),
},
}
}
}
/// Configuration struct for Adc peripheral.
pub struct AdcConfig {
/// Determines the clock source for the ADC peripheral
///
/// Default is [AdcClocks::Bus]
pub clock_source: AdcClocks,
/// Divides the clock source to get the ADC clock into it's usable range of
/// 400kHz - 8MHz (4MHz in low power mode).
///
/// Default is [ClockDivisor::_1] (no divison)
pub clock_divisor: ClockDivisor,
/// Set the resolution of ADC conversion
///
/// Default is [AdcResolution::_8bit]
pub resolution: AdcResolution,
/// Set ADC sample time.
///
/// Default is [AdcSampleTime::Short]
pub sample_time: AdcSampleTime,
/// Set low power mode
///
/// Default is false.
pub low_power: bool,
}
impl AdcConfig {
/// Calculate the ADC clock divisor
///
/// Uses the current clock source and clock frequency to determine
/// the best divisor to use in order to have minimal error between
/// the ADC clock rate and the desired ADC clock rate.
///
/// Note: This relies on trustworthy values for source_freq and valid
/// values for req_adc_freq. In the future this should know or
/// determine what the current clock frequency is instead of relying
/// on the user to provide it.
pub fn calculate_divisor(&mut self, source_freq: Hertz, req_adc_freq: Hertz) {
let denom: u8 = (source_freq.integer() / req_adc_freq.integer()) as u8;
let mut output: u8 = 1;
let mut err: i8 = (denom - output) as i8;
let mut err_old: i8 = err;
let max_divisor = match self.clock_source {
AdcClocks::Bus => 16,
_ => 8,
};
while output < max_divisor {
err = (denom - (output << 1)) as i8;
if err.is_negative() {
err = err.abs();
}
if err <= err_old {
output <<= 1;
err_old = err;
} else {
break;
}
}
// I am of the mind that this assert is okay, at least until the input
// clock can be known at compile time.
let ad_clock = source_freq.integer() / output as u32;
assert!(400_000 <= ad_clock);
assert!(
ad_clock
<= match self.low_power {
false => 8_000_000,
true => 4_000_000,
}
);
self.clock_divisor = match output {
1 => ClockDivisor::_1,
2 => ClockDivisor::_2,
4 => ClockDivisor::_4,
8 => ClockDivisor::_8,
_ => ClockDivisor::_16,
}
}
/// Set the divisor directly. panics if divisor isn't supported by the
/// clock source.
///
/// TODO: Refactor to remove assert. Add Clock Source as a type state
pub fn set_divisor(&mut self, divisor: ClockDivisor) {
// divisor can't be 16 unless using the Bus clock
assert!(
!(!matches!(self.clock_source, AdcClocks::Bus) && matches!(divisor, ClockDivisor::_16))
);
self.clock_divisor = divisor;
}
/// Sets the clock source, panics if divisor isn't supported
///
/// TODO: Refactor to remove assert. Add Clock Source as a type state
pub fn set_clock_source(&mut self, clock: AdcClocks) {
// Panic if setting the clock to anything other than Bus if the divisor
// is set to 16
assert!(
!matches!(clock, AdcClocks::Bus) && matches!(self.clock_divisor, ClockDivisor::_16)
);
self.clock_source = clock;
}
}
impl Default for AdcConfig {
fn default() -> AdcConfig {
AdcConfig {
clock_source: AdcClocks::Bus,
clock_divisor: ClockDivisor::_1,
resolution: AdcResolution::_12bit,
sample_time: AdcSampleTime::Short,
low_power: false,
}
}
}
/// Clock types available to the Adc peripheral
///
/// Dividers will be chosen appropriately to suit requested clock rate.
pub enum AdcClocks {
/// Use the incoming Bus Clock
Bus,
/// jkl
External,
/// Available in Wait AND Stop Mode
Async,
}
/// This enum represents the availabe ADC resolutions
///
/// Regardless of resolution chosen, results are always right justified
#[repr(u8)]
pub enum AdcResolution {
/// 8 bit AD conversion mode
_8bit = 0,
/// 10 bit AD conversion mode
_10bit = 1,
/// 12 bit AD conversion mode
_12bit = 2,
}
/// Adc sample time
pub enum AdcSampleTime {
/// Sample for 3.5 ADC clock (ADCK) cycles.
Short = 0,
/// Sample for 23.5 ADC clock (ADCK) cycles.
///
/// Required for high impedence (>2k @ADCK > 4MHz, >5k @ ADCK < 4MHz)
/// inputs.
Long = 1,
}
/// Adc Clock Divisors
///
/// Note 1/16 divisor is only usable for the Bus clock
pub enum ClockDivisor {
/// Source / 1, No divison
_1 = 0,
/// Source / 2
_2 = 1,
/// Source / 4
_4 = 2,
/// Source / 8
_8 = 3,
/// Source / 16
_16 = 4,
}
/// Enabled state
pub struct Enabled;
/// Disabled state
pub struct Disabled;
impl Adc<Enabled> {
/// Poll to determine if ADC conversion is complete.
///
/// Note: This flag is cleared when the sampling mode is changed,
/// interrupts are enabled, [Adc::set_channel] is called, and when [Adc::result] is
/// called (including [Adc::try_result])
pub fn is_done(&self) -> bool {
self.peripheral.sc1.read().coco().bit()
}
/// Poll to determine if ADC conversion is underway
pub fn is_converting(&self) -> bool {
self.peripheral.sc2.read().adact().bit()
}
/// Grab the last ADC conversion result.
pub fn result(&self) -> u16 {
self.peripheral.r.read().adr().bits()
}
/// Poll for conversion completion, if done return the result.
pub fn try_result(&self) -> Option<u16> {
if self.is_done() {
Some(self.result())
} else {
None
}
}
/// Set ADC target channel.
///
/// In Single conversion mode (OneShot), setting the channel begins the conversion. In FIFO mode
/// the channel is added to the FIFO buffer.
///
/// Note: If the channel is changed while a conversion is in progress the
/// current conversion will be cancelled. If in FIFO mode, conversion will
/// resume once the FIFO channels are refilled.
pub fn set_channel<T: Channel<Adc<Enabled>, ID = u8>>(&self, _pin: &T) {
self.peripheral
.sc1
.modify(|_, w| unsafe { w.adch().bits(T::channel()) });
}
/// Set the ADC's configuration
pub fn configure(self, config: AdcConfig) -> Adc<Enabled> {
self.peripheral.sc3.modify(|_, w| {
use pac::adc::sc3::{ADICLK_A, ADIV_A, ADLSMP_A, MODE_A};
w.adiclk()
.variant(match config.clock_source {
AdcClocks::Bus =>
// If divisor is 16, use the Bus / 2 clock source, else use
// the 1:1 Bus clock source
{
match config.clock_divisor {
ClockDivisor::_16 => ADICLK_A::_01,
_ => ADICLK_A::_00,
}
}
AdcClocks::External => ADICLK_A::_10,
AdcClocks::Async => ADICLK_A::_11,
})
.mode()
.variant(match config.resolution {
AdcResolution::_8bit => MODE_A::_00,
AdcResolution::_10bit => MODE_A::_01,
AdcResolution::_12bit => MODE_A::_10,
})
.adlsmp()
.variant(match config.sample_time {
AdcSampleTime::Short => ADLSMP_A::_0,
AdcSampleTime::Long => ADLSMP_A::_1,
})
.adiv()
.variant(match config.clock_divisor {
ClockDivisor::_1 => ADIV_A::_00,
ClockDivisor::_2 => ADIV_A::_01,
ClockDivisor::_4 => ADIV_A::_10,
_ => ADIV_A::_11,
})
.adlpc()
.bit(config.low_power)
});
// It looks like SCGC has to be set before touching the peripheral
// at all, else hardfault. Go back later to confirm that if using external clock
// scgc can be cleared.
// w.adc().variant(match config.clock_source {
// AdcClocks::Bus => ADC_A::_1,
// _ => ADC_A::_0,
// })
Adc {
peripheral: self.peripheral,
_state: PhantomData,
onchip_channels: self.onchip_channels,
}
}
}
impl Adc<Disabled> {
/// Connects the bus clock to the adc via the SIM peripheral, allowing
/// read and write access to ADC registers.
///
/// Any attempt to access ADC registers while disabled results in a
/// HardFault, generated by hardware.
///
/// This also enables the bandgap voltage reference.
pub fn enable(self) -> Adc<Enabled> {
cortex_m::interrupt::free(|_| {
unsafe { &(*pac::SIM::ptr()) }.scgc.modify(|_, w| {
use pac::sim::scgc::ADC_A;
w.adc().variant(ADC_A::_1)
});
// Don't start a conversion (set channel to DummyDisable)
self.peripheral.sc1.modify(|_, w| w.adch()._11111());
// Bandgap. Grab directly, Currently the bandgap isn't implemented
// in [system::PMC]. We will eventually have to pass in the pmc
// peripheral handle as a variable.
unsafe { &(*pac::PMC::ptr()) }
.spmsc1
.modify(|_, w| w.bgbe()._1());
});
Adc {
peripheral: self.peripheral,
_state: PhantomData,
onchip_channels: self.onchip_channels,
}
}
/// Set the ADC's configuration
///
/// This is a sugar method for calling [Adc<Disabled>::enable] followed by
/// [Adc<Enabled>::configure]
pub fn configure(self, config: AdcConfig) -> Adc<Enabled> {
self.enable().configure(config)
}
}
impl<Mode> Adc<Mode> {
/// Not Implemented
pub fn into_interrupt(self) -> Adc<Mode> {
unimplemented!("Interrupt is not yet implemented");
// Adc::<Mode> {
// peripheral: self.peripheral,
// _state: PhantomData,
// onchip_channels: self.onchip_channels,
// }
}
/// Not Implemented
pub fn into_fifo(self, _depth: u8) -> Adc<Mode> {
// self.peripheral
// .sc4
// .modify(|_r, w| w.afdep().bits(depth & 0x7));
// Adc::<Mode> {
// peripheral: self.peripheral,
// _state: PhantomData,
// onchip_channels: self.onchip_channels,
// }
unimplemented!("FIFO is not yet implemented");
}
/// Not Implemented
pub fn into_continuous(self) -> Adc<Mode> {
unimplemented!("Continuous Conversion mode not yet implemented");
}
}
impl OnChipChannels {
/// Request an instance of an on-chip [Vss] channel.
pub fn vss(&mut self) -> Result<Analog<Vss<Input>>, Error> {
self.vss.take().ok_or(Error::Moved)
}
/// Return the instance of [Vss]
pub fn return_vss(&mut self, inst: Analog<Vss<Input>>) {
self.vss.replace(inst);
}
/// Try to grab an instance of the onchip [TempSense] channel.
pub fn tempsense(&mut self) -> Result<Analog<TempSense<Input>>, Error> {
self.temp_sense.take().ok_or(Error::Moved)
}
/// Return the instance of [TempSense]
pub fn return_tempsense(&mut self, inst: Analog<TempSense<Input>>) {
self.temp_sense.replace(inst);
}
/// Try to grab an instance of the onchip [Bandgap] channel.
///
/// The bandgap reference is a fixed 1.16V (nom, Factory trimmed to +/-
/// 0.02V at Vdd=5.0 at 125C) signal that is available to the ADC Module.
/// It can be used as a voltage reference for the ACMP and as an [Analog]
/// channel that can be used to (roughly) check the VDD voltage
pub fn bandgap(&mut self) -> Result<Analog<Bandgap<Input>>, Error> {
self.bandgap.take().ok_or(Error::Moved)
}
/// Return the instance of [Bandgap]
pub fn return_bandgap(&mut self, inst: Analog<Bandgap<Input>>) {
self.bandgap.replace(inst);
}
/// Try to grab an instance of the onchip Voltage Reference High ([VrefH]) channel.
pub fn vref_h(&mut self) -> Result<Analog<VrefH<Input>>, Error> {
self.vref_h.take().ok_or(Error::Moved)
}
/// Return the instance of [VrefH]
pub fn return_vref_h(&mut self, inst: Analog<VrefH<Input>>) {
self.vref_h.replace(inst);
}
/// Try to grab an instance of the onchip Voltage Reference Low ([VrefL]) channel.
pub fn vref_l(&mut self) -> Result<Analog<VrefL<Input>>, Error> {
self.vref_l.take().ok_or(Error::Moved)
}
/// Return the instance of [VrefL]
pub fn return_vref_l(&mut self, inst: Analog<VrefL<Input>>) {
self.vref_l.replace(inst);
}
/// Grab a [DummyDisable] instance. Multiple Instances possible.
pub fn dummy_disable(&self) -> Analog<DummyDisable<Input>> {
Analog {
pin: DummyDisable::<Input> { _mode: PhantomData },
}
}
}
/// Holds On-Chip ADC Channel inputs and provides an interface to grab and return them.
// These have to have the Input dummy type to allow them to have the Channel
// trait.
pub struct OnChipChannels {
vss: Option<Analog<Vss<Input>>>,
temp_sense: Option<Analog<TempSense<Input>>>,
bandgap: Option<Analog<Bandgap<Input>>>,
vref_h: Option<Analog<VrefH<Input>>>,
vref_l: Option<Analog<VrefL<Input>>>,
}
/// Dummy type state for on-chip ADC input channels
pub struct Input;
/// Adc Input Channel, measures ground (should be 0?)
pub struct Vss<Input> {
_mode: PhantomData<Input>,
}
/// Adc Input Channel, measures internal temperature sensor
pub struct TempSense<Input> {
_mode: PhantomData<Input>,
}
/// Adc Input Channel, Bandgap internal voltage reference
pub struct Bandgap<Input> {
_mode: PhantomData<Input>,
}
/// Adc Input Channel, Voltage Reference, High
pub struct VrefH<Input> {
_mode: PhantomData<Input>,
}
/// Adc Input Channel, Voltage Reference, Low
pub struct VrefL<Input> {
_mode: PhantomData<Input>,
}
/// Dummy Channel that temporarily disables the Adc Module.
pub struct DummyDisable<Input> {
_mode: PhantomData<Input>,
}
macro_rules! adc_input_channels {
( $($Chan:expr => $Pin:ident),+ $(,)*) => {
$(
impl<OldMode> Channel<Adc<Enabled>> for Analog<$Pin<OldMode>> {
type ID = u8;
fn channel() -> u8 { $Chan }
}
)+
};
}
use crate::gpio::{gpioa::*, gpiob::*};
adc_input_channels! (
0_u8 => PTA0,
1_u8 => PTA1,
2_u8 => PTA6,
3_u8 => PTA7,
4_u8 => PTB0,
5_u8 => PTB1,
6_u8 => PTB2,
7_u8 => PTB3,
8_u8 => PTC0,
9_u8 => PTC1,
10_u8 => PTC2,
11_u8 => PTC3,
12_u8 => PTF4,
13_u8 => PTF5,
14_u8 => PTF6,
15_u8 => PTF7,
16_u8 => Vss,
22_u8 => TempSense,
23_u8 => Bandgap,
24_u8 => VrefH,
25_u8 => VrefL,
0x1F_u8 => DummyDisable,
);
macro_rules! impl_analog_pin {
( $($Chan:expr => $Pin:ident),+ $(,)*) => {
$(
impl<OldMode> $Pin<OldMode> {
/// Convert Pin into the [Analog] state for use by the ADC.
///
/// This implementation provides the GPIO interface a method to
/// give an eligible pin to the ADC peripheral for conversion
/// into an Analog pin. This method is only implemented in
/// eligible pins. The ADC peripheral disables the GPIO and
/// PORT control over the pin and connects it to the ADC mux
/// (controlled by [Adc::set_channel].
///
/// Note: The [Analog::outof_analog] method must be used to
/// return the pin to a normal Input/Output typestate. The pin
/// will be returned in the same typestate as it was received.
pub fn into_analog(self) -> Analog<$Pin<OldMode>> {
unsafe {
(*ADC::ptr())
.apctl1
.modify(|r, w| w.adpc().bits(r.adpc().bits() | (1 << $Chan)));
}
Analog { pin: self }
}
}
impl<OldMode> Analog<$Pin<OldMode>> {
/// Return Analog state Pin to normal GPIO-state interface.
///
/// The Pin will be in the same state that it was when it
/// entered the Analog type state.
pub fn outof_analog(self) -> $Pin<OldMode> {
let adc = unsafe { &(*ADC::ptr()) };
adc.apctl1
.modify(|r, w| unsafe { w.adpc().bits(r.adpc().bits() & !(1 << $Chan)) });
self.pin
}
}
)+
};
}
impl_analog_pin!(
0_u8 => PTA0,
1_u8 => PTA1,
2_u8 => PTA6,
3_u8 => PTA7,
4_u8 => PTB0,
5_u8 => PTB1,
6_u8 => PTB2,
7_u8 => PTB3,
8_u8 => PTC0,
9_u8 => PTC1,
10_u8 => PTC2,
11_u8 => PTC3,
12_u8 => PTF4,
13_u8 => PTF5,
14_u8 => PTF6,
15_u8 => PTF7,
);
impl<Pin> OneShot<Adc<Enabled>, u16, Pin> for Adc<Enabled>
where
Pin: Channel<Adc<Enabled>, ID = u8>,
{
type Error = Infallible;
fn read(&mut self, pin: &mut Pin) -> nb::Result<u16, Self::Error> {
self.set_channel(pin);
while !self.is_done() {}
let ret_val = Ok(self.result());
let disable = self.onchip_channels.dummy_disable();
self.set_channel(&disable);
ret_val
}
}
| true
|
11825a9621f704a2aed2504b4ac86b89a58ccc8a
|
Rust
|
sahil-blulabs/learning_rust
|
/Lesson1/45_option_enum.rs
|
UTF-8
| 305
| 3.578125
| 4
|
[] |
no_license
|
fn main() {
let name = String::from("Domenic");
println!(
"Character at index 8: {}",
match name.chars().nth(6) {
Some(c) => c.to_string(),
None => "No character at index 8!".to_string(),
}
);
// FYI: name.chars().nth(8) return either `Some` or `None` case.
}
| true
|
16dc1a6a5b6223003724dfa30d8fb0edb5ff708c
|
Rust
|
fmdkdd/asobiba
|
/rust/nil-checker/src/bin/check.rs
|
UTF-8
| 1,060
| 2.953125
| 3
|
[] |
no_license
|
extern crate nil_checker;
use std::io::{self, Read};
use nil_checker::parser::{Node, NodeKind, Parser, ParseTree};
#[derive(Debug)]
struct Constraint {
desc: String,
}
struct Checker<'a> {
parse_tree: &'a ParseTree,
}
impl<'a> Checker<'a> {
fn new(p: &'a ParseTree) -> Self {
Checker {
parse_tree: p,
}
}
fn emit(&self) -> Vec<Constraint> {
self.parse_tree.roots.iter().flat_map(Self::emit_node).collect()
}
// Emit type constraints
fn emit_node(node: &Node) -> Vec<Constraint> {
use NodeKind::*;
match node.kind {
Sexp(ref nodes) =>
vec![Constraint {
desc: format!("{:?} is a function",
nodes[0].kind)
}],
_ => Vec::new(),
}
}
}
fn main() {
let stdin = io::stdin();
let mut input = String::new();
stdin.lock().read_to_string(&mut input).unwrap();
let mut p = Parser::new(&input);
let ast = p.parse();
let chck = Checker::new(&ast);
let cstr = chck.emit();
println!("{:?}", cstr);
println!("{} constraints", cstr.len());
}
| true
|
a225e996318ca659646b491521c368ceb8fe1da4
|
Rust
|
yasu0001/rbre
|
/core/src/vulkano_surface_context.rs
|
UTF-8
| 2,905
| 2.609375
| 3
|
[] |
no_license
|
use vulkano::instance::{Instance, PhysicalDevice};
use vulkano::device::{Queue, Device};
use vulkano::image::SwapchainImage;
use vulkano::swapchain::{Swapchain, Surface, SurfaceTransform, PresentMode, SwapchainAcquireFuture};
use vulkano::swapchain;
use vulkano::format::Format;
use winit::Window;
use std::sync::Arc;
pub struct VulkanoSurfaceContext {
queue: Arc<Queue>,
swapchain: Arc<Swapchain<Window>>,
images: Vec<Arc<SwapchainImage<Window>>>,
// rendering images
}
impl VulkanoSurfaceContext {
pub fn initialize(
instance: &Arc<Instance>,
surface: &Arc<Surface<Window>>,
physica_device_index: usize,
device: &Arc<Device>,
queue: &Arc<Queue>,
) -> Self {
let queue = queue.clone();
let (swapchain, images) = Self::create_swapchain(instance, surface, physica_device_index, device, &queue);
Self {
queue,
swapchain,
images
}
}
fn create_swapchain (
instance: &Arc<Instance>,
surface: &Arc<Surface<Window>>,
physica_device_index: usize,
device: &Arc<Device>,
queue: &Arc<Queue>,
) -> (Arc<Swapchain<Window>>, Vec<Arc<SwapchainImage<Window>>>) {
let window = surface.window();
let physical = PhysicalDevice::from_index(instance, physica_device_index).unwrap();
let caps = surface
.capabilities(physical)
.expect("Failed to get surface");
let usage = caps.supported_usage_flags;
let alpha = caps.supported_composite_alpha.iter().next().unwrap();
let format = caps.supported_formats[0].0;
let initial_dimensions = if let Some(dimensions) = window.get_inner_size() {
let dimensions: (u32, u32) = dimensions.to_physical(window.get_hidpi_factor()).into();
[dimensions.0, dimensions.1]
} else {
panic!("window no longer exists");
};
Swapchain::new(
device.clone(),
surface.clone(),
caps.min_image_count,
format,
initial_dimensions,
1,
usage,
queue,
SurfaceTransform::Identity,
alpha,
PresentMode::Fifo,
true,
None,
)
.unwrap()
}
pub fn format(&self) -> Format {
self.swapchain.format()
}
pub fn dimensions(&self) -> [u32; 2] {
self.images[0].dimensions()
}
pub fn images(&self) -> &[Arc<SwapchainImage<Window>>] {
&self.images
}
pub fn acquire_next_image(&self) -> (usize, SwapchainAcquireFuture<Window>){
swapchain::acquire_next_image(self.swapchain.clone(),None).unwrap()
}
pub fn queue(&self) -> &Arc<Queue> {
&self.queue
}
pub fn swapchain(&self) -> &Arc<Swapchain<Window>> {
&self.swapchain
}
}
| true
|
1f853f999d48a127055f19e9f649fadab0c2581c
|
Rust
|
Disasm/stm32f4xx-hal
|
/src/usb.rs
|
UTF-8
| 2,418
| 2.5625
| 3
|
[
"0BSD",
"BSD-3-Clause"
] |
permissive
|
//! USB peripheral
//!
//! Requires the `synopsys-usb-otg` feature and one of the `usb_fs`/`usb_hs` features.
//! See https://github.com/stm32-rs/stm32f4xx-hal/tree/master/examples
//! for usage examples.
use crate::stm32;
#[cfg(feature = "usb_fs")]
use crate::gpio::{Alternate, AF10, gpioa::{PA11, PA12}};
#[cfg(feature = "usb_hs")]
use crate::gpio::{Alternate, AF12, gpiob::{PB14, PB15}};
use synopsys_usb_otg::UsbPeripheral;
pub use synopsys_usb_otg::UsbBus;
#[cfg(feature = "usb_fs")]
pub struct Peripheral {
pub usb_global: stm32::OTG_FS_GLOBAL,
pub usb_device: stm32::OTG_FS_DEVICE,
pub usb_pwrclk: stm32::OTG_FS_PWRCLK,
pub pin_dm: PA11<Alternate<AF10>>,
pub pin_dp: PA12<Alternate<AF10>>,
}
#[cfg(feature = "usb_hs")]
pub struct Peripheral {
pub usb_global: stm32::OTG_HS_GLOBAL,
pub usb_device: stm32::OTG_HS_DEVICE,
pub usb_pwrclk: stm32::OTG_HS_PWRCLK,
pub pin_dm: PB14<Alternate<AF12>>,
pub pin_dp: PB15<Alternate<AF12>>,
}
unsafe impl Sync for Peripheral {}
#[cfg(feature = "usb_fs")]
unsafe impl UsbPeripheral for Peripheral {
//const REGISTERS: *const () = stm32::OTG_FS_GLOBAL::ptr() as *const ();
const REGISTERS: *const () = 0x50000000 as *const ();
const HIGH_SPEED: bool = false;
const FIFO_DEPTH_WORDS: usize = 320;
fn enable() {
let rcc = unsafe { &*stm32::RCC::ptr() };
cortex_m::interrupt::free(|_| {
// Enable USB peripheral
rcc.ahb2enr.modify(|_, w| w.otgfsen().set_bit());
// Reset USB peripheral
rcc.ahb2rstr.modify(|_, w| w.otgfsrst().set_bit());
rcc.ahb2rstr.modify(|_, w| w.otgfsrst().clear_bit());
});
}
}
#[cfg(feature = "usb_hs")]
unsafe impl UsbPeripheral for Peripheral {
//const REGISTERS: *const () = stm32::OTG_HS_GLOBAL::ptr() as *const ();
const REGISTERS: *const () = 0x40040000 as *const ();
const HIGH_SPEED: bool = true;
const FIFO_DEPTH_WORDS: usize = 1024;
fn enable() {
let rcc = unsafe { &*stm32::RCC::ptr() };
cortex_m::interrupt::free(|_| {
// Enable USB peripheral
rcc.ahb1enr.modify(|_, w| w.otghsen().set_bit());
// Reset USB peripheral
rcc.ahb1rstr.modify(|_, w| w.otghsrst().set_bit());
rcc.ahb1rstr.modify(|_, w| w.otghsrst().clear_bit());
});
}
}
pub type UsbBusType = UsbBus<Peripheral>;
| true
|
c4d3cead19dbcbcf447fb7e1d8b1573753ff6ed3
|
Rust
|
trayanr/fvm
|
/src/alias.rs
|
UTF-8
| 3,546
| 2.9375
| 3
|
[] |
no_license
|
use crate::{installation_path::get_installation_path, releases::Release};
use std::io::prelude::*;
use std::{fmt, fs::File, fs::OpenOptions, io::ErrorKind, io::Read, path::PathBuf};
pub struct AliasFile {
aliases: Vec<Alias>,
}
impl AliasFile {
pub fn open() -> AliasFile {
let aliases = get_aliases_path();
// println!("{}", aliases.to_str().unwrap());
match File::open(aliases.to_str().unwrap()) {
Ok(mut file) => {
let mut string_file = String::new();
file.read_to_string(&mut string_file).unwrap();
let lines: Vec<&str> = string_file.split("\n").collect();
let aliases = lines
.iter()
.cloned()
.filter(|l| l != &"")
.map(|l| Alias::parse(l.to_string()));
AliasFile {
aliases: aliases.collect(),
}
}
Err(e) => match e.kind() {
ErrorKind::NotFound => match File::create(aliases.to_str().unwrap()) {
Ok(f) => AliasFile { aliases: vec![] },
Err(ec) => {
panic!("Couldn't create file - {}", ec)
}
},
_ => {
println!("Couldn't open file - {}", e);
AliasFile { aliases: vec![] }
}
},
}
}
pub fn save(&self) {
let contents = self
.aliases
.iter()
.map(|a| format!("{}", a))
.collect::<Vec<String>>()
.join("\n");
let aliases = get_aliases_path();
match OpenOptions::new()
.write(true)
.create(true)
.open(aliases.to_str().unwrap())
{
Ok(f) => {
f.set_len(0).unwrap();
let mut writer = std::io::BufWriter::new(f);
writer.write_all(contents.as_bytes()).unwrap();
}
Err(e) => {
println!("Error saving aliases: {}", e);
}
}
}
pub fn push(&mut self, a: Alias) {
self.aliases.push(a);
self.save();
}
pub fn get(&self) -> Vec<Alias> {
self.aliases.to_vec()
}
pub fn remove_by_alias(&mut self, name: String) {
self.aliases = self
.aliases
.iter()
.cloned()
.filter(|a| a.name != name)
.collect();
self.save();
}
pub fn remove_by_version(&mut self, version: &String) {
self.aliases = self
.aliases
.iter()
.cloned()
.filter(|a| &a.dir_name != version)
.collect();
self.save();
}
}
fn get_aliases_path() -> PathBuf {
let mut root = get_installation_path();
root.push("aliases");
root
}
#[derive(Clone, Debug)]
pub struct Alias {
pub dir_name: String,
pub name: String,
}
impl Alias {
pub fn parse(s: String) -> Alias {
let elem: Vec<&str> = s.split(",").collect();
Alias {
dir_name: elem[0].to_string(),
name: elem[1].to_string(),
}
}
pub fn new(dir_name: String, name: String) -> Alias {
Alias {
dir_name: dir_name,
name,
}
}
}
impl fmt::Display for Alias {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{},{}", self.dir_name, self.name)
}
}
| true
|
6d561ed87e768ef38217950c59b34d9b65633e74
|
Rust
|
anasahmed700/Rust-examples
|
/ch04.1_ownership/src/main.rs
|
UTF-8
| 1,685
| 4.125
| 4
|
[] |
no_license
|
fn main() {
// types of string (&str and String)
// 1. hard coded string literal (&str) are immutable which stores memory on the stack which known at compile time
let mut _primitive_str = "Hello Literals";
// _primitive_str = _primitive_str + "some"; // can't concatenate
// 2. string complex (String) are mutable which allocate memory at runtime on the heap which unknown at compile time
let mut complex_str = String::from("Hello Complex");
println!("{}", complex_str);
complex_str.push_str(" World!"); // push_str() appends a literal to a String
println!("{}", complex_str);
complex_str = complex_str + " with concatenation"; // also can concatenate
println!("{}", complex_str);
// 2 Memory & allocation
if true{
let s = String::from("new string");// s is valid from this point forward which stored in heap memory
println!("{}", s);
} //When a variable goes out of scope, Rust calls a special function called "drop" to cleans up the heap memory for variable
let x = 5;
let y = x; // binding y with x
println!("x = {} y = {}",x, y); // runs smoothly
// 3. ownership moved
let s1 = String::from("hello"); // String store in two parts: stack(pointer,len,capacity) heap(string contents)
let s2 = s1; // here data from s1 stack is copied to s2 but not from heap that's why s1 is invalid now (s1 moved to s2)
println!("{}", s2); // new owner s2
// println!("{}", s1); // gets error
// deeply copy the heap data
let x1 = String::from("World");
let x2 = x1.clone(); // here is copied both stack & heap data
println!("x1 = {} x2 = {}", x1, x2);
}
| true
|
3f46f594738f85b0c1524f14a13a1e9d795eda3a
|
Rust
|
rkat0/AtCoder
|
/ABC095_ARC096/B.rs
|
UTF-8
| 691
| 3.125
| 3
|
[] |
no_license
|
use std::io::*;
fn read<T: std::str::FromStr>() -> T {
let stdin = stdin();
let mut buf = String::new();
stdin.lock().read_line(&mut buf);
buf.trim().parse().ok().unwrap()
}
fn read_vec<T: std::str::FromStr>() -> Vec<T> {
read::<String>().trim().split_whitespace()
.map(|w| w.parse().ok().unwrap()).collect()
}
fn read_mat<T: std::str::FromStr>(n: usize) -> Vec<Vec<T>> {
(0..n).map(|_| read_vec()).collect()
}
fn main() {
let v = read_vec::<usize>();
let (n,x) = (v[0],v[1]);
let ms: Vec<usize> = (0..n).map(|_| read()).collect();
let sum: usize = ms.iter().sum();
let min = ms.iter().min().unwrap();
println!("{}",n + (x - sum) / min);
}
| true
|
055c6b875a6f97406354fc1f86893c2dbb397995
|
Rust
|
xiaochai/batman
|
/RustProject/example/src/lib.rs
|
UTF-8
| 485
| 2.90625
| 3
|
[] |
no_license
|
//! # Art
//!
//! 测试用于艺术建模的库
pub use crate::kinds::PrimaryColor;
pub use crate::kinds::SecondaryColor;
pub use crate::utils::mixed;
pub mod kinds {
pub enum PrimaryColor {
Red,
Yellow,
Blue,
}
pub enum SecondaryColor {
Orange,
Green,
Purple,
}
}
pub mod utils{
use crate::kinds::*;
pub fn mixed(_c1:PrimaryColor, _c2:PrimaryColor) -> SecondaryColor{
SecondaryColor::Orange
}
}
| true
|
7d79f3d0e0ed1b31f7d447f12c949a28f821916e
|
Rust
|
GaiaWorld/pi_lib
|
/deque/src/deque.rs
|
UTF-8
| 7,591
| 3.046875
| 3
|
[
"Apache-2.0",
"MIT"
] |
permissive
|
//! 双端队列核心逻辑,通常不单独使用,而是需要与一个索引工厂配合使用。
//! 关于索引的意义,请参考:https://github.com/GaiaWorld/pi_lib/tree/master/dyn_uint
//! 由于需要从任意位置删除元素,我们未采用标准库使用vec作为双端队列内部容器的做法。
//! 如果要从任意位置删除,链表是个不错的选择。
//!
//! 简单的使用本双端队列,请使用slab_deque模块提供的双端队列
//! 要查看本模块的用法,可以参照slab_deque模块,和https://github.com/GaiaWorld/pi_lib/tree/master/task_pool库
use std::fmt::{Debug, Formatter, Result as FResult};
use std::marker::PhantomData;
use std::mem::replace;
use std::iter::Iterator;
use slab::IndexMap;
/// 双端队列
pub struct Deque<T, C: IndexMap<Node<T>>>{
first : usize,
last :usize,
len: usize,
mark: PhantomData<(T, C)>,
}
impl<T, C: IndexMap<Node<T>>> Default for Deque<T, C> {
fn default() -> Self {
Deque::new()
}
}
impl<T, C: IndexMap<Node<T>>> Deque<T, C> {
pub fn new() -> Self {
Self {
first: 0,
last: 0,
len: 0,
mark: PhantomData,
}
}
pub fn get_first(&self) -> usize {
self.first
}
pub fn get_last(&self) -> usize {
self.last
}
/// Append an element to the Deque. return a index
pub fn push_back(&mut self, elem: T, index_map: &mut C) -> usize {
self.len += 1;
if self.last == 0 {
let index = index_map.insert(Node::new(elem, 0, 0));
self.last = index;
self.first = index;
index
}else {
let index = index_map.insert(Node::new(elem, self.last, 0));
unsafe{index_map.get_unchecked_mut(self.last).next = index;}
self.last = index;
index
}
}
/// Prepend an element to the Deque. return a index
pub fn push_front(&mut self, elem: T, index_map: &mut C) -> usize{
self.len += 1;
if self.first == 0 {
let index = index_map.insert(Node::new(elem, 0, 0));
self.last = index;
self.first = index;
index
}else {
let index = index_map.insert(Node::new(elem, 0, self.first));
unsafe{index_map.get_unchecked_mut(self.first).pre = index;}
self.first = index;
index
}
}
/// Append an element to the Deque. return a index
pub unsafe fn push_to_back(&mut self, elem: T, index: usize, index_map: &mut C) -> usize{
self.len += 1;
let i = index_map.insert(Node::new(elem, index, 0));
let next = {
let e = index_map.get_unchecked_mut(index);
replace(&mut e.next, i)
};
if next == 0 {
self.last = i;
} else {
index_map.get_unchecked_mut(next).pre = i;
index_map.get_unchecked_mut(i).next = next;
}
i
}
/// Prepend an element to the Deque. return a index
pub unsafe fn push_to_front(&mut self, elem: T, index: usize, index_map: &mut C) -> usize{
self.len += 1;
let i = index_map.insert(Node::new(elem, 0, index));
let pre = {
let e = index_map.get_unchecked_mut(index);
replace(&mut e.pre, i)
};
if pre == 0 {
self.first = i;
} else {
index_map.get_unchecked_mut(pre).next = i;
index_map.get_unchecked_mut(i).pre = pre;
}
i
}
/// Removes the first element from the Deque and returns it, or panic if Deque is empty.
pub unsafe fn pop_front_unchecked(&mut self, index_map: &mut C) -> T {
self.len -= 1;
let node = index_map.remove(self.first);
self.first = node.next;
if self.first == 0 {
self.last = 0;
} else {
index_map.get_unchecked_mut(self.first).pre = 0;
}
node.elem
}
/// Removes the first element from the Deque and returns it, or None if it is empty.
pub fn pop_front(&mut self, index_map: &mut C) -> Option<T> {
if self.first == 0{
None
} else {
Some(unsafe { self.pop_front_unchecked(index_map) } )
}
}
/// Removes the last element from the Deque and returns it, or panic if Deque is empty.
pub unsafe fn pop_back_unchecked(&mut self, index_map: &mut C) -> T {
self.len -= 1;
let node = index_map.remove(self.last);
self.last = node.pre;
if self.last == 0 {
self.first = 0;
} else {
index_map.get_unchecked_mut(self.last).next = 0;
}
node.elem
}
/// Removes the last element from the Deque and returns it, or None if it is empty.
pub fn pop_back(&mut self, index_map: &mut C) -> Option<T> {
if self.last == 0 {
None
} else {
Some(unsafe { self.pop_back_unchecked(index_map) } )
}
}
///Removes and returns the element at index from the Deque.
pub fn remove(&mut self, index: usize, index_map: &mut C) -> T {
let node = index_map.remove(index);
match (node.pre, node.next) {
(0, 0) => {
//如果该元素既不存在上一个元素,也不存在下一个元素, 则设置队列的头部None, 则设置队列的尾部None
self.first = 0;
self.last = 0;
},
(_, 0) => {
//如果该元素存在上一个元素,不存在下一个元素, 则将上一个元素的下一个元素设置为None, 并设置队列的尾部为该元素的上一个元素
unsafe{ index_map.get_unchecked_mut(node.pre).next = 0};
self.last = node.pre;
},
(0, _) => {
//如果该元素不存在上一个元素,但存在下一个元素, 则将下一个元素的上一个元素设置为None, 并设置队列的头部为该元素的下一个元素
unsafe{ index_map.get_unchecked_mut(node.next).pre = 0};
self.first = node.next;
},
(_, _) => {
//如果该元素既存在上一个元素,也存在下一个元素, 则将上一个元素的下一个元素设置为本元素的下一个元素, 下一个元素的上一个元素设置为本元素的上一个元素
unsafe{ index_map.get_unchecked_mut(node.pre).next = node.next};
unsafe{ index_map.get_unchecked_mut(node.next).pre = node.pre};
},
}
self.len -= 1;
node.elem
}
///Removes and returns the element at index from the Deque.
pub fn try_remove(&mut self, index: usize, index_map: &mut C) -> Option<T> {
match index_map.contains(index){
true => Some(self.remove(index, index_map)),
false => None,
}
}
//clear Deque
pub fn clear(&mut self, index_map: &mut C) {
loop {
if self.first == 0 {
self.last = 0;
break;
}
let node = index_map.remove(self.first);
self.first = node.next;
}
self.len = 0;
}
//clear Deque
pub fn len(&self) -> usize {
self.len
}
pub fn iter<'a>(&self, container: &'a C) -> Iter<'a, T, C> {
Iter{
next: self.first,
container: container,
mark: PhantomData,
}
}
}
impl<T, C: IndexMap<Node<T>>> Clone for Deque<T, C>{
fn clone(&self) -> Deque<T, C>{
Deque {
first: self.first,
last: self.last,
len: self.len,
mark: PhantomData
}
}
}
pub struct Iter<'a, T: 'a, C: 'a + IndexMap<Node<T>>> {
next: usize,
container: &'a C,
mark: PhantomData<T>
}
impl<'a, T, C: IndexMap<Node<T>>> Iterator for Iter<'a, T, C> {
type Item = &'a T;
fn next(&mut self) -> Option<&'a T> {
if self.next == 0 {
return None;
}
let node = unsafe{self.container.get_unchecked(self.next)};
self.next = node.next;
Some(&node.elem)
}
}
impl<T, C: IndexMap<Node<T>>> Debug for Deque<T, C> {
fn fmt(&self, f: &mut Formatter) -> FResult {
f.debug_struct("Deque")
.field("first", &self.first)
.field("last", &self.last)
.finish()
}
}
pub struct Node<T>{
pub elem: T,
pub next: usize,
pub pre: usize,
}
impl<T> Node<T>{
fn new(elem: T, pre: usize, next: usize) -> Node<T>{
Node{
elem,
pre,
next,
}
}
}
impl<T: Debug> Debug for Node<T> {
fn fmt(&self, f: &mut Formatter) -> FResult {
f.debug_struct("Node")
.field("elem", &self.elem)
.field("pre", &self.pre)
.field("next", &self.next)
.finish()
}
}
| true
|
094a4e95b417a09a47fb4f85668145233aff7b3f
|
Rust
|
tillrohrmann/rust-challenges
|
/euler-67/src/lib.rs
|
UTF-8
| 975
| 3.296875
| 3
|
[
"Apache-2.0"
] |
permissive
|
use std::fs::File;
use std::io::{BufReader, BufRead};
use std::io::Error;
use std::io::Result;
pub fn find_maximum_path(filename: &str) -> Result<u64> {
let file = File::open(filename)?;
let buffered = BufReader::new(file);
let result: Vec<String> = buffered.lines().map(|line| line.unwrap()).collect();
let rows: Vec<Vec<u64>> = result.iter().map(|line| line.split_whitespace().map(|v| v.parse::<u64>().unwrap()).collect()).rev().collect();
let maximum_path = rows.into_iter().fold(Vec::new(), |acc, row| {
if acc.is_empty() {
row
} else {
assert!(acc.len() == row.len() + 1);
row.iter().enumerate().map(|(index, value)| value + u64::max(acc[index], acc[index + 1])).collect()
}
});
Ok(*maximum_path.get(0).unwrap())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
assert_eq!(find_maximum_path("simple_triangle.txt").unwrap(), 23);
}
}
| true
|
d6046c20893ebc547213b050954ff45b4fbed705
|
Rust
|
RonquilloAeon/cryptopanic-portfolio-tracker-rust
|
/src/main.rs
|
UTF-8
| 6,193
| 3.0625
| 3
|
[] |
no_license
|
use std::collections::HashMap;
use std::fs::create_dir;
use std::path::PathBuf;
use chrono::Utc;
use clap::{App, Arg, ArgMatches};
use dirs::home_dir;
use preferences::{AppInfo, Preferences, PreferencesMap};
use reqwest;
use serde_json;
use tokio::fs::File;
use tokio::io::AsyncWriteExt;
const AUTHOR: &str = "RonquilloAeon";
const API_BASE_URL: &str = "https://cryptopanic.com/api/v1";
const APP_INFO: AppInfo = AppInfo {
name: "CryptoPanicPortfolioFetcher",
author: AUTHOR,
};
const PREFERENCES_KEY: &str = "config";
async fn fetch_portfolio_data(api_token: &String) -> Result<String, std::io::Error> {
let client = reqwest::Client::new();
let data = client
.get(format!("{}/portfolio/", API_BASE_URL))
.query(&[("auth_token", api_token)])
.send()
.await
.expect("Error fetching")
.text()
.await
.expect("Error getting response text");
Ok(data)
}
fn process_portfolio_data(
data: String,
) -> Result<HashMap<String, serde_json::Value>, std::io::Error> {
let now = Utc::now().to_rfc3339();
// Deserialize portfolio data and add date
let mut values: HashMap<String, serde_json::Value> = serde_json::from_str(&data[..])?;
values.insert("date".to_string(), serde_json::Value::String(now));
Ok(values)
}
async fn save_portfolio(
data: HashMap<String, serde_json::Value>,
data_dir: PathBuf,
) -> Result<(), std::io::Error> {
// Get file name
let file_name_date_part = Utc::now().format("%Y-%m-%d-%H-%M").to_string();
let file_name = format!("{}_data.json", file_name_date_part);
// Save to file
let path = data_dir
.as_path()
.join(file_name)
.to_string_lossy()
.to_string();
let mut file = File::create(&path).await?;
file.write_all(serde_json::to_string(&data).unwrap().as_bytes())
.await?;
println!("Data saved to {}!", path);
Ok(())
}
fn get_preferences() -> PreferencesMap {
let result = PreferencesMap::<String>::load(&APP_INFO, PREFERENCES_KEY);
return match result {
Ok(prefs) => prefs,
Err(_) => PreferencesMap::new(),
};
}
fn get_data_dir(prefs: &PreferencesMap) -> Result<PathBuf, std::io::Error> {
let path = match prefs.contains_key("data_dir") {
true => PathBuf::from(prefs.get("data-dir").unwrap()),
false => {
let mut p = home_dir().unwrap();
p.push("CryptoPanicData");
p
}
};
if !path.exists() {
create_dir(&path)?;
}
Ok(path)
}
fn print_portfolio_data(data: &HashMap<String, serde_json::Value>) {
for currency in &["BTC", "USD"] {
println!(
"Total ({}): {}",
currency, data["portfolio"]["totals"][currency]
)
}
}
fn manage_configuration(prefs: &mut PreferencesMap, matches: &ArgMatches) {
// Handle changes
let mut changed = false;
if matches.is_present("api_token") {
prefs.insert(
"api-token".into(),
matches.value_of("api_token").unwrap().into(),
);
changed = true;
}
if matches.is_present("data_dir") {
let data_dir = matches.value_of("data_dir").unwrap();
prefs.insert("data-dir".into(), data_dir.into());
changed = true;
}
if changed {
let result = prefs.save(&APP_INFO, PREFERENCES_KEY);
assert!(result.is_ok());
}
// Optionally list preferences
if matches.is_present("list") {
for pref in prefs.into_iter() {
println!("{}={}", pref.0, pref.1)
}
}
}
async fn run_fetch_portfolio(
prefs: &PreferencesMap,
matches: &ArgMatches,
) -> Result<(), std::io::Error> {
if !prefs.contains_key("api-token") {
println!("Please set your API token using 'configure' command")
} else {
let data_dir = match get_data_dir(&prefs) {
Ok(path_buf) => path_buf,
Err(e) => panic!("Error selecting data dir: {}", e),
};
let results = fetch_portfolio_data(prefs.get("api-token").unwrap()).await;
if results.is_ok() {
let data = process_portfolio_data(results.unwrap()).unwrap();
print_portfolio_data(&data);
if !matches.is_present("no_save") {
save_portfolio(data, data_dir)
.await
.expect("Error saving portfolio data to file");
}
} else {
println!("Error fetching data: {}", results.err().unwrap())
}
}
Ok(())
}
#[tokio::main]
async fn main() {
let mut prefs = get_preferences();
let matches = App::new(APP_INFO.name)
.author(APP_INFO.author)
.subcommand(
App::new("configure")
.about("Configure the application")
.arg(
Arg::new("data_dir")
.short('d')
.long("data-dir")
.value_name("DATA_DIR")
.takes_value(true),
)
.arg(
Arg::new("list")
.short('l')
.long("list")
.value_name("LIST")
.takes_value(false),
)
.arg(
Arg::new("api_token")
.short('t')
.long("api-token")
.value_name("API_TOKEN")
.multiple(true),
),
)
.subcommand(
App::new("fetch").about("Fetch your portfolio").arg(
Arg::new("no_save")
.short('n')
.long("no-save")
.value_name("NO_SAVE")
.takes_value(false),
),
)
.get_matches();
// Let's go!
if let Some(ref matches) = matches.subcommand_matches("configure") {
manage_configuration(&mut prefs, &matches)
} else if let Some(ref matches) = matches.subcommand_matches("fetch") {
run_fetch_portfolio(&prefs, &matches).await.unwrap()
}
}
| true
|
b055d929e9715f026a9e20814c225ee5863f39de
|
Rust
|
IThawk/rust-project
|
/rust-master/src/test/ui/issues/issue-18783.rs
|
UTF-8
| 674
| 3.34375
| 3
|
[
"MIT",
"LicenseRef-scancode-other-permissive",
"Apache-2.0",
"BSD-3-Clause",
"BSD-2-Clause",
"NCSA"
] |
permissive
|
use std::cell::RefCell;
fn main() {
let mut y = 1;
let c = RefCell::new(vec![]);
c.push(Box::new(|| y = 0));
c.push(Box::new(|| y = 0));
//~^ ERROR cannot borrow `y` as mutable more than once at a time
}
fn ufcs() {
let mut y = 1;
let c = RefCell::new(vec![]);
Push::push(&c, Box::new(|| y = 0));
Push::push(&c, Box::new(|| y = 0));
//~^ ERROR cannot borrow `y` as mutable more than once at a time
}
trait Push<'c> {
fn push<'f: 'c>(&self, push: Box<dyn FnMut() + 'f>);
}
impl<'c> Push<'c> for RefCell<Vec<Box<dyn FnMut() + 'c>>> {
fn push<'f: 'c>(&self, fun: Box<dyn FnMut() + 'f>) {
self.borrow_mut().push(fun)
}
}
| true
|
54a706367fbf0e7cf0f52a4bbba8a7de36f774c7
|
Rust
|
justinj/last-layer-algs
|
/src/corner_permutation.rs
|
UTF-8
| 3,857
| 2.671875
| 3
|
[] |
no_license
|
use prunable::Prunable;
pub const CP_SOLVED: usize = 0;
const NUM_CORNERS: usize = 8;
const FACTORIAL: [u16; 8] = [
1,
1,
2,
6,
24,
120,
720,
5040,
];
pub type CPIndex = usize;
const NUM_PERMUTATIONS: usize = 40320;
#[derive(Debug, Copy, Clone)]
struct CornerPermutation {
state: [u8; NUM_CORNERS]
}
const MOVES_BY_INDEX: [CornerPermutation; 18] = [
CornerPermutation { state: [1, 2, 3, 0, 4, 5, 6, 7] }, // U
CornerPermutation { state: [2, 3, 0, 1, 4, 5, 6, 7] }, // U2
CornerPermutation { state: [3, 0, 1, 2, 4, 5, 6, 7] }, // U'
CornerPermutation { state: [0, 1, 2, 3, 5, 6, 7, 4] }, // D
CornerPermutation { state: [0, 1, 2, 3, 6, 7, 4, 5] }, // D2
CornerPermutation { state: [0, 1, 2, 3, 7, 4, 5, 6] }, // D'
CornerPermutation { state: [3, 1, 2, 5, 0, 4, 6, 7] }, // F
CornerPermutation { state: [5, 1, 2, 4, 3, 0, 6, 7] }, // F2
CornerPermutation { state: [4, 1, 2, 0, 5, 3, 6, 7] }, // F'
CornerPermutation { state: [0, 7, 1, 3, 4, 5, 2, 6] }, // B
CornerPermutation { state: [0, 6, 7, 3, 4, 5, 1, 2] }, // B2
CornerPermutation { state: [0, 2, 6, 3, 4, 5, 7, 1] }, // B'
CornerPermutation { state: [4, 0, 2, 3, 7, 5, 6, 1] }, // R
CornerPermutation { state: [7, 4, 2, 3, 1, 5, 6, 0] }, // R2
CornerPermutation { state: [1, 7, 2, 3, 0, 5, 6, 4] }, // R'
CornerPermutation { state: [0, 1, 6, 2, 4, 3, 5, 7] }, // L
CornerPermutation { state: [0, 1, 5, 6, 4, 2, 3, 7] }, // L2
CornerPermutation { state: [0, 1, 3, 5, 4, 6, 2, 7] }, // L'
];
impl CornerPermutation {
fn new(state: [u8; NUM_CORNERS]) -> Self {
CornerPermutation {
state: state
}
}
fn apply(&self, other: &Self) -> Self {
let mut state: [u8; NUM_CORNERS] = [0; NUM_CORNERS];
for i in 0..NUM_CORNERS {
state[i] = self.state[other.state[i] as usize];
}
CornerPermutation { state: state }
}
}
impl Prunable for CornerPermutation {
fn initial_pos() -> Self {
CornerPermutation {
state: [0, 1, 2, 3, 4, 5, 6, 7],
}
}
fn apply_idx(&self, idx: usize) -> Self {
Self::apply(&self, &MOVES_BY_INDEX[idx])
}
fn is_solved(&self) -> bool {
for i in 4..8 {
if self.state[i] != i as u8 {
return false;
}
}
true
}
fn index(&self) -> usize {
let mut state = self.state.clone();
let mut result: usize = 0;
for i in 0..NUM_CORNERS {
result += state[i] as usize * FACTORIAL[NUM_CORNERS - i - 1] as usize;
for j in (i + 1)..NUM_CORNERS {
if state[j] > state[i] {
state[j] -= 1;
}
}
}
result
}
fn total_states() -> usize { NUM_PERMUTATIONS }
}
lazy_static! {
pub static ref TRANSITIONS: Vec<[usize; 18]> = {
CornerPermutation::make_transition_table()
};
pub static ref PRUNING: Vec<u16> = {
CornerPermutation::make_pruning_table()
};
}
#[test]
fn performs_permutation() {
let perm = CornerPermutation::new([1, 0, 2, 3, 4, 5, 6, 7]);
let perm2 = CornerPermutation::new([0, 2, 1, 3, 7, 5, 6, 4]);
let composed = perm.apply(&perm2);
assert_eq!(vec![1, 2, 0, 3, 7, 5, 6, 4], composed.state);
}
#[test]
fn indexes_permutations() {
assert_eq!(0, CornerPermutation::new([0, 1, 2, 3, 4, 5, 6, 7]).index());
assert_eq!(1, CornerPermutation::new([0, 1, 2, 3, 4, 5, 7, 6]).index());
assert_eq!(40319, CornerPermutation::new([7, 6, 5, 4, 3, 2, 1, 0]).index());
assert_eq!(5880, CornerPermutation::new([1, 2, 3, 0, 4, 5, 6, 7]).index());
}
#[test]
fn lookup_table() {
assert_eq!(5880, TRANSITIONS[0][0]);
}
#[test]
fn pruning_table() {
assert_eq!(0, PRUNING[5880]);
}
| true
|
3588a7e3519601c7d5ee15988ffd09bf6d12767e
|
Rust
|
Rahix/shared-bus
|
/src/mutex.rs
|
UTF-8
| 7,028
| 3.6875
| 4
|
[
"MIT",
"Apache-2.0"
] |
permissive
|
use core::cell;
/// Common interface for mutex implementations.
///
/// `shared-bus` needs a mutex to ensure only a single device can access the bus at the same time
/// in concurrent situations. `shared-bus` already implements this trait for a number of existing
/// mutex types. Most of them are guarded by a feature that needs to be enabled. Here is an
/// overview:
///
/// | Mutex | Feature Name | Notes |
/// | --- | --- | --- |
/// | [`shared_bus::NullMutex`][null-mutex] | always available | For sharing within a single execution context. |
/// | [`std::sync::Mutex`][std-mutex] | `std` | For platforms where `std` is available. |
/// | [`cortex_m::interrupt::Mutex`][cortexm-mutex] | `cortex-m` | For Cortex-M platforms; Uses a critcal section (i.e. turns off interrupts during bus transactions). |
///
/// [null-mutex]: ./struct.NullMutex.html
/// [std-mutex]: https://doc.rust-lang.org/std/sync/struct.Mutex.html
/// [cortexm-mutex]: https://docs.rs/cortex-m/0.6.3/cortex_m/interrupt/struct.Mutex.html
///
/// For other mutex types, a custom implementation is needed. Due to the orphan rule, it might be
/// necessary to wrap it in a newtype. As an example, this is what such a custom implementation
/// might look like:
///
/// ```
/// struct MyMutex<T>(std::sync::Mutex<T>);
///
/// impl<T> shared_bus::BusMutex for MyMutex<T> {
/// type Bus = T;
///
/// fn create(v: T) -> Self {
/// Self(std::sync::Mutex::new(v))
/// }
///
/// fn lock<R, F: FnOnce(&mut Self::Bus) -> R>(&self, f: F) -> R {
/// let mut v = self.0.lock().unwrap();
/// f(&mut v)
/// }
/// }
///
/// // It is also beneficial to define a type alias for the BusManager
/// type BusManagerCustom<BUS> = shared_bus::BusManager<MyMutex<BUS>>;
/// ```
pub trait BusMutex {
/// The actual bus that is wrapped inside this mutex.
type Bus;
/// Create a new mutex of this type.
fn create(v: Self::Bus) -> Self;
/// Lock the mutex and give a closure access to the bus inside.
fn lock<R, F: FnOnce(&mut Self::Bus) -> R>(&self, f: F) -> R;
}
/// "Dummy" mutex for sharing in a single task/thread.
///
/// This mutex type can be used when all bus users are contained in a single execution context. In
/// such a situation, no actual mutex is needed, because a RefCell alone is sufficient to ensuring
/// only a single peripheral can access the bus at the same time.
///
/// This mutex type is used with the [`BusManagerSimple`] type.
///
/// To uphold safety, this type is `!Send` and `!Sync`.
///
/// [`BusManagerSimple`]: ./type.BusManagerSimple.html
#[derive(Debug)]
pub struct NullMutex<T> {
bus: cell::RefCell<T>,
}
impl<T> BusMutex for NullMutex<T> {
type Bus = T;
fn create(v: Self::Bus) -> Self {
NullMutex {
bus: cell::RefCell::new(v),
}
}
fn lock<R, F: FnOnce(&mut Self::Bus) -> R>(&self, f: F) -> R {
let mut v = self.bus.borrow_mut();
f(&mut v)
}
}
#[cfg(feature = "std")]
impl<T> BusMutex for ::std::sync::Mutex<T> {
type Bus = T;
fn create(v: Self::Bus) -> Self {
::std::sync::Mutex::new(v)
}
fn lock<R, F: FnOnce(&mut Self::Bus) -> R>(&self, f: F) -> R {
let mut v = self.lock().unwrap();
f(&mut v)
}
}
/// Alias for a Cortex-M mutex.
///
/// Based on [`cortex_m::interrupt::Mutex`][cortexm-mutex]. This mutex works by disabling
/// interrupts while the mutex is locked.
///
/// [cortexm-mutex]: https://docs.rs/cortex-m/0.6.3/cortex_m/interrupt/struct.Mutex.html
///
/// This type is only available with the `cortex-m` feature.
#[cfg(feature = "cortex-m")]
pub type CortexMMutex<T> = cortex_m::interrupt::Mutex<cell::RefCell<T>>;
#[cfg(feature = "cortex-m")]
impl<T> BusMutex for CortexMMutex<T> {
type Bus = T;
fn create(v: T) -> Self {
cortex_m::interrupt::Mutex::new(cell::RefCell::new(v))
}
fn lock<R, F: FnOnce(&mut Self::Bus) -> R>(&self, f: F) -> R {
cortex_m::interrupt::free(|cs| {
let c = self.borrow(cs);
f(&mut c.borrow_mut())
})
}
}
/// Wrapper for an interrupt free spin mutex.
///
/// Based on [`spin::Mutex`][spin-mutex]. This mutex works by disabling
/// interrupts while the mutex is locked.
///
/// [spin-mutex]: https://docs.rs/spin/0.9.2/spin/type.Mutex.html
///
/// This type is only available with the `xtensa` feature.
#[cfg(feature = "xtensa")]
pub struct XtensaMutex<T>(spin::Mutex<T>);
#[cfg(feature = "xtensa")]
impl<T> BusMutex for XtensaMutex<T> {
type Bus = T;
fn create(v: T) -> Self {
XtensaMutex(spin::Mutex::new(v))
}
fn lock<R, F: FnOnce(&mut Self::Bus) -> R>(&self, f: F) -> R {
xtensa_lx::interrupt::free(|_| f(&mut (*self.0.lock())))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn std_mutex_api_test() {
let t = "hello ".to_string();
let m: std::sync::Mutex<_> = BusMutex::create(t);
BusMutex::lock(&m, |s| {
s.push_str("world");
});
BusMutex::lock(&m, |s| {
assert_eq!("hello world", s);
});
}
}
/// A simple coherency checker for sharing across multiple tasks/threads.
///
/// This mutex type can be used when all bus users are contained in a single structure, and is
/// intended for use with RTIC. When all bus users are contained within a structure managed by RTIC,
/// RTIC will guarantee that bus collisions do not occur. To protect against accidentaly misuse,
/// this mutex uses an atomic bool to determine when the bus is in use. If a bus collision is
/// detected, the code will panic.
///
/// This mutex type is used with the [`BusManagerAtomicMutex`] type.
///
/// This manager type is explicitly safe to share across threads because it checks to ensure that
/// collisions due to bus sharing do not occur.
///
/// [`BusManagerAtomicMutex`]: ./type.BusManagerAtomicMutex.html
#[cfg(feature = "cortex-m")]
#[derive(Debug)]
pub struct AtomicCheckMutex<BUS> {
bus: core::cell::UnsafeCell<BUS>,
busy: atomic_polyfill::AtomicBool,
}
// It is explicitly safe to share this across threads because there is a coherency check using an
// atomic bool comparison.
#[cfg(feature = "cortex-m")]
unsafe impl<BUS> Sync for AtomicCheckMutex<BUS> {}
#[cfg(feature = "cortex-m")]
impl<BUS> BusMutex for AtomicCheckMutex<BUS> {
type Bus = BUS;
fn create(v: BUS) -> Self {
Self {
bus: core::cell::UnsafeCell::new(v),
busy: atomic_polyfill::AtomicBool::from(false),
}
}
fn lock<R, F: FnOnce(&mut Self::Bus) -> R>(&self, f: F) -> R {
self.busy
.compare_exchange(
false,
true,
core::sync::atomic::Ordering::SeqCst,
core::sync::atomic::Ordering::SeqCst,
)
.expect("Bus conflict");
let result = f(unsafe { &mut *self.bus.get() });
self.busy.store(false, core::sync::atomic::Ordering::SeqCst);
result
}
}
| true
|
47e3d6871df1e7b0bbb7cd4bb956ec066bd87eed
|
Rust
|
azriel91/autexousious
|
/crate/collision_model/src/config/hit_repeat_delay.rs
|
UTF-8
| 627
| 2.546875
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] |
permissive
|
use amethyst::ecs::{storage::VecStorage, Component};
use derivative::Derivative;
use derive_more::{Add, AddAssign, Display, From, Sub, SubAssign};
use numeric_newtype_derive::numeric_newtype;
use serde::{Deserialize, Serialize};
/// Default number of ticks to wait before another hit may occur.
const HIT_REPEAT_DELAY_DEFAULT: u32 = 10;
/// Number of ticks to wait before another hit may occur.
#[numeric_newtype]
#[derive(Component, Debug, Derivative, Deserialize, Hash, Serialize)]
#[derivative(Default)]
#[storage(VecStorage)]
pub struct HitRepeatDelay(#[derivative(Default(value = "HIT_REPEAT_DELAY_DEFAULT"))] pub u32);
| true
|
9175fb6d702d78363bdd3e2c8294194b8fd3dc18
|
Rust
|
jasilven/chat
|
/src/main.rs
|
UTF-8
| 9,745
| 2.875
| 3
|
[] |
no_license
|
use anyhow::Result;
use async_std::channel::{bounded, Receiver, Sender};
use async_std::io::BufReader;
use async_std::net::{TcpListener, TcpStream};
use async_std::prelude::*;
use async_std::task;
use std::collections::HashMap;
use std::net::{SocketAddr, SocketAddrV4};
use rand::distributions::Alphanumeric;
use rand::Rng;
#[derive(Debug, Clone)]
struct Client {
nick: String,
stream: TcpStream,
}
#[derive(Debug)]
enum Command {
MsgToAll(SocketAddrV4, String),
MsgToOne(SocketAddrV4, String),
Quit(SocketAddrV4),
New(SocketAddrV4, Client),
ChangeNick(SocketAddrV4, String),
Users(SocketAddrV4),
Me(SocketAddrV4),
}
struct Server {
rx: Receiver<Command>,
clients: HashMap<SocketAddrV4, Client>,
}
impl Server {
fn new(rx: Receiver<Command>) -> Self {
Server {
rx,
clients: HashMap::new(),
}
}
fn random_nick(&self) -> Result<String> {
let mut limit = 10;
loop {
if limit == 0 {
anyhow::bail!("unable to generate nick");
}
let nick = rand::thread_rng()
.sample_iter(&Alphanumeric)
.take(6)
.collect::<String>();
if self.clients.iter().all(|(_, client)| client.nick != nick) {
return Ok(nick);
}
limit -= 1;
}
}
async fn broadcast(&mut self, addr: &SocketAddrV4, is_admin: bool, s: &str) {
let time = chrono::Local::now().format("%H:%M:%S").to_string();
let msg = s.trim();
if let Some(client) = self.clients.get(addr) {
eprintln!("{} says '{}'", client.nick, msg);
let line = if is_admin {
format!("{} <{}>\n", time, msg)
} else {
format!("{} [{}]: {}\n", time, client.nick, msg)
};
for (_, client) in self.clients.iter_mut().filter(|(a, _)| a.ne(&addr)) {
if let Err(e) = client.stream.write_all(line.as_bytes()).await {
eprintln!("broadcast error: {}", e);
}
}
}
}
async fn send_message(&mut self, addr: &SocketAddrV4, s: &str) {
let msg = format!("{}\n", s.trim());
eprintln!(
"sending message '{}' to addr '{}' ",
msg.as_str().trim(),
addr
);
if let Some(client) = self.clients.get_mut(addr) {
if let Err(e) = client.stream.write_all(msg.as_bytes()).await {
eprintln!("send_message error: {}", e);
}
}
}
async fn change_nick(&mut self, addr: &SocketAddrV4, nick: &str) -> Result<String> {
if self
.clients
.iter()
.find(|(_, client)| client.nick == nick)
.is_some()
{
anyhow::bail!("Nick '{}' already present!", nick);
}
if let Some(client) = self.clients.get_mut(&addr) {
let old_nick = client.nick.clone();
client.nick = nick.to_string();
return Ok(old_nick);
} else {
anyhow::bail!("Cannot change nick.");
}
}
async fn new_client(&mut self, addr: SocketAddrV4, mut client: Client) -> Result<String> {
let nick = self.random_nick().unwrap_or("<anonymous>".to_string());
if !self.clients.contains_key(&addr) {
client.nick = nick.clone();
self.clients.insert(addr, client);
Ok(nick)
} else {
anyhow::bail!("Client '{}' already present!", addr);
}
}
async fn run(&mut self) -> Result<()> {
loop {
match self.rx.recv().await? {
Command::New(addr, client) => {
eprintln!("new client: {}", addr);
match self.new_client(addr, client).await {
Ok(nick) => {
self.broadcast(&addr, true, &format!("{} joined", &nick))
.await;
self.send_message(&addr, &format!("Hello '{}'!", &nick))
.await;
}
Err(e) => {
self.send_message(&addr, &e.to_string()).await;
}
}
}
Command::ChangeNick(addr, nick) => match self.change_nick(&addr, &nick).await {
Ok(old_nick) => {
self.broadcast(&addr, true, &format!("{} is now {}", &old_nick, &nick))
.await;
self.send_message(&addr, &format!("You are now '{}'!", &nick))
.await;
}
Err(e) => {
self.send_message(&addr, &e.to_string()).await;
}
},
Command::Quit(addr) => {
let nick = if let Some(client) = self.clients.get(&addr) {
client.nick.clone()
} else {
"<anonymous>".to_string()
};
self.broadcast(&addr, true, &format!("{} left", nick)).await;
self.clients.remove(&addr);
}
Command::MsgToAll(addr, s) => {
eprintln!("broadcasting: {}", &s);
self.broadcast(&addr, false, &s).await;
}
Command::MsgToOne(addr, s) => {
eprintln!("private: {}", &s);
self.send_message(&addr, &s).await;
}
Command::Users(addr) => {
let mut users = vec![];
self.clients.iter().for_each(|(_, c)| {
users.push(c.nick.clone());
});
self.send_message(
&addr,
&format!(
"{} users online: [{}]\n",
self.clients.len(),
users.join(", ")
),
)
.await;
}
Command::Me(addr) => {
let nick = if let Some(client) = self.clients.get(&addr) {
client.nick.clone()
} else {
"<anonymous>".to_string()
};
self.send_message(
&addr,
&format!("You are '{}' connected from '{}'", &nick, addr),
)
.await;
}
}
}
}
}
async fn handle_client(stream: TcpStream, addr: SocketAddrV4, tx: Sender<Command>) -> Result<()> {
eprintln!("connection from: {} ", &addr);
// TODO: implement Client::new(stream)
let client = Client {
nick: "".to_string(),
stream: stream.clone(),
};
tx.send(Command::New(addr, client)).await;
let mut reader = BufReader::new(stream);
let mut buf = String::from("");
loop {
match reader.read_line(&mut buf).await {
Ok(0) => {
tx.send(Command::Quit(addr)).await?;
break;
}
Ok(_) => {
if let Some(cmd) = buf.split_ascii_whitespace().next() {
match cmd {
"/quit" => {
tx.send(Command::Quit(addr)).await?;
break;
}
"/nick" => {
if let Some(nick) = buf.split_ascii_whitespace().nth(1) {
tx.send(Command::ChangeNick(addr, nick.to_string())).await?;
} else {
tx.send(Command::Me(addr)).await?;
}
}
"/users" => {
tx.send(Command::Users(addr)).await?;
}
"/me" => {
tx.send(Command::Me(addr)).await?;
}
_ => {
if cmd.starts_with('/') {
tx.send(Command::MsgToOne(
addr,
format!("no such command '{}'", cmd),
))
.await?;
} else {
let line = buf.trim().to_string();
tx.send(Command::MsgToAll(addr, line)).await;
}
}
}
}
}
Err(e) => {
anyhow::bail!(e);
}
}
buf.clear();
}
Ok(())
}
#[async_std::main]
async fn main() -> Result<()> {
let listener = TcpListener::bind("127.0.0.1:8080").await?;
let (tx, rx) = bounded(100);
task::spawn(async move {
if let Err(e) = Server::new(rx).run().await {
panic!("server crash: {}", e);
}
});
loop {
let (stream, addr) = listener.accept().await?;
if let SocketAddr::V4(addr) = addr {
let tx2 = tx.clone();
task::spawn(async move {
match handle_client(stream, addr, tx2).await {
Ok(_) => {}
Err(e) => eprintln!("Unable to handle client: {}", e),
};
});
}
}
}
| true
|
78dbde10ae31c2d0e8315fd6dfa61d20e9fcbc44
|
Rust
|
arbaregni/resolution-prover
|
/src/prover/mod.rs
|
UTF-8
| 18,170
| 3.1875
| 3
|
[] |
no_license
|
#[macro_use]
mod clause;
pub use clause::*;
mod term_tree;
pub use term_tree::*;
mod clause_set;
pub use clause_set::*;
use crate::ast::{Expr, SymbolTable};
use crate::error::BoxedErrorTrait;
/// Uses proof by contradiction to search for a proof of `goal` from `givens`
/// If it runs without internal error, returns `Ok(true)` if such a proof is found
pub fn find_proof(symbols: &mut SymbolTable, givens: Vec<Expr>, goal: Expr) -> Result<bool, BoxedErrorTrait> {
let mut clause_set = ClosedClauseSet::new();
// enter all the givens
for expr in givens {
expr.into_clauses(symbols, &mut clause_set)?;
}
// we do proof by contradiction
// negate the goal, and if we find a contradiction, that's a proof
goal
.negate()
.into_clauses(symbols, &mut clause_set)?;
// clause_set.term_tree.pretty_print(&mut io::stdout()).unwrap();
// a contradiction means that the system was inconsistent with `not goal`,
// meaning we have proven `goal`
clause_set.has_contradiction()
}
#[cfg(test)]
mod tests {
use crate::prover::{Clause, ClosedClauseSet, find_proof, ClauseBuilder};
use crate::ast::{ExprKind, Term, SymbolTable};
#[test]
fn resolution_simple_0() {
let mut symbols = SymbolTable::new();
let p = symbols.make_fun();
let q = symbols.make_fun();
let r = symbols.make_fun();
let a = clause!(p, q);
let b = clause!(~q, r);
assert_eq!(Clause::resolve(&a, &b), Some(clause!(p, r)));
}
#[test]
fn resolution_simple_1() {
let mut symbols = SymbolTable::new();
let p = symbols.make_fun();
let q = symbols.make_fun();
let a = clause!(~p, q); // equivalent to p -> q
let b = clause!(p);
assert_eq!(Clause::resolve(&a, &b), Some(clause!(q)));
}
#[test]
fn resolution_simple_2() {
let mut symbols = SymbolTable::new();
let p = symbols.make_fun();
let a = clause!(p);
let b = clause!(~p);
assert_eq!(Clause::resolve(&a, &b), Some(clause!()));
}
#[test]
fn resolution_simple_3() {
let mut symbols = SymbolTable::new();
let p = symbols.make_fun();
let q = symbols.make_fun();
let m = symbols.make_fun();
let a = clause!(~m, p, q);
let b = clause!(~p, q);
assert_eq!(Clause::resolve(&a, &b), Some(clause!(~m, q)));
}
#[test]
fn clause_intern_0() {
let mut symbols = SymbolTable::new();
let p = symbols.make_fun();
let q = symbols.make_fun();
let r = symbols.make_fun();
let mut interner = ClosedClauseSet::new();
let a = interner.integrate_clause(clause!(p, ~q, r));
let b = interner.integrate_clause(clause!(p, ~q, r));
assert_eq!(a, b);
}
#[test]
fn satisfy_simple_0() {
let mut clause_set = ClosedClauseSet::new();
clause_set.integrate_clause(clause!()); // contradiction immediately
let success = clause_set.has_contradiction().expect("should not error");
assert_eq!(success, true); // should recognize the immediate contradiction
}
#[test]
fn satisfy_simple_1() {
let mut symbols = SymbolTable::new();
let p = symbols.make_fun();
let mut clause_set = ClosedClauseSet::new();
clause_set.integrate_clause(clause!(p));
clause_set.integrate_clause(clause!(~p));
let success = clause_set.has_contradiction().expect("should not error");
assert_eq!(success, true); // both q and ~q is a contradiction
}
#[test]
fn satisfy_simple_2() {
let mut symbols = SymbolTable::new();
let p = symbols.make_fun();
let q = symbols.make_fun();
let mut clause_set = ClosedClauseSet::new();
clause_set.integrate_clause(clause!(p, q)); // p or q
clause_set.integrate_clause(clause!(~p)); // not p, so q is true
clause_set.integrate_clause(clause!(~q)); // q is not true
let success = clause_set.has_contradiction().expect("should not error");
assert_eq!(success, true); // both q and ~q is a contradiction
}
#[test]
fn satisfy_simple_3() {
let mut symbols = SymbolTable::new();
let p = symbols.make_fun();
let q = symbols.make_fun();
let mut clause_set= ClosedClauseSet::new();
clause_set.integrate_clause(clause!(~p, q)); // p => q
clause_set.integrate_clause(clause!(p)); // p is true
clause_set.integrate_clause(clause!(q)); // q is true
let success = clause_set.has_contradiction().expect("should not error");
assert_eq!(success, false); // there is no contradiction
}
#[test]
fn satisfy_simple_4() {
let mut symbols = SymbolTable::new();
let p = symbols.make_fun();
let q = symbols.make_fun();
let r = symbols.make_fun();
let mut clause_set = ClosedClauseSet::new();
clause_set.integrate_clause(clause!(~p, q)); // p => q
clause_set.integrate_clause(clause!(~q, r)); // q => r
clause_set.integrate_clause(clause!(p)); // p is true
clause_set.integrate_clause(clause!(~r)); // r is false
let success = clause_set.has_contradiction().expect("should not error");
assert_eq!(success, true); // there is a contradiction because we can derive r
}
#[test]
fn satisfy_simple_5() {
let mut symbols = SymbolTable::new();
let p = symbols.make_fun();
let q = symbols.make_fun();
let r = symbols.make_fun();
let mut clause_set = ClosedClauseSet::new();
clause_set.integrate_clause(clause!( p, q)); // p or q
clause_set.integrate_clause(clause!(~p, r)); // not p or r
clause_set.integrate_clause(clause!(~p, ~r)); // not p or not r
clause_set.integrate_clause(clause!( p, ~q)); // p or not q
// derivation of paradox:
// (1) p or q given
// (2) p or ~q given
// (3) p resolution (1, 2)
// (4) ~p or r given
// (5) r resolution (3, 4)
// (6) ~p or ~r given
// (7) ~r resolution (3, 6)
// (8) {} resolution (5, 7)
let success = clause_set.has_contradiction().expect("should not error");
assert_eq!(success, true); // there is a contradiction
}
#[test]
fn satisfy_fol_0() {
let mut symbols = SymbolTable::new();
let x = symbols.make_var();
let p = symbols.make_fun();
let q = symbols.make_fun();
let a = symbols.make_fun();
let mut clause_set = ClosedClauseSet::new();
// P(x) implies Q(x)
let clause = ClauseBuilder::new()
.set(Term::predicate(p, vec![
Term::variable(x),
]), false)
.set(Term::predicate(q, vec![
Term::variable(x),
]), true)
.finish().expect("not a tautology");
clause_set.integrate_clause(clause);
// P(a)
let clause = ClauseBuilder::new()
.set(Term::predicate(p, vec![
Term::atom(a),
]), true)
.finish().expect("not a tautology");
clause_set.integrate_clause(clause);
let success = clause_set.has_contradiction().expect("should not error");
assert_eq!(success, false);
// make sure that we've derived what Q(a)
let clause = ClauseBuilder::new()
.set(Term::predicate(q, vec![
Term::atom(a),
]), true)
.finish().expect("not a tautology");
println!("{:#?}", clause_set);
assert!(clause_set.clauses.contains(&clause));
}
#[test]
fn satisfy_fol_1() {
let mut symbols = SymbolTable::new();
let x = symbols.make_var();
let y = symbols.make_var();
let p = symbols.make_fun();
let a = symbols.make_fun();
let mut clause_set = ClosedClauseSet::new();
// P(x) or P(y)
let clause = ClauseBuilder::new()
.set(Term::predicate(p, vec![
Term::variable(x),
]), true)
.set(Term::predicate(p, vec![
Term::variable(y),
]), true)
.finish().expect("not a tautology");
clause_set.integrate_clause(clause);
// ~P(a)
let clause = ClauseBuilder::new()
.set(Term::predicate(p, vec![
Term::atom(a),
]), false)
.finish().expect("not a tautology");
clause_set.integrate_clause(clause);
let success = clause_set.has_contradiction().expect("should not error");
// derivation:
// P(x) or P(y)
// P(x) reduce (factor) by unifying x and y
// P(a) unify x with a
// ~P(a)
// contradiction!
println!("{:#?}", clause_set);
assert_eq!(success, true);
}
#[test]
fn satisfy_fol_2() {
let mut symbols = SymbolTable::new();
let u = symbols.make_var();
let v = symbols.make_var();
let w = symbols.make_var();
let x = symbols.make_var();
let f = symbols.make_fun();
let p = symbols.make_fun();
// P(u) or P(f(u))
let clause_0 = ClauseBuilder::new()
.set(Term::predicate(p, vec![
Term::variable(u)
]), true)
.set(Term::predicate(p, vec![
Term::predicate(f, vec![
Term::variable(u)
])
]), true)
.finish().expect("not a tautology");
// ~P(v) or P(f(w))
let clause_1 = ClauseBuilder::new()
.set(Term::predicate(p, vec![
Term::variable(v)
]), false)
.set(Term::predicate(p, vec![
Term::predicate(f, vec![
Term::variable(w)
])
]), true)
.finish().expect("not a tautology");
// ~P(x) or not P(f(x))
let clause_2 = ClauseBuilder::new()
.set(Term::predicate(p, vec![
Term::variable(x)
]), false)
.set(Term::predicate(p, vec![
Term::predicate(f, vec![
Term::variable(x)
])
]), false)
.finish().expect("not a tautology");
let mut clause_set = ClosedClauseSet::new();
clause_set.integrate_clause(clause_0);
clause_set.integrate_clause(clause_1);
clause_set.integrate_clause(clause_2);
// clause_set.term_tree.pretty_print(&mut std::io::stdout()).unwrap();
let success = clause_set.has_contradiction().expect("should not error");
// derivation of a contradiction:
// 0. P(u) or P(f(u)) given 0
// 1. ~P(v) or P(f(w)) given 1
// 2. ~P(x) or ~P(f(x)) given 2
// 3. P(u) or P(f(w)) resolve (0) and (1), with v = f(u)
// 4. P(f(w)) factor (3) with u = f(w)
// 5. ~P(f(f(w))) resolve (4) and (2) with x = f(w)
// 6. :(
println!("{:#?}", clause_set);
assert_eq!(success, true);
}
#[test]
fn provability_simple_0() {
let mut symbols = SymbolTable::new();
let it_rains = symbols.make_fun();
let get_wet = symbols.make_fun();
let will_fall = symbols.make_fun();
let givens = vec![
ExprKind::If(
Term::atom(it_rains).into(),
Term::atom(get_wet).into(),
).into(),
ExprKind::If(
Term::atom(get_wet).into(),
Term::atom(will_fall).into(),
).into(),
Term::atom(it_rains).into(),
];
let goal = Term::atom(will_fall).into();
let success = find_proof(&mut symbols, givens, goal).expect("should not fail");
assert_eq!(success, true);
}
#[test]
fn provability_simple_1() {
let mut symbols = SymbolTable::new();
let it_rains = symbols.make_fun();
let get_wet = symbols.make_fun();
let will_fall = symbols.make_fun();
let givens = vec![
ExprKind::If(
Term::atom(it_rains).into(), // if it_rains, you will get wet
Term::atom(get_wet).into(),
).into(),
ExprKind::If(
Term::atom(get_wet).into(), // if you get wet, you will fall
Term::atom(will_fall).into(),
).into(),
];
let goal = ExprKind::If( // therefore, if it_rains, you will fall
Term::atom(it_rains).into(),
Term::atom(will_fall).into(),
).into();
let success = find_proof(&mut symbols, givens, goal).expect("should not fail");
assert_eq!(success, true);
}
#[test]
fn provability_simple_2() {
let mut symbols = SymbolTable::new();
let it_rains = symbols.make_fun();
let get_wet = symbols.make_fun();
let will_fall = symbols.make_fun();
let givens = vec![
ExprKind::If(
Term::atom(it_rains).into(), // if it_rains, you will get wet
Term::atom(get_wet).into(),
).into(),
ExprKind::If(
Term::atom(get_wet).into(), // if you get wet, you will fall
Term::atom(will_fall).into(),
).into(),
];
let goal = Term::atom(will_fall).into();
let success = find_proof(&mut symbols, givens, goal).expect("should not fail");
assert_eq!(success, false); // we can't prove definitely that you will fall
}
#[test]
fn provability_simple_3() {
let mut symbols = SymbolTable::new();
let p = symbols.make_fun();
let q = symbols.make_fun();
let zeta = symbols.make_fun();
let givens = vec![
ExprKind::Or(vec![
Term::atom(p).into(),
ExprKind::Not(
Term::atom(q).into(),
).into(),
]).into(),
ExprKind::Or(vec![
Term::atom(q).into(),
ExprKind::Not(
Term::atom(p).into(),
).into(),
]).into(),
];
// this is a consistent set of givens
// we should NOT be able to prove an arbitrary formula
let goal = Term::atom(zeta).into();
let success = find_proof(&mut symbols, givens, goal).expect("should not error");
assert_eq!(success, false);
}
#[test]
fn provability_medium_0() {
let mut symbols = SymbolTable::new();
let it_rains = symbols.make_fun();
let get_wet = symbols.make_fun();
let it_lightnings = symbols.make_fun();
let it_thunders = symbols.make_fun();
let will_be_scared = symbols.make_fun();
let will_fall = symbols.make_fun();
let it_hails = symbols.make_fun();
let it_snows = symbols.make_fun();
let will_be_slippery = symbols.make_fun();
let clear_skies = symbols.make_fun();
let givens = vec![
// if it rains, you will get wet
ExprKind::If(
Term::atom(it_rains).into(),
Term::atom(get_wet).into(),
).into(),
// if you get wet, you will fall
ExprKind::If(
Term::atom(get_wet).into(),
Term::atom(will_fall).into(),
).into(),
// if it lightnings, you will be scared
ExprKind::If(
Term::atom(it_lightnings).into(),
Term::atom(will_be_scared).into(),
).into(),
// if you're scared, you will fall
ExprKind::If(
Term::atom(will_be_scared).into(),
Term::atom(will_fall).into(),
).into(),
// if it hails or snows, you will be slippery
ExprKind::If(
ExprKind::Or(vec![
Term::atom(it_hails).into(),
Term::atom(it_snows).into(),
]).into(),
Term::atom(will_be_slippery).into(),
).into(),
// if you're slippery, you will fall
ExprKind::If(
Term::atom(will_be_slippery).into(),
Term::atom(will_fall).into(),
).into(),
// one of these will happen
ExprKind::Or(vec![
// it will rain, ...
Term::atom(it_rains).into(),
// or will be clear skies, ...
Term::atom(clear_skies).into(),
// or, will be one of these:
ExprKind::Or(vec![
// all of these will happen:
ExprKind::And(vec![
// it rains, ...
Term::atom(it_rains).into(),
// and, if it rains, it thunders, ...
ExprKind::If(
Term::atom(it_rains).into(),
Term::atom(it_thunders).into(),
).into(),
// and, if it thunders, it lightnings
ExprKind::If(
Term::atom(it_thunders).into(),
Term::atom(it_lightnings).into(),
).into()
]).into(),
// or, it will hail
Term::atom(it_hails).into(),
// or, it will snow
Term::atom(it_snows).into(),
]).into()
]).into(),
];
let goal = ExprKind::Or(vec![
Term::atom(clear_skies).into(),
Term::atom(will_fall).into()
]).into();
let success = find_proof(&mut symbols, givens, goal).expect("should not error");
assert_eq!(success, true);
}
}
| true
|
58a2752da3a52346144cc4d47d447c1d777511b4
|
Rust
|
trolleyman/Portal2
|
/src/key.rs
|
UTF-8
| 883
| 2.984375
| 3
|
[] |
no_license
|
#[allow(unused_imports)]
use prelude::*;
use std::collections::HashSet;
use glutin::VirtualKeyCode as Key;
use glutin::ElementState;
pub struct KeyboardState {
pressed_keys: HashSet<Key>,
}
impl KeyboardState {
pub fn new() -> KeyboardState {
KeyboardState {
pressed_keys: HashSet::new(),
}
}
pub fn key_state(&self, key: Key) -> ElementState {
if self.pressed_keys.contains(&key) {
ElementState::Pressed
} else {
ElementState::Released
}
}
pub fn is_key_down(&self, key: Key) -> bool {
self.key_state(key) == ElementState::Pressed
}
pub fn is_key_up(&self, key: Key) -> bool {
self.key_state(key) == ElementState::Released
}
pub fn set_key_state(&mut self, key: Key, state: ElementState) {
match state {
ElementState::Pressed => { self.pressed_keys.insert(key); },
ElementState::Released => { self.pressed_keys.remove(&key); }
}
}
}
| true
|
31840f944151f7cef630e173cb0b497c0be11568
|
Rust
|
MovAh13h/mkv
|
/src/main.rs
|
UTF-8
| 3,001
| 2.609375
| 3
|
[] |
no_license
|
mod record;
mod hash;
mod remote;
mod mkv;
use mkv::Minikeyvalue;
use clap::{App, Arg};
fn main() {
let matches = App::new("Minikeyvalue")
.version("0.1.0")
.author("Tanishq Jain <tanishqjain1002@gmail.com>")
.about("A Rust port of minikeyvalue (https://github.com/geohot/minikeyvalue)")
.usage("Usage: ./mkv <server, rebuild, rebalance> [FLAGS] [OPTIONS]")
.arg(Arg::with_name("command")
.help("Command to run from server, rebalance, rebuild")
.required(true)
.index(1))
.arg(Arg::with_name("port")
.short("p")
.long("port")
.value_name("PORT")
.help("Port for the server to listen on")
.default_value("3000")
.takes_value(true))
.arg(Arg::with_name("fallback")
.short("f")
.long("fallback")
.value_name("PATH")
.help("Fallback server for missing keys")
.default_value("")
.takes_value(true))
.arg(Arg::with_name("replicas")
.short("r")
.long("replicas")
.value_name("INT")
.help("Amount of replicas to make of the data")
.default_value("3")
.takes_value(true))
.arg(Arg::with_name("subvolumes")
.short("s")
.long("subvolumes")
.value_name("INT")
.help("Amount of subvolumes, disks per machine")
.default_value("10")
.takes_value(true))
.arg(Arg::with_name("volumes")
.short("v")
.long("volumes")
.value_name("PATH")
.help("Volumes to use for storage, comma separated")
.default_value("")
.takes_value(true))
.arg(Arg::with_name("unlink")
.short("u")
.long("unlink")
.default_value("true")
.help("Force UNLINK before DELETE"))
.get_matches();
let command = matches.value_of("command").unwrap();
let volumes: Vec<String> = matches.value_of("volumes").unwrap().split(',').map(|x| x.to_string()).collect();
let fallback = matches.value_of("fallback").unwrap().to_string();
let replicas = matches.value_of("replicas").unwrap().parse::<i32>().expect("could not parse replicas");
let subvolumes = matches.value_of("subvolumes").unwrap().parse::<i32>().expect("could not parse subvolumes");
let protect = matches.value_of("unlink").unwrap_or("false").parse::<bool>().unwrap();
let port = matches.value_of("port").unwrap().parse::<u16>().expect("could not parse port");
if command != "server" && command != "rebalance" && command != "rebuild" {
panic!("{}", matches.usage());
}
if matches.value_of("database").unwrap() == "" {
panic!("Need a path to the database");
}
if volumes.len() < matches.value_of("replicas").unwrap().parse::<usize>().expect("Cannot parse replicas to INT") {
panic!("Need at least as many volumes as replicas");
}
let mut mkv = Minikeyvalue::new(volumes, fallback, replicas, subvolumes, protect, port);
if command == "server" {
mkv.server();
} else if command == "rebalance" {
mkv.rebalance();
} else if command == "rebuild" {
mkv.rebuild();
}
}
| true
|
7c2048d9edc58f5dbbcc6251ab158cf388d68592
|
Rust
|
llogiq/openpgp
|
/src/lib.rs
|
UTF-8
| 25,757
| 3.015625
| 3
|
[] |
no_license
|
//! The goal of this crate is to interact with the OpenPGP-format,
//! i.e. parse it and produce correct PGP files. OpenPGP can describe
//! so many things that parsing is much more pleasant to write in an
//! event-driven way, and the resulting API is also smaller.
//!
//! This version is not yet able to produce encrypted content, but
//! signed messages should work, as demonstrated by the following
//! example, which reads a private key (in the format output by `gpg
//! --export-secret-keys -a`), signs a message and reads it back,
//! verifying the signature.
//!
//! PGP files are split into *packets*, with different meanings.
//!
//! ```
//! use openpgp::*;
//! use openpgp::key::*;
//! struct P {
//! key: Option<Key>,
//! subkey: Option<Key>,
//! data: Vec<u8>,
//! password: &'static [u8],
//! }
//!
//! impl PGP for P {
//!
//! fn get_secret_key<'a>(&'a mut self, _: &[u8]) -> &'a key::SecretKey {
//! self.subkey.as_ref().unwrap().unwrap_secret()
//! }
//!
//! fn get_password(&mut self) -> &[u8] {
//! &self.password
//! }
//!
//! fn public_key(&mut self, _: u32, public_key: key::PublicKey) -> Result<(), Error> {
//! self.key = Some(Key::Public(public_key));
//! Ok(())
//! }
//!
//! fn secret_key(&mut self, _: u32, secret_key: key::SecretKey) -> Result<(), Error> {
//! self.key = Some(Key::Secret(secret_key));
//! Ok(())
//! }
//! fn secret_subkey(&mut self, _: u32, secret_key: key::SecretKey) -> Result<(), Error> {
//! self.subkey = Some(Key::Secret(secret_key));
//! Ok(())
//! }
//! fn get_public_signing_key<'a>(&'a mut self, keyid: &[u8]) -> Option<&'a key::Key> {
//! self.key.as_ref()
//! }
//! fn signature_verified(&mut self, is_ok:bool) -> Result<(), Error> {
//! println!("Verified: {:?}", is_ok);
//! Ok(())
//! }
//! fn get_signed_data(&mut self, _: signature::Type) -> &[u8] {
//! &self.data
//! }
//!
//! }
//! let secret_key = "-----BEGIN PGP PRIVATE KEY BLOCK-----\nVersion: GnuPG v2\n\nlQPGBFeWBdYBCADZtx24u+o/1nN+7L/OzXY8icC72AI93U8TGMg4jEDmuDJkMThu\nWviYQpC4JbJJMBHeZcfzXragSVJKJNZCKsRcZ+lbJqv/EARlfkgIdP0aN0tcPMjp\nmN4sZU8BD2dCmWGG9ZBiZ3dpPfvKPzOiWuMrabsznDDWBSRVWviceiqASjdD6Q58\nGGXie5xwlnh2PbfENtCImn+Kuzn/nNa1iaL+g4TEo4fMMEyuarMU79PI4OSf3x78\nujKY77i2upZ4NYMoPqqEG89CgtuTnQkMGGg8T1HAU+AD00OYZS+DesoUWCf3BuyF\nAcUuuQdi9pZbXYM1SbWLtI1/fQqFTzufmmppABEBAAH+BwMCatGKnKN96hnrz8F/\n02ACLJinv+781dfKfcPFHoQ24zplM9AjIRASpV6PC3CJb+rtKsj8vdeFv253Nhpp\nWWlA/T58ZQjTfuXEg72cvij9HdMU70FF2WDt8ZOUszoTHfbQouf3leFQovTcmwZu\ndNRQMEGn/bcder3+dt5gg3ZC0C2mzpQxlXY9Z3R9RaUuhiimleh7eKfEPTZXlnaO\nLHMQ4yIOHD9ML8CPZtbEPRcx7h9GBjyxea9D55I7czgMC92fvkWbfykNDmbo6RPl\nqBDjgHwJlnJH9JphTExbxblWam/18u7Rjov8geAY0r3EUV0wpFJQMLKbIj9ukj0k\nXsiCnUpXD/IH25fDxya+7SzQAHJ4p70czB62O764BeeVD996XTpnVOPYAG3DE/sm\n9rPRD2cihQwRmvwVviO60BkiWjCmXRtU/gExgKIxyyHmBgEWv6B7dMBVg5VrifHd\n8/V4vYLlXbqIN++S7AabRp9ucBXVopsvH3B38tfvzbcQwELpDHvT3DXVBbikotzl\nshJeAqDGbaZSKSejuVHgWJHNHyxziTcM5fmOgpxm2yuRsvSzK3yuSzUKvjCXvfUi\nsgvrvtyKed2C+Wf47+nXsWkEImi/+S5Gyi0/xFn7L0BbRS32SEpB4tST7o6KbCRi\nBNgCoh1rdeER/D5snDAjKOzX/kq/x/7cV8wuylODXL1yNa6kvhNpXWjEuq0vtsUJ\nbee8zNsH+WEj4vO5gXRWm2IBvWOKUwwN2j+Mu7IO3SBwcraGHQ4SAYo4+JzrAp4n\naoQL8jf8aQucqPnyXSjc0nG9QciF4NjQp58iPCb3umy2rjo+upYJ2ZZASH3RnIx5\nbyri7cdeZUTP6zyixmjui3vn8c1SK7Ie2j/GBphy+rm5MlonNjTemnX62eWubkxH\nxDkmlI1eOAlttCZQaWVycmUtw4l0aWVubmUgTWV1bmllciA8cGVAcGlqdWwub3Jn\nPokBNwQTAQgAIQUCV5YF1gIbAwULCQgHAgYVCAkKCwIEFgIDAQIeAQIXgAAKCRAU\nelLpMLYCImgCB/4mrdC6Wa0nmQqmfP+VZX9Z+zxbceSgbkYSpPW6PEzlprM/pZs0\niOUuAXPRSOnNeGmqPKyT9uU2FnrIVg5MVSB3D27cn0DFSAsteP7CCEAldUeJrhod\nawibqrrbCz00+Sx4u5HxmugcYxn/L6TGkUFuiKocV1DxaUSdVmRqYxrLz0aBqVqT\ng8B7l9y6dJvzMMUBeW4ROtQZbJjznd3gMa77PkhHjaFoMqd0pCBcl7Kv4CC9OGx2\nnvMda9pVERujF1MOwz25CBQLZsS6fEzVRJh+9qj5RtId6VRjZyVYWFqlUkEAZZ8Z\nc/wG75zGj2TnAx40gllJ09tgiyqbWG/0s7ppnQPGBFeWBdYBCADtRNwTUXaTxVts\nvAKLWrlosmcpSDoNci9jqrF/+OYJcHeE89m2ouv8lrvJlRWSX85i2PMYqp3kEa2I\nW5/Eh3i13USoAScCYMoCqeTSfDefX4X24Q3i3JTu2CUxJm5Nacmn7lf0vaNjxYNP\n8mWHujG0CaiEdjW1x+8lx15eoMENfo7eScgEdrQVuLcafOduPZpbrplUtKYYOM8/\n4vvNfxYkPMhL//BiuVXG4r5nQpvc96lS4083N5J14NeKwTduS6J68w92J3SbigTB\nV1RVqZ296CNIJTrGdjPYz/4LQaCa1P0jFeNJHAdPqdBPwO1/PYm4BIpMXGlCdMEm\nJHGvdgyHABEBAAH+BwMC9g9MFatna+jr33gZZ4avfhBpobRc4gNtL/zO6bKVKW1b\nNhBqGnBKVa3IOdD86QduTyNGqiZ8o6GXEWs4U4bvsOfJIiuhaN2EOlOJ7ic/qRU2\nCLo2CkurXmNI8ThH9Y6FldxhqmMLEpZZexo6FsknOd3iTVlW8E8wmjOQTpu7DprJ\nu92vOiFwa6jnsWJREDdqEPnZH/2Ymmz5aoNrS/+AmgIrE+nOH2o8vOTeBSdMg9sj\nCcPdToWSAuYgdDQvrV+7RblqV1HFVPy3kNOoLCB98F3DZrDe5zkoI68EAExyJelO\nKVR6oxXyNStyyB2odOCrUJgNW4SEUrqH3La9MxxVQRkZACKTLQa2lBgskOz0mKDy\nrrX8sQl7p4OwdPLf6s0rTPs6PVw5WZj+F9lnzf4akIRXfnScWZvnqLDzYE/iiPd1\n7x4pr2iQhLMs9ilPmq0QGWHOqlfo/HT3RgQF5P5wf0cJXjtUsE6ZGvSygMl+KAgu\nQZsP+vf96USRyOMQuMULi7EctNrimPko1AxvsSPgSw9FX+cRXaFyBEsSihsGsK2i\nXcMIKGU9D90NFiW7qehgM3Hb/BkwwKeRxAG46DvMtCV06eV3inp82ZtjWU7WWZ1z\nIVO2hprrehPRz6BVz/vDRF8fPnqhGJMKzBWlIwB4LpQIFKZHbYpQ/3SP1MBMe4I/\nwJz6BxdKrXQD6YVVoiq/5L88KXmd3X1Snu+th4oaBdU/bexlBcUtA8Lpw6GoA7Ot\ns5ZQ+ms2ANAyELYYDth12FYIMEKxuf/rJGhuNKoSLWTYrSZae/vGRnG5cSDZKEsC\nuxeVGbb6ug4uyVnDFQ/EHyuKHs4iUMq37KzkiKRUTw8RDPU70tWK27bJ08MROwyt\niOnitjE+sOHU+lxiVq4sQEAIAUQklPa8l+/8WwQkFzczPtk1iQEfBBgBCAAJBQJX\nlgXWAhsMAAoJEBR6UukwtgIiBOEH/Rc9c21Ljpe6OWC1XslV0AVeQWeTc0pZKTR4\nCW1nqSzqin2ajAmfxFXP3Ngtb6z90FzF2unTubwxiiwWvM61oZ3+RLK4L0yd8TmX\n5Zbk+eQ4ucz0XXrsDPC+aPV3aWjAZb8NflIQYlYiRvTEX9ZMgy7DgVBsgJCqTmUG\nihjoTLeKdjYQTFEIsPsePfbvRdDqdtZUXd9JCq+eMr/dLd4oJmCsvFMDPPGfW7rw\n5rPd0/9nwNu0Bst0PAiOliHYmRfSYy9l15wy8FrVIsJGqpEDotzo+sXicZWTtUuA\nIbBVag5seqXE70GhZ+pdSx+dJNE55NOlCzw4Y2yc6HbeVeguIXY=\n=USRz\n-----END PGP PRIVATE KEY BLOCK-----\n";
//!
//! let contents = b"Moi non plus, Bob";
//! let mut p = P {
//! key: None,
//! subkey: None,
//! data: contents.to_vec(),
//! password: b"blabla blibli",
//! };
//!
//! {
//! let mut sk = secret_key.as_bytes();
//! let sk = read_armored(&mut sk);
//! let mut sk = &sk[..];
//! parse(&mut p, &mut sk).unwrap();
//! };
//!
//! let mut s = Vec::new();
//! {
//! let mut buf = Vec::new();
//!
//! let now = std::time::SystemTime::now();
//! let now = now.duration_since(std::time::UNIX_EPOCH).unwrap().as_secs() as u32;
//! if let Some(Key::Secret(ref sk)) = p.key {
//! sk.sign(&mut buf,
//! contents,
//! signature::Type::Binary,
//! &[signature::Subpacket::SignatureCreationTime(now)],
//! &[])
//! .unwrap();
//! packet::write(&mut s, packet::Tag::Signature, &buf).unwrap();
//! }
//! }
//! let mut slice = &s[..];
//! parse(&mut p, &mut slice).unwrap();
//! ```
#[macro_use]
extern crate log;
extern crate byteorder;
extern crate rustc_serialize;
extern crate libc;
#[macro_use]
extern crate bitflags;
extern crate openssl;
extern crate flate2;
use rustc_serialize::base64::FromBase64;
use byteorder::{BigEndian, ReadBytesExt, ByteOrder};
use std::io::{Read, Write, BufRead};
#[cfg(test)]
extern crate rand;
mod error;
pub use error::Error;
mod algorithm;
use algorithm::*;
mod encoding;
use encoding::*;
mod sodium;
pub mod packet;
pub mod signature;
pub mod key;
#[derive(Debug)]
enum SymmetricKey {
AES256([u8; 32]),
}
const PK_SESSION_KEY_VERSION: u8 = 3;
const SYM_INT_DATA_VERSION: u8 = 1;
const ONE_PASS_VERSION: u8 = 3;
struct Parser {
mdc_hash: Option<Vec<u8>>,
one_pass: Vec<OnePass>,
session_key: Option<SymmetricKey>
}
#[allow(dead_code)]
struct OnePass {
sig_type: signature::Type,
hasher: openssl::crypto::hash::Hasher,
pk_algo: PublicKeyAlgorithm,
keyid: [u8; 8],
}
/// This trait is mostly a collection of callbacks called while parsing a series of PGP packets.
pub trait PGP: Sized {
/// Called when the given public key is about to be used for
/// verifying a signature. The default implementation just panics.
#[allow(unused_variables)]
fn get_public_signing_key<'a>(&'a mut self, keyid: &[u8]) -> Option<&'a key::Key> {
unimplemented!()
}
/// Called when the secret key with the given identifier is
/// needed. The default implementation just panics.
#[allow(unused_variables)]
fn get_secret_key<'a>(&'a mut self, keyid: &[u8]) -> &'a key::SecretKey {
unimplemented!()
}
/// Called when a password is required to decrypt a secret/private key.
#[allow(unused_variables)]
fn get_password(&mut self) -> &[u8] {
unimplemented!()
}
/// Should return the data signed by a signature packet.
#[allow(unused_variables)]
fn get_signed_data(&mut self, sigtype: signature::Type) -> &[u8] {
unimplemented!()
}
/// Called on a public key packet.
#[allow(unused_variables)]
fn public_key(&mut self, creation_time: u32, pk: key::PublicKey) -> Result<(), Error> {
debug!("public key: {:?}", creation_time);
Ok(())
}
/// Called on a public subkey packet.
#[allow(unused_variables)]
fn public_subkey(&mut self, creation_time: u32, pk: key::PublicKey) -> Result<(), Error> {
debug!("public subkey: {:?}", creation_time);
Ok(())
}
/// Called on a secret key packet.
#[allow(unused_variables)]
fn secret_key(&mut self, creation_time: u32, pk: key::SecretKey) -> Result<(), Error> {
debug!("secret key: {:?}", creation_time);
Ok(())
}
/// Called on a secret subkey packet.
#[allow(unused_variables)]
fn secret_subkey(&mut self, creation_time: u32, pk: key::SecretKey) -> Result<(), Error> {
debug!("secret subkey: {:?}", creation_time);
Ok(())
}
/// Called on a userid packet, this is normally used to store a user's name and email address.
#[allow(unused_variables)]
fn user_id(&mut self, user_id: &str) -> Result<(), Error> {
debug!("user id: {:?}", user_id);
Ok(())
}
/// Called on a user attribute packet, which is used to store
/// free-form extra information about the user. The only
/// `attribute_type` defined in RFC4880 is `1`, which means it's
/// an image (of unspecified format, good luck!).
#[allow(unused_variables)]
fn user_attribute(&mut self, attribute_type: u8, attr: &[u8]) -> Result<(), Error> {
Ok(())
}
/// Signatures can be used on a wide variety of things, and their
/// meaning is specified by one or more subpackets.
#[allow(unused_variables)]
fn signature_subpacket(&mut self, subpacket: signature::Subpacket) -> Result<(), Error> {
debug!("subpacket: {:?}", subpacket);
Ok(())
}
/// Called when we've read a signature packet and checked the
/// signature. This function is always called after verifying a
/// signature, no matter whether the signature is valid (this is
/// specified by `is_ok`).
#[allow(unused_variables)]
fn signature_verified(&mut self, is_ok:bool) -> Result<(), Error> {
debug!("signature is ok: {:?}", is_ok);
Ok(())
}
/// "Raw" data packet.
#[allow(unused_variables)]
fn literal(&mut self, file_name:&str, date:u32, literal: &[u8]) -> Result<(), Error> {
Ok(())
}
/// Trust packet, mostly free/unspecified -form. I wouldn't rely too much on what's in there.
#[allow(unused_variables)]
fn trust(&mut self, trust: &[u8]) -> Result<(), Error> {
Ok(())
}
}
/// Start the parsing. The default implementation should probably not be overwritten.
pub fn parse<P:PGP, R: Read>(p: &mut P, r: &mut R) -> Result<(), Error> {
let mut parser = Parser {
mdc_hash: None,
one_pass: Vec::new(),
session_key: None
};
let mut buffer = Vec::new();
parse_(p, r, &mut buffer, &mut parser)
}
fn parse_<R: Read, P: PGP>(p: &mut P,
r: &mut R,
packet_body: &mut Vec<u8>,
parser: &mut Parser)
-> Result<(), Error> {
loop {
match packet::read(r, packet_body) {
Ok(packet::Tag::PublicKeyEncryptedSessionKey) => {
parser.session_key = Some(try!(parse_pk_session_key(p, &packet_body)));
}
Ok(packet::Tag::Signature) => {
parser.one_pass.pop(); // This is not actually used by GnuPG.
try!(signature::read(p, &packet_body));
}
Ok(packet::Tag::SymmetricKeyEncryptedSessionKey) => unimplemented!(),
Ok(packet::Tag::OnePassSignature) => {
// This is not actually used by GnuPG.
let mut body = &packet_body[..];
let version = try!(body.read_u8());
assert_eq!(version, ONE_PASS_VERSION);
let sig_type = try!(signature::Type::from_byte(try!(body.read_u8())));
let hash_algo = try!(HashAlgorithm::from_byte(try!(body.read_u8())));
let pk_algo = try!(PublicKeyAlgorithm::from_byte(try!(body.read_u8())));
let (keyid, mut body) = body.split_at(8);
let _ = try!(body.read_u8()) == 0; // is it nested?
let mut kid = [0; 8];
(&mut kid).clone_from_slice(keyid);
use openssl::crypto::hash::*;
let hash_type = match hash_algo {
HashAlgorithm::SHA1 => Type::SHA1,
HashAlgorithm::SHA256 => Type::SHA256,
_ => unimplemented!(),
};
parser.one_pass.push(OnePass {
sig_type: sig_type,
hasher: Hasher::new(hash_type),
pk_algo: pk_algo,
keyid: kid,
});
}
Ok(packet::Tag::SecretKey) => {
let mut slice = &packet_body[..];
let (creation_time, sk) = try!(key::SecretKey::read(&mut slice, p.get_password()));
try!(p.secret_key(creation_time, sk))
}
Ok(packet::Tag::PublicKey) => {
let mut slice = &packet_body[..];
let (creation_time, pk) = try!(key::PublicKey::read(&mut slice));
try!(p.public_key(creation_time, pk))
}
Ok(packet::Tag::SecretSubkey) => {
let mut slice = &packet_body[..];
let (creation_time, sk) = try!(key::SecretKey::read(&mut slice, p.get_password()));
try!(p.secret_subkey(creation_time, sk))
}
Ok(packet::Tag::CompressedData) => {
let mut body = &packet_body[..];
let comp_algo = try!(CompressionAlgorithm::from_byte(try!(body.read_u8())));
match comp_algo {
CompressionAlgorithm::Uncompressed => try!(parse(p, &mut body)),
CompressionAlgorithm::Zip => {
let mut decoder = flate2::read::DeflateDecoder::new(&mut body);
let mut buf = Vec::new();
try!(decoder.read_to_end(&mut buf));
let mut slice = &buf[..];
try!(parse(p, &mut slice))
}
CompressionAlgorithm::Zlib => {
let mut decoder = flate2::read::ZlibDecoder::new(&mut body);
let mut buf = Vec::new();
try!(decoder.read_to_end(&mut buf));
let mut slice = &buf[..];
try!(parse(p, &mut slice))
}
CompressionAlgorithm::Bzip2 => unimplemented!(),
}
}
Ok(packet::Tag::SymmetricallyEncryptedData) => unimplemented!(),
Ok(packet::Tag::Marker) => {
// This is obsolete in RFC4880
unimplemented!()
}
Ok(packet::Tag::LiteralData) => {
let mut lit = &packet_body[..];
let type_ = try!(lit.read_u8());
let file_name = {
let len = try!(lit.read_u8()) as usize;
let (a, b) = lit.split_at(len);
lit = b;
a
};
let date = try!(lit.read_u32::<BigEndian>());
match type_ {
b'b' => {
for onepass in parser.one_pass.iter_mut() {
try!(onepass.hasher.write_all(lit));
}
try!(p.literal(try!(std::str::from_utf8(file_name)), date, lit));
}
_ => unimplemented!(),
}
}
Ok(packet::Tag::Trust) => try!(p.trust(&packet_body)),
Ok(packet::Tag::UserID) => try!(p.user_id(try!(std::str::from_utf8(&packet_body)))),
Ok(packet::Tag::PublicSubkey) => {
let mut slice = &packet_body[..];
let (creation_time, pk) = try!(key::PublicKey::read(&mut slice));
try!(p.public_subkey(creation_time, pk))
}
Ok(packet::Tag::UserAttribute) => {
let mut slice = &packet_body[..];
while !slice.is_empty() {
let p0 = try!(slice.read_u8()) as usize;
let len = try!(read_length(p0, &mut slice));
let (mut a, b) = slice.split_at(len);
slice = b;
let typ = try!(a.read_u8());
try!(p.user_attribute(typ, a))
}
}
Ok(packet::Tag::SymIntData) => {
let mut body = &packet_body[..];
assert_eq!(try!(body.read_u8()), SYM_INT_DATA_VERSION);
// decrypt(t: Type, key: &[u8], iv: &[u8], data: &[u8])
const AES_BLOCK_SIZE: usize = 16;
let data = match parser.session_key {
Some(SymmetricKey::AES256(ref k)) => {
// block size 16;
use openssl::crypto::symm::*;
let iv = [0; AES_BLOCK_SIZE];
decrypt(Type::AES_256_CFB128, k, &iv, body)
},
None => return Err(Error::NoSessionKey)
};
let (a, mut clear) = data.split_at(AES_BLOCK_SIZE + 2);
let (_, a0) = a.split_at(AES_BLOCK_SIZE - 2);
let (a0, a1) = a0.split_at(2);
assert_eq!(a0, a1);
let (clear0, mdc) = clear.split_at(clear.len() - 22);
if mdc[0] == 0xD3 && mdc[1] == 0x14 {
// This packet is not produced by GnuPG, contrarily to RFC4880.
use openssl::crypto::hash::{hash, Type};
parser.mdc_hash = Some(hash(Type::SHA1, clear0));
}
let mut new_body = Vec::new();
try!(parse_(p, &mut clear, &mut new_body, parser))
}
Ok(packet::Tag::ModificationDetectionCode) => {
// Already handled before.
if let Some(ref h) = parser.mdc_hash {
assert_eq!(&packet_body[..], &h[..])
}
}
Err(e) => {
debug!("error {:?}", e);
break;
}
}
}
Ok(())
}
fn parse_pk_session_key<P: PGP>(p: &mut P, mut body: &[u8]) -> Result<SymmetricKey, Error> {
let version = try!(body.read_u8());
assert_eq!(version, PK_SESSION_KEY_VERSION);
let (keyid, b) = body.split_at(8);
body = b;
let algo = try!(PublicKeyAlgorithm::from_byte(try!(body.read_u8())));
match algo {
PublicKeyAlgorithm::RSAEncryptSign => {
match p.get_secret_key(keyid) {
&key::SecretKey::RSAEncryptSign(ref pk) => {
use openssl::crypto::pkey::*;
let mut key = PKey::new();
key.set_rsa(pk);
let mpi = try!(body.read_mpi());
let session_key = key.private_decrypt_with_padding(mpi,
EncryptionPadding::PKCS1v15);
let mut session_key = &session_key[..];
debug!("session key {:?}", session_key);
let algo = try!(session_key.read_u8());
debug!("algo {:?}", algo);
let (key, mut check) = session_key.split_at(session_key.len() - 2);
match try!(SymmetricKeyAlgorithm::from_byte(algo)) {
SymmetricKeyAlgorithm::AES256 => {
let mut k = [0; 32];
k.clone_from_slice(key);
use std::num::Wrapping;
let mut checksum: Wrapping<u16> = Wrapping(0);
for &byte in key {
checksum += Wrapping(byte as u16)
}
assert_eq!(checksum.0, check.read_u16::<BigEndian>().unwrap());
Ok(SymmetricKey::AES256(k))
}
_ => unimplemented!(),
}
}
_ => unimplemented!(),
}
}
_ => unimplemented!(),
}
}
pub fn read_armored<R: BufRead>(r: &mut R) -> Vec<u8> {
let mut buf = String::new();
let mut fin = String::new();
let mut armor_started = false;
let mut contents_started = false;
loop {
buf.clear();
let n = r.read_line(&mut buf).unwrap();
if n == 0 {
break;
}
let tr = buf.trim_right();
if tr.starts_with("-----BEGIN PGP ") && tr.ends_with("-----") {
armor_started = true
} else if tr.starts_with("-----END PGP ") && tr.ends_with("-----") {
break;
} else if armor_started {
if contents_started {
if buf.starts_with("=") {
contents_started = false
} else {
fin = fin + buf.trim_right()
}
} else {
if buf.trim_right() == "" {
contents_started = true
}
}
}
}
fin.from_base64().unwrap()
}
#[cfg(test)]
mod tests {
extern crate env_logger;
use super::*;
use std;
use key::*;
const SECRET_KEY: &'static str = include_str!("secret_key.asc");
const PUBLIC_KEY:&'static str = include_str!("public_key.asc");
struct P {
key: Option<Key>,
subkey: Option<Key>,
data: Vec<u8>,
password: &'static [u8],
}
impl PGP for P {
fn get_secret_key<'a>(&'a mut self, _: &[u8]) -> &'a key::SecretKey {
if let Some(Key::Secret(ref key)) = self.subkey {
key
} else {
panic!("no key")
}
}
fn get_signed_data(&mut self, sigtype: signature::Type) -> &[u8] {
&self.data
}
fn get_public_signing_key<'a>(&'a mut self, keyid: &[u8]) -> Option<&'a key::Key> {
self.key.as_ref()
}
fn get_password(&mut self) -> &[u8] {
&self.password
}
fn public_key(&mut self, _: u32, public_key: key::PublicKey) -> Result<(), Error> {
self.key = Some(Key::Public(public_key));
Ok(())
}
fn secret_key(&mut self, _: u32, secret_key: key::SecretKey) -> Result<(), Error> {
self.key = Some(Key::Secret(secret_key));
Ok(())
}
fn secret_subkey(&mut self, _: u32, secret_key: key::SecretKey) -> Result<(), Error> {
self.subkey = Some(Key::Secret(secret_key));
Ok(())
}
fn literal(&mut self, file_name:&str, date:u32, literal: &[u8]) -> Result<(), Error> {
println!("literal: {:?} {:?}", file_name, date);
self.data.clear();
self.data.extend(literal);
Ok(())
}
fn signature_verified(&mut self, is_ok:bool) -> Result<(), Error> {
println!("Verified: {:?}", is_ok);
Ok(())
}
}
#[test]
fn verify() {
let _ = env_logger::init();
let contents = b"Test";
let signature = include_str!("signature.asc");
let base = {
let mut pubkey = PUBLIC_KEY.as_bytes();
super::read_armored(&mut pubkey)
};
let mut slice = &base[..];
let mut p = P {
key: None,
subkey: None,
data: contents.to_vec(),
password: b"",
};
parse(&mut p, &mut slice).unwrap();
let s = {
let mut signature = signature.as_bytes();
super::read_armored(&mut signature)
};
let mut slice = &s[..];
parse(&mut p, &mut slice).unwrap();
}
#[test]
fn sign_verify() {
let _ = env_logger::init();
let contents = b"This is a test file";
let mut p = P {
key: None,
subkey: None,
data: contents.to_vec(),
password: b"blabla blibli",
};
{
// reading secret key.
let mut sk = SECRET_KEY.as_bytes();
let sk = super::read_armored(&mut sk);
let mut sk = &sk[..];
parse(&mut p, &mut sk).unwrap();
};
let mut s = Vec::new();
{
let mut buf = Vec::new();
let now = std::time::SystemTime::now();
let now = now.duration_since(std::time::UNIX_EPOCH).unwrap().as_secs() as u32;
if let Some(Key::Secret(ref sk)) = p.key {
sk.sign(&mut buf,
contents,
signature::Type::Binary,
&[signature::Subpacket::SignatureCreationTime(now)],
&[])
.unwrap();
packet::write(&mut s, packet::Tag::Signature, &buf).unwrap();
}
}
let mut slice = &s[..];
parse(&mut p, &mut slice).unwrap();
}
#[test]
fn keyring_open() {
let _ = env_logger::init();
let mut p = P {
key: None,
subkey: None,
data: b"".to_vec(),
password: b"blabla blibli",
};
{
// reading secret key.
let mut sk = SECRET_KEY.as_bytes();
let sk = super::read_armored(&mut sk);
let mut sk = &sk[..];
parse(&mut p, &mut sk).unwrap();
}
assert!(p.key.is_some())
}
#[test]
fn keyring_open_save() {
let _ = env_logger::init();
let mut p = P {
key: None,
subkey: None,
data: b"".to_vec(),
password: b"blabla blibli",
};
{
// reading secret key.
let mut sk = SECRET_KEY.as_bytes();
let sk = super::read_armored(&mut sk);
let mut sk = &sk[..];
parse(&mut p, &mut sk).unwrap();
}
if let Some(Key::Secret(ref sk)) = p.key {
let mut v = Vec::new();
let new_password = b"new_password";
let now = std::time::SystemTime::now();
let now = now.duration_since(std::time::UNIX_EPOCH).unwrap().as_secs() as u32;
sk.write(&mut v,
now,
super::algorithm::SymmetricKeyAlgorithm::AES128,
new_password)
.unwrap();
let mut v = &v[..];
key::SecretKey::read(&mut v, new_password).unwrap();
}
}
#[test]
fn email_pgp_message() {
let email = include_str!("email.asc");
let email = {
let mut email = email.as_bytes();
super::read_armored(&mut email)
};
let mut email = &email[..];
let mut p = P {
key: None,
subkey: None,
data: b"".to_vec(),
password: b"blabla blibli",
};
{
// reading secret key.
let mut sk = SECRET_KEY.as_bytes();
let sk = super::read_armored(&mut sk);
let mut sk = &sk[..];
parse(&mut p, &mut sk).unwrap();
}
parse(&mut p, &mut email).unwrap();
}
// This fails, because it's a DSA key, which is not included in OpenSSL.
// #[test]
// fn rustup_pgp_key() {
// let key = "-----BEGIN PGP PUBLIC KEY BLOCK-----
// Version: GnuPG v1
//
// mQGiBFSvfs0RBACq3IMYK0JuSu764zrWfAh4hu1wnb8XMlXxj23drkGqSMHAW1fj
// VoA4etCwhumoqyhYtRkr4Rnae+le2FcYy8MUpSE+zQbX5X37saO0ppDXbKh0PLzw
// /0qQ6YhKllJX9T/cSH4LSw0JGFyHs5Nj+4sVsGexhn8mkuqkM6wBk6RGTwCgiYJB
// nWtKygKH1koIsSIQ5mxhQWMD/imRz4zH/tUDMF7PepRehOtbIIYI+B7m80Xz5gfU
// HwMiXRgWBRClbPbUDzEwb6sEfBn104tRgHtHetBFRV9niAuwqycJSd1b/Em4PanZ
// TO8dZzglD0VxKJDnlxKWb4YAs6082p6zWgCf4EK2EI6jc6KExy3rY7SJgWBibxPb
// nLBBA/9xKWCs7OxOtDdojh2nI7ZH0O5x+ycPohrLZ2S9pd9kg4QgaeXqDyKbp00h
// slIz768WgAPwluE+sLq2H9967kjKII2D3giiKp/HvV6ew7mZpNOARYxZVJW948kw
// Tj4H+WCycbRwp6dj52fD+r+TrJnWF/wcdj1s9hNKeohi8peQY7QSbXVsdGlydXN0
// IHRlc3Qga2V5iGIEExECACIFAlSvfs0CGwMGCwkIBwMCBhUIAgkKCwQWAgMBAh4B
// AheAAAoJENsvtiW3Dh9iKtcAnAkhTbaaid6u9a1ctSIr0s0FsxDaAJ4y8IBNvFAj
// BZVWgYLtCDPB3nYkeA==
// =zJHN
// -----END PGP PUBLIC KEY BLOCK-----
// ";
//
// let base = {
// let mut pubkey = key.as_bytes();
// super::read_armored(&mut pubkey)
// };
// let mut slice = &base[..];
// let pubkey = {
// read_pubkey(&mut slice).unwrap()
// };
// }
//
}
| true
|
bf121fc422bcf809d9a81b8b03a7d4b57d4d4eb8
|
Rust
|
donaldducky/advent-of-code
|
/2019/day9/src/main.rs
|
UTF-8
| 596
| 2.859375
| 3
|
[] |
no_license
|
use std::sync::mpsc;
use std::thread;
use intcode;
fn main() {
let program = intcode::read_program("input.txt");
println!("Part 1: {}", boost_keycode(program.clone(), 1));
println!("Part 2: {}", boost_keycode(program.clone(), 2));
}
fn boost_keycode(program: Vec<i128>, input: i128) -> i128 {
let mut cpu = intcode::CPU::new("day9".to_string(), program.clone());
let (tx, rx) = mpsc::channel();
let tx0 = mpsc::Sender::clone(&tx);
let handle = thread::spawn(move || {
cpu.run(&tx0, &rx)
});
tx.send(input).unwrap();
handle.join().unwrap()
}
| true
|
edea352e282c4ab7533674d291778e8bc3a4b0f1
|
Rust
|
hexgolems/td
|
/src/background.rs
|
UTF-8
| 2,868
| 2.796875
| 3
|
[] |
no_license
|
use crate::algebra::{Point, Vector};
use crate::assets::{Data, ImgID};
use crate::playing_state::PlayingState;
use ggez::graphics;
use ggez::graphics::Color;
use ggez::{Context, GameResult};
use rand::prelude::*;
use rand::thread_rng;
pub struct Wave {
pos: Point,
disp: ImgID,
time: f32,
}
impl Wave {
pub fn new() -> Self {
let wave_id = 1 + thread_rng().gen::<usize>() % 4;
let disp = ImgID::BackgroundWave(wave_id);
let pos = Point::new(
thread_rng().gen::<f32>() * 800.0,
thread_rng().gen::<f32>() * 800.0,
);
return Self {
disp,
pos,
time: thread_rng().gen::<f32>() * 16.0,
};
}
pub fn tick(&mut self) {
self.pos.x += 0.5;
self.pos.y += 0.05;
self.time += 0.01;
if self.pos.x > 800.0 {
self.pos.x = -10.0;
}
if self.pos.y > 600.0 {
self.pos.y = -10.0;
}
}
pub fn draw(&self, data: &Data, ctx: &mut Context) -> GameResult<()> {
graphics::draw(
ctx,
data.get_i(&self.disp),
graphics::DrawParam::default()
.dest(self.pos)
.scale(Vector::new(4.0, 4.0))
.color(Color::new(1.0, 1.0, 1.0, (self.time.sin() + 1.0) / 2.0)),
)?;
return Ok(());
}
}
pub struct Background {
pub offset: Point,
pub waves: Vec<Wave>,
}
impl Background {
pub fn new() -> Self {
let mut waves = vec![];
for _ in 0..20 {
waves.push(Wave::new());
}
Self {
waves,
offset: Point::new(0.0, 0.0),
}
}
pub fn tick(&mut self) {
for w in self.waves.iter_mut() {
w.tick();
}
self.offset += Vector::new(0.0002, 0.0002);
if self.offset.x > 1.0 {
self.offset.x -= 1.0;
}
if self.offset.y > 1.0 {
self.offset.y -= 1.0;
}
}
pub fn draw(state: &PlayingState, data: &Data, ctx: &mut Context) -> GameResult<()> {
for x in -1..5 {
for y in -1..5 {
graphics::draw(
ctx,
data.get_i(&ImgID::BackgroundWater),
graphics::DrawParam::default()
.dest(
state.gui.cam().ground_pos(Point::new(
4.0 * 80.0 * x as f32,
4.0 * 80.0 * y as f32,
)),
)
.offset(state.background.offset)
.scale(Vector::new(4.0, 4.0)),
)?;
}
}
for w in state.background.waves.iter() {
w.draw(data, ctx)?;
}
return Ok(());
}
}
| true
|
879deeaf0a3174dcfcd8b5a8193d06d7161fe53f
|
Rust
|
gontard/rchess
|
/crate-wasm/src/utils.rs
|
UTF-8
| 1,140
| 3.109375
| 3
|
[] |
no_license
|
use chess::{ChessMove, Square};
pub fn set_panic_hook() {
// When the `console_error_panic_hook` feature is enabled, we can call the
// `set_panic_hook` function at least once during initialization, and then
// we will get better error messages if our code ever panics.
//
// For more details see
// https://github.com/rustwasm/console_error_panic_hook#readme
#[cfg(feature = "console_error_panic_hook")]
console_error_panic_hook::set_once();
}
pub fn read_chess_move(move_as_str: &str) -> ChessMove {
let parts: Vec<_> = move_as_str.split("-").collect();
ChessMove::new(
Square::from_string(parts[0].to_string()).unwrap(),
Square::from_string(parts[1].to_string()).unwrap(),
None,
)
}
#[cfg(test)]
mod tests {
use chess::{ChessMove, Square};
use super::read_chess_move;
#[test]
fn read_chess_move_success() {
assert_eq!(
ChessMove::new(Square::A1, Square::E7, None),
read_chess_move("a1-e7")
);
}
#[test]
#[should_panic]
fn read_chess_move_failure() {
read_chess_move("a1e7");
}
}
| true
|
32259e0b98bf38aa813e47e0a5e9b8e3ec7ca1ee
|
Rust
|
ocstl/project_euler
|
/src/bin/problem46.rs
|
UTF-8
| 440
| 3.203125
| 3
|
[] |
no_license
|
use primal::is_prime;
/// What is the smallest odd composite that cannot be written as the sum of a prime and twice a
/// square?
fn main() {
let answer = (5u64..)
.step_by(2)
.find(|&n| {
!is_prime(n)
&& (1..)
.take_while(|&x| 2 * (x * x) < n)
.all(|x| !is_prime(n - 2 * (x * x)))
})
.unwrap();
println!("Answer: {}", answer);
}
| true
|
a9cd2a089747223a3afc4b3a11b9a13d9b098e93
|
Rust
|
DjDeveloperr/dapi-rs
|
/v8-format/src/ser.rs
|
UTF-8
| 27,278
| 2.8125
| 3
|
[
"Apache-2.0"
] |
permissive
|
#![allow(dead_code)]
#![allow(unused_variables)]
use crate::common::Error;
use serde::ser;
use serde::Serialize;
use std::collections::HashMap;
use std::collections::HashSet;
use integer_encoding::VarInt;
use crate::common::ArrayBufferViewType;
use crate::common::ErrorType;
use crate::common::Value;
pub const FORMAT_VERSION: u8 = 0xD0;
pub fn to_vec<T: Serialize>(value: T) -> Result<Vec<u8>, Error> {
let mut serializer = Serializer {
data: vec![0xFF, FORMAT_VERSION],
start_pos: 0,
current_len: None,
lazy_len: 0,
};
value.serialize(&mut serializer)?;
Ok(serializer.data)
}
pub struct Serializer {
data: Vec<u8>,
start_pos: usize,
current_len: Option<usize>,
lazy_len: usize,
}
// Old impl, non-serde one.
impl Serializer {
fn write_undefined(&mut self) {
self.data.push('_' as u8)
}
fn write_null(&mut self) {
self.data.push('0' as u8)
}
fn write_boolean(&mut self, value: bool) {
match value {
true => self.data.push('T' as u8),
false => self.data.push('F' as u8),
}
}
fn write_int32(&mut self, value: i32) {
self.data.push('I' as u8);
self.data.extend(value.encode_var_vec());
}
fn write_uint32(&mut self, value: u32) {
self.data.push('U' as u8);
self.data.extend(value.encode_var_vec());
}
fn write_double(&mut self, value: f64) {
self.data.push('N' as u8);
self.data.extend(value.to_ne_bytes());
}
// todo: support i128 too
fn write_bigint(&mut self, value: i64) {
self.data.push('Z' as u8);
let mut flags = 0u32;
if value < 0 {
flags |= 1 << 0; // signed
}
flags |= 8 * 2; // bits
self.data.extend(flags.encode_var_vec());
self.data.extend((value as u64).to_le_bytes()); // is this right
}
fn write_string(&mut self, value: String, utf16: bool) {
self.data.push(if utf16 { 'c' } else { '"' } as u8);
self.data.extend(value.len().encode_var_vec());
self.data.extend(value.as_bytes());
}
fn write_object_reference(&mut self, id: u32) {
self.data.push('^' as u8);
self.data.extend(id.encode_var_vec());
}
fn write_object(&mut self, value: HashMap<String, Value>) {
self.data.push('o' as u8);
let size = value.len();
for (k, v) in value {
self.write_string(k, false);
self.write_value(v);
}
self.data.push('{' as u8);
self.data.extend((size as u32).encode_var_vec());
}
fn write_array(&mut self, value: Vec<Value>) {
self.data.push('A' as u8);
let len = value.len();
let enc = len.encode_var_vec();
self.data.extend(&enc);
for val in value {
self.write_value(val);
}
self.data.push(36);
self.data.push(0);
self.data.extend(enc);
}
fn write_date(&mut self, value: f64) {
self.data.push('D' as u8);
self.data.extend(value.to_ne_bytes()); // ne or le?
}
fn write_number_object(&mut self, value: f64) {
self.data.push('n' as u8);
self.data.extend(value.to_ne_bytes()); // ne or le?
}
fn write_bigint_object(&mut self) {
self.data.push('z' as u8); // todo
}
fn write_string_object(&mut self, value: String) {
self.data.push('s' as u8);
self.data.extend((value.len() as u32).encode_var_vec());
self.data.extend(value.as_bytes());
}
fn write_regexp(&mut self, expr: String, flags: u32) {
self.data.push('R' as u8);
self.data.extend((expr.len() as u32).encode_var_vec());
self.data.extend(expr.as_bytes());
self.data.extend(flags.encode_var_vec());
}
fn write_map(&mut self, value: HashMap<Value, Value>) {
self.data.push(';' as u8);
let size = value.len();
for (k, v) in value {
self.write_value(k);
self.write_value(v);
}
self.data.push(':' as u8);
self.data.extend((size as u32).encode_var_vec());
}
fn write_set(&mut self, value: HashSet<Value>) {
self.data.push('\'' as u8);
let size = value.len();
for v in value {
self.write_value(v);
}
self.data.push(',' as u8);
self.data.extend((size as u32).encode_var_vec());
}
fn write_array_buffer(&mut self, value: Vec<u8>) {
self.data.push('B' as u8);
self.data.extend((value.len() as u32).encode_var_vec());
self.data.extend(value);
}
fn write_array_buffer_transfer(&mut self, transfer_id: u32) {
self.data.push('t' as u8);
self.data.extend(transfer_id.encode_var_vec());
}
fn write_array_buffer_view(
&mut self,
ty: ArrayBufferViewType,
byte_offset: u32,
byte_length: u32,
buffer: Vec<u8>,
) {
self.write_array_buffer(buffer);
self.data.push('V' as u8);
self.data.push(match ty {
ArrayBufferViewType::Int8Array => 'b',
ArrayBufferViewType::Uint8Array => 'B',
ArrayBufferViewType::Uint8ClampedArray => 'C',
ArrayBufferViewType::Int16Array => 'w',
ArrayBufferViewType::Uint16Array => 'W',
ArrayBufferViewType::Int32Array => 'd',
ArrayBufferViewType::Uint32Array => 'D',
ArrayBufferViewType::Float32Array => 'f',
ArrayBufferViewType::Float64Array => 'F',
ArrayBufferViewType::BigInt64Array => 'q',
ArrayBufferViewType::BigUint64Array => 'Q',
ArrayBufferViewType::DataView => '?',
} as u8);
self.data.extend(byte_offset.encode_var_vec());
self.data.extend(byte_length.encode_var_vec());
}
fn write_shared_array_buffer(&mut self, transfer_id: u32) {
self.data.push('u' as u8);
self.data.extend(transfer_id.encode_var_vec());
}
fn write_error(&mut self, ty: ErrorType, message: Option<String>, stack: Option<String>) {
self.data.push('r' as u8);
if let Some(ch) = match ty {
ErrorType::EvalError => Some('E'),
ErrorType::RangeError => Some('R'),
ErrorType::ReferenceError => Some('F'),
ErrorType::SyntaxError => Some('C'),
ErrorType::TypeError => Some('T'),
ErrorType::UriError => Some('U'),
ErrorType::Unknown => None,
} {
self.data.push(ch as u8);
}
if let Some(message) = message {
self.data.push('m' as u8);
self.write_string(message, false);
}
if let Some(stack) = stack {
self.data.push('s' as u8);
self.write_string(stack, false);
}
self.data.push('.' as u8);
}
fn write_value(&mut self, value: Value) {
match value {
Value::Undefined => self.write_undefined(),
Value::Null => self.write_null(),
Value::Boolean(value) => self.write_boolean(value),
Value::Int32(value) => self.write_int32(value),
Value::Uint32(value) => self.write_uint32(value),
Value::Double(value) => self.write_double(value),
Value::BigInt(value) => self.write_bigint(value),
Value::String(value, utf16) => self.write_string(value, utf16),
Value::ObjectReference { id } => self.write_object_reference(id),
Value::Object(value) => self.write_object(value),
Value::Array(value) => self.write_array(value),
Value::Date(value) => self.write_date(value),
Value::NumberObject(value) => self.write_number_object(value),
Value::BigIntObject() => self.write_bigint_object(),
Value::StringObject(value) => self.write_string_object(value),
Value::RegExp { expr, flags } => self.write_regexp(expr, flags),
Value::Map(value) => self.write_map(value),
Value::Set(value) => self.write_set(value),
Value::ArrayBuffer(value) => self.write_array_buffer(value),
Value::ArrayBufferTransfer { transfer_id } => {
self.write_array_buffer_transfer(transfer_id)
}
Value::ArrayBufferView {
ty,
byte_offset,
byte_length,
buffer,
} => self.write_array_buffer_view(ty, byte_offset, byte_length, buffer),
Value::SharedArrayBuffer { transfer_id } => self.write_shared_array_buffer(transfer_id),
Value::Error { ty, message, stack } => self.write_error(ty, message, stack),
}
}
fn serialize(mut self, value: Value) -> Vec<u8> {
self.write_value(value);
self.data
}
}
impl<'a> ser::Serializer for &'a mut Serializer {
type Ok = ();
type Error = Error;
type SerializeSeq = Self;
type SerializeTuple = Self;
type SerializeTupleStruct = Self;
type SerializeTupleVariant = Self;
type SerializeMap = Self;
type SerializeStruct = Self;
type SerializeStructVariant = Self;
fn serialize_bool(self, v: bool) -> Result<Self::Ok, Self::Error> {
match v {
true => self.data.push('T' as u8),
false => self.data.push('F' as u8),
}
Ok(())
}
fn serialize_i8(self, v: i8) -> Result<Self::Ok, Self::Error> {
self.data.push('I' as u8);
self.data.extend(v.encode_var_vec());
Ok(())
}
fn serialize_i16(self, v: i16) -> Result<Self::Ok, Self::Error> {
self.data.push('I' as u8);
self.data.extend(v.encode_var_vec());
Ok(())
}
fn serialize_i32(self, v: i32) -> Result<Self::Ok, Self::Error> {
self.data.push('I' as u8);
self.data.extend(v.encode_var_vec());
Ok(())
}
fn serialize_i64(self, v: i64) -> Result<Self::Ok, Self::Error> {
self.data.push('Z' as u8);
let mut flags = 0u32;
flags |= 1 << 0; // signed
flags |= 8 * 2; // bits
self.data.extend(flags.encode_var_vec());
self.data.extend((v as u64).to_le_bytes());
Ok(())
}
fn serialize_u8(self, v: u8) -> Result<Self::Ok, Self::Error> {
self.data.push('U' as u8);
self.data.extend(v.encode_var_vec());
Ok(())
}
fn serialize_u16(self, v: u16) -> Result<Self::Ok, Self::Error> {
self.data.push('U' as u8);
self.data.extend(v.encode_var_vec());
Ok(())
}
fn serialize_u32(self, v: u32) -> Result<Self::Ok, Self::Error> {
self.data.push('U' as u8);
self.data.extend(v.encode_var_vec());
Ok(())
}
fn serialize_u64(self, v: u64) -> Result<Self::Ok, Self::Error> {
self.data.push('Z' as u8);
let mut flags = 0u32;
flags |= 8 * 2; // bits
self.data.extend(flags.encode_var_vec());
self.data.extend(v.to_le_bytes());
Ok(())
}
fn serialize_f32(self, v: f32) -> Result<Self::Ok, Self::Error> {
self.data.push('N' as u8);
self.data.extend((v as f64).to_ne_bytes());
Ok(())
}
fn serialize_f64(self, v: f64) -> Result<Self::Ok, Self::Error> {
self.data.push('N' as u8);
self.data.extend(v.to_ne_bytes());
Ok(())
}
fn serialize_char(self, v: char) -> Result<Self::Ok, Self::Error> {
self.data.push('"' as u8);
self.data.push(1);
self.data.push(v as u8);
Ok(())
}
fn serialize_str(self, v: &str) -> Result<Self::Ok, Self::Error> {
self.data.push('"' as u8);
self.data.extend(v.len().encode_var_vec());
self.data.extend(v.as_bytes());
Ok(())
}
fn serialize_bytes(self, v: &[u8]) -> Result<Self::Ok, Self::Error> {
self.data.push('B' as u8);
if v.len() > u32::MAX as usize {
return Err(Error::Message(String::from(
"Bytes cannot be larger than u32::MAX",
)));
}
self.data.extend((v.len() as u32).encode_var_vec());
self.data.extend(v);
Ok(())
}
fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
self.data.push('_' as u8);
Ok(())
}
fn serialize_some<T: ?Sized>(self, value: &T) -> Result<Self::Ok, Self::Error>
where
T: serde::Serialize,
{
value.serialize(self)
}
fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
self.serialize_none()
}
fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok, Self::Error> {
// empty object
self.data.push('o' as u8);
self.data.push('{' as u8);
self.data.push(0);
Ok(())
}
fn serialize_unit_variant(
self,
_name: &'static str,
_variant_index: u32,
variant: &'static str,
) -> Result<Self::Ok, Self::Error> {
self.data.push('o' as u8);
self.serialize_str(variant)?;
self.serialize_none()?;
self.data.push('{' as u8);
self.data.push(1);
Ok(())
}
fn serialize_newtype_struct<T: ?Sized>(
self,
_name: &'static str,
value: &T,
) -> Result<Self::Ok, Self::Error>
where
T: serde::Serialize,
{
value.serialize(self)
}
fn serialize_newtype_variant<T: ?Sized>(
self,
_name: &'static str,
_variant_index: u32,
variant: &'static str,
value: &T,
) -> Result<Self::Ok, Self::Error>
where
T: serde::Serialize,
{
self.data.push('o' as u8);
self.serialize_str(variant)?;
value.serialize(&mut *self)?;
self.data.push('{' as u8);
self.data.push(1);
Ok(())
}
fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
self.data.push('A' as u8);
self.current_len = len;
self.lazy_len = 0;
if let Some(len) = len {
self.data.extend((len as u32).encode_var_vec());
} else {
self.start_pos = self.data.len();
}
Ok(self)
}
fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Self::Error> {
self.data.push('A' as u8);
self.data.extend((len as u32).encode_var_vec());
self.current_len = Some(len);
Ok(self)
}
fn serialize_tuple_struct(
self,
name: &'static str,
len: usize,
) -> Result<Self::SerializeTupleStruct, Self::Error> {
self.data.push('A' as u8);
self.data.extend((len as u32).encode_var_vec());
self.current_len = Some(len);
Ok(self)
}
fn serialize_tuple_variant(
self,
_name: &'static str,
_variant_index: u32,
variant: &'static str,
len: usize,
) -> Result<Self::SerializeTupleVariant, Self::Error> {
self.data.push('o' as u8);
self.serialize_str(variant)?;
self.data.push('A' as u8);
self.data.extend((len as u32).encode_var_vec());
self.current_len = Some(len);
Ok(self)
}
fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
self.data.push(';' as u8);
self.current_len = len;
self.lazy_len = 0;
Ok(self)
}
fn serialize_struct(
self,
name: &'static str,
len: usize,
) -> Result<Self::SerializeStruct, Self::Error> {
self.data.push('o' as u8);
self.current_len = Some(len);
self.lazy_len = 0;
Ok(self)
}
fn serialize_struct_variant(
self,
_name: &'static str,
_variant_index: u32,
variant: &'static str,
len: usize,
) -> Result<Self::SerializeStructVariant, Self::Error> {
self.data.push('o' as u8);
self.serialize_str(variant)?;
self.data.push('o' as u8);
self.current_len = Some(len);
self.lazy_len = 0;
Ok(self)
}
}
impl<'a> ser::SerializeSeq for &'a mut Serializer {
type Ok = ();
type Error = Error;
fn serialize_element<T>(&mut self, value: &T) -> Result<(), Error>
where
T: ?Sized + Serialize,
{
if self.current_len.is_none() {
self.lazy_len += 1;
}
value.serialize(&mut **self)
}
fn end(self) -> Result<(), Error> {
// It was a lazy one, so insert len at start_pos
if self.current_len.is_none() {
let mut pos = self.start_pos;
for byte in (self.lazy_len as u32).encode_var_vec() {
self.data.insert(pos, byte);
pos += 1;
}
}
self.data.push('$' as u8);
self.data.push(0);
self.data
.extend((self.current_len.unwrap_or(self.lazy_len) as u32).encode_var_vec());
Ok(())
}
}
impl<'a> ser::SerializeTuple for &'a mut Serializer {
type Ok = ();
type Error = Error;
fn serialize_element<T>(&mut self, value: &T) -> Result<(), Error>
where
T: ?Sized + Serialize,
{
value.serialize(&mut **self)
}
fn end(self) -> Result<(), Error> {
self.data.push('$' as u8);
self.data.push(0);
self.data
.extend((self.current_len.unwrap() as u32).encode_var_vec());
Ok(())
}
}
impl<'a> ser::SerializeTupleStruct for &'a mut Serializer {
type Ok = ();
type Error = Error;
fn serialize_field<T>(&mut self, value: &T) -> Result<(), Error>
where
T: ?Sized + Serialize,
{
value.serialize(&mut **self)
}
fn end(self) -> Result<(), Error> {
self.data.push('$' as u8);
self.data.push(0);
self.data
.extend((self.current_len.unwrap() as u32).encode_var_vec());
Ok(())
}
}
impl<'a> ser::SerializeTupleVariant for &'a mut Serializer {
type Ok = ();
type Error = Error;
fn serialize_field<T>(&mut self, value: &T) -> Result<(), Error>
where
T: ?Sized + Serialize,
{
value.serialize(&mut **self)
}
fn end(self) -> Result<(), Error> {
// End the tuple
self.data.push('$' as u8);
self.data.push(0);
self.data
.extend((self.current_len.unwrap() as u32).encode_var_vec());
// End the enum variant object
self.data.push('{' as u8);
self.data.push(1);
Ok(())
}
}
impl<'a> ser::SerializeMap for &'a mut Serializer {
type Ok = ();
type Error = Error;
fn serialize_key<T>(&mut self, key: &T) -> Result<(), Error>
where
T: ?Sized + Serialize,
{
key.serialize(&mut **self)
}
fn serialize_value<T>(&mut self, value: &T) -> Result<(), Error>
where
T: ?Sized + Serialize,
{
if self.current_len.is_none() {
self.lazy_len += 1;
}
value.serialize(&mut **self)
}
fn end(self) -> Result<(), Error> {
self.data.push(':' as u8);
// Actually * 2 length is used here because its two values per entry.
self.data
.extend(((self.current_len.unwrap_or(self.lazy_len) * 2) as u32).encode_var_vec());
Ok(())
}
}
impl<'a> ser::SerializeStruct for &'a mut Serializer {
type Ok = ();
type Error = Error;
fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), Error>
where
T: ?Sized + Serialize,
{
use serde::Serializer;
self.serialize_str(key)?;
value.serialize(&mut **self)
}
fn end(self) -> Result<(), Error> {
self.data.push('{' as u8);
self.data
.extend((self.current_len.unwrap() as u32).encode_var_vec());
Ok(())
}
}
impl<'a> ser::SerializeStructVariant for &'a mut Serializer {
type Ok = ();
type Error = Error;
fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), Error>
where
T: ?Sized + Serialize,
{
use serde::Serializer;
self.serialize_str(key)?;
value.serialize(&mut **self)
}
fn end(self) -> Result<(), Error> {
// End inner object (variant's value)
self.data.push('{' as u8);
self.data
.extend((self.current_len.unwrap() as u32).encode_var_vec());
// End outer object (variant)
self.data.push('{' as u8);
self.data.push(1);
Ok(())
}
}
pub trait SerializeDateExt {
type Ok;
type Error: std::error::Error;
fn serialize_date<T: ?Sized>(&mut self, date: std::time::Instant) -> Result<(), Self::Error>
where
T: Serialize;
}
impl<'a> SerializeDateExt for &'a mut Serializer {
type Ok = ();
type Error = Error;
fn serialize_date<T: ?Sized>(&mut self, date: std::time::Instant) -> Result<(), Self::Error>
where
T: Serialize,
{
self.data.push('D' as u8);
self.data
.extend((date.elapsed().as_millis() as f64).to_ne_bytes());
Ok(())
}
}
#[test]
fn test_boolean() {
assert_eq!(to_vec(true).unwrap(), vec![0xFF, FORMAT_VERSION, 84]);
assert_eq!(to_vec(false).unwrap(), vec![0xFF, FORMAT_VERSION, 70]);
}
#[test]
fn test_numbers() {
// Upto 32 bit numbers, encoding is same.
assert_eq!(to_vec(1u32).unwrap(), vec![0xFF, FORMAT_VERSION, 85, 1]);
assert_eq!(to_vec(1i32).unwrap(), vec![0xFF, FORMAT_VERSION, 73, 2]);
// For 64 bit (and above), it's different
assert_eq!(
to_vec(1u64).unwrap(),
vec![0xFF, FORMAT_VERSION, 90, 16, 1, 0, 0, 0, 0, 0, 0, 0]
);
assert_eq!(
to_vec(1i64).unwrap(),
vec![0xFF, FORMAT_VERSION, 90, 17, 1, 0, 0, 0, 0, 0, 0, 0]
);
// For floats too it is different encoding, but it's at least same for both f32 and f64.
// But there's a quirk with this format: it uses native endianness
// making this format non-portable. So we need a cfg directive here.
#[cfg(target_endian = "little")]
let expected = vec![0xFF, FORMAT_VERSION, 78, 31, 133, 235, 81, 184, 30, 9, 64];
#[cfg(target_endian = "big")]
let expected = vec![0xFF, FORMAT_VERSION, 78, 64, 9, 30, 184, 81, 235, 133, 31];
assert_eq!(to_vec(3.14f64).unwrap(), expected);
}
#[test]
fn test_char() {
assert_eq!(to_vec('h').unwrap(), vec![0xFF, FORMAT_VERSION, 34, 1, 104]);
}
#[test]
fn test_str() {
assert_eq!(
to_vec("test").unwrap(),
vec![0xFF, FORMAT_VERSION, 34, 4, 116, 101, 115, 116]
);
}
#[test]
fn test_bytes() {
use serde_bytes::Bytes;
let bytes: [u8; 3] = [1, 2, 3];
assert_eq!(
to_vec(Bytes::new(&bytes)).unwrap(),
vec![0xFF, FORMAT_VERSION, 66, 3, 1, 2, 3]
);
}
#[test]
fn test_undefined() {
assert_eq!(
to_vec(None as Option<()>).unwrap(),
vec![0xFF, FORMAT_VERSION, 95]
);
assert_eq!(to_vec(()).unwrap(), vec![0xFF, FORMAT_VERSION, 95]);
}
#[test]
fn test_some() {
assert_eq!(to_vec(Some(true)).unwrap(), vec![0xFF, FORMAT_VERSION, 84]);
}
#[test]
fn test_unit_struct() {
#[derive(Serialize)]
struct Unit;
let unit = Unit;
assert_eq!(
to_vec(unit).unwrap(),
vec![0xFF, FORMAT_VERSION, 111, 123, 0]
);
}
#[test]
fn test_unit_variant() {
#[derive(Serialize)]
enum Enum {
Variant,
}
assert_eq!(
to_vec(Enum::Variant).unwrap(),
vec![
0xFF,
FORMAT_VERSION,
111,
34,
7,
86,
97,
114,
105,
97,
110,
116,
95,
123,
1
]
)
}
#[test]
fn test_newtype_struct() {
#[derive(Serialize)]
struct Newtype(bool);
assert_eq!(
to_vec(Newtype(true)).unwrap(),
vec![0xFF, FORMAT_VERSION, 84]
);
}
#[test]
fn test_newtype_variant() {
#[derive(Serialize)]
enum Enum {
Variant(bool),
}
assert_eq!(
to_vec(Enum::Variant(true)).unwrap(),
vec![
0xFF,
FORMAT_VERSION,
111,
34,
7,
86,
97,
114,
105,
97,
110,
116,
84,
123,
1
]
)
}
#[test]
fn test_seq() {
assert_eq!(
to_vec([true, false]).unwrap(),
vec![0xFF, FORMAT_VERSION, 65, 2, 84, 70, 36, 0, 2]
);
}
#[test]
fn test_tuple() {
assert_eq!(
to_vec((false, true)).unwrap(),
vec![0xFF, FORMAT_VERSION, 65, 2, 70, 84, 36, 0, 2]
);
}
#[test]
fn test_tuple_struct() {
#[derive(Serialize)]
struct Tuple(bool, bool);
assert_eq!(
to_vec(Tuple(false, true)).unwrap(),
vec![0xFF, FORMAT_VERSION, 65, 2, 70, 84, 36, 0, 2]
);
}
#[test]
fn test_tuple_variant() {
#[derive(Serialize)]
enum Enum {
Variant(bool, bool),
}
assert_eq!(
to_vec(Enum::Variant(true, false)).unwrap(),
vec![
0xFF,
FORMAT_VERSION,
111,
34,
7,
86,
97,
114,
105,
97,
110,
116,
65,
2,
84,
70,
36,
0,
2,
123,
1
],
);
}
#[test]
fn test_map() {
let mut map = std::collections::HashMap::new();
map.insert("Hello", "World");
assert_eq!(
to_vec(map).unwrap(),
vec![
0xFF,
FORMAT_VERSION,
59,
34,
5,
72,
101,
108,
108,
111,
34,
5,
87,
111,
114,
108,
100,
58,
2
],
)
}
#[test]
fn test_struct() {
#[derive(Serialize)]
struct Point {
x: i32,
y: i32,
}
assert_eq!(
to_vec(Point { x: 69, y: 70 }).unwrap(),
vec![
0xFF,
FORMAT_VERSION,
111,
34,
1,
120,
73,
138,
1,
34,
1,
121,
73,
140,
1,
123,
2
],
)
}
#[test]
fn test_struct_variant() {
#[derive(Serialize)]
enum Enum {
Point { x: i32, y: i32 },
}
assert_eq!(
to_vec(Enum::Point { x: 69, y: 70 }).unwrap(),
vec![
0xFF,
FORMAT_VERSION,
111,
34,
5,
80,
111,
105,
110,
116,
111,
34,
1,
120,
73,
138,
1,
34,
1,
121,
73,
140,
1,
123,
2,
123,
1
]
);
}
#[test]
fn test_date_ext() {
// todo
}
| true
|
297c66637d8575968a1b71d51014ff762ed223ba
|
Rust
|
Pfarrer/rust-jvm
|
/_deprecated/src/vm/eval/istore_x.rs
|
UTF-8
| 869
| 3.046875
| 3
|
[] |
no_license
|
use vm::Vm;
use vm::primitive::Primitive;
/// Can handle instructions istore and istore_<n>.
pub fn eval(vm: &mut Vm, code: &Vec<u8>, pc: u16) -> Option<u16> {
// Check which instruction triggered this call, if it was istore, then one byte should be read,
// when it was istore_<n>, the index is implicit
let (index, pc_inc) = match *code.get(pc as usize).unwrap() {
// istore
54 => (*code.get((pc+1) as usize).unwrap(), 2),
// istore_<n>
i @ 59...62 => (i - 59, 1),
i => panic!("Unexpected invocation of this instruction, found: {}", i),
};
let frame = vm.frame_stack.last_mut().unwrap();
let value = frame.stack_pop_int();
trace!("istore_{}: Popped Int {} from to stack and write to locals", index, value);
frame.locals_write(index as usize, Primitive::Int(value));
Some(pc + pc_inc)
}
| true
|
7738cff61f52623ec1eddb7332c80ccf2fa7ba60
|
Rust
|
schoenenberg/oauth2-rs
|
/examples/auth0_async_devicecode.rs
|
UTF-8
| 3,148
| 3.09375
| 3
|
[
"Apache-2.0",
"MIT"
] |
permissive
|
//!
//! This example showcases the Auth0 device authorization flow using the async methods.
//!
//! Before running it, you'll need to create an API and an Application on [auth0.com](https://auth0.com). Take a look at this tutorial, for the details: [Call Your API Using the Device Authorization Flow](https://auth0.com/docs/flows/call-your-api-using-the-device-authorization-flow).
//!
//! In order to run the example call:
//!
//! ```sh
//! AUTH0_CLIENT_ID=xxx AUTH0_AUDIENCE=<your_api_identifier> AUTH_URL=yyy TOKEN_URL=zzz DEVICE_CODE_URL=abc cargo run --example auth0_async_devicecode
//! ```
//!
//! ...and follow the instructions.
//!
use oauth2::basic::BasicClient;
use oauth2::devicecode::StandardDeviceAuthorizationResponse;
use oauth2::reqwest::async_http_client;
use oauth2::{AuthType, AuthUrl, ClientId, DeviceAuthorizationUrl, Scope, TokenUrl};
use std::env;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let auth0_client_id = ClientId::new(
env::var("AUTH0_CLIENT_ID").expect("Missing the AUTH0_CLIENT_ID environment variable."),
);
let audience: String =
env::var("AUTH0_AUDIENCE").expect("MISSING AUTH0_AUDIENCE environment variable.");
let auth_url =
AuthUrl::new(env::var("AUTH_URL").expect("MISSING AUTH_URL environment variable."))
.expect("Invalid authorization endpoint URL");
let token_url =
TokenUrl::new(env::var("TOKEN_URL").expect("MISSING TOKEN_URL environment variable."))
.expect("Invalid token endpoint URL");
let device_auth_url = DeviceAuthorizationUrl::new(
env::var("DEVICE_CODE_URL").expect("MISSING DEVICE_CODE_URL environment variable."),
)
.expect("Invalid device authorization endpoint URL");
// Set up the config for the Auth0 OAuth2 process.
//
// Auth0's OAuth endpoint expects the client_id to be in the request body,
// so ensure that option is set.
let device_client = BasicClient::new(auth0_client_id, None, auth_url, Some(token_url))
.set_device_authorization_url(device_auth_url)
.set_auth_type(AuthType::RequestBody);
// Request the set of codes from the Device Authorization endpoint.
let details: StandardDeviceAuthorizationResponse = device_client
.exchange_device_code()
.unwrap()
.add_scope(Scope::new("profile".to_string()))
.add_extra_param("audience".to_string(), audience) // This is a required parameter
.request_async(async_http_client)
.await?;
// Display the URL and user-code.
println!(
"Open this URL in your browser:\n{}\nand enter the code: {}",
details.verification_uri().to_string(),
details.user_code().secret().to_string()
);
// Now poll for the token
let token = device_client
.exchange_device_access_token(&details)
.request_async(
async_http_client,
|dur| async move {
let _ = tokio::time::sleep(dur).await;
},
None,
)
.await?;
println!("Auth0 returned the following token:\n{:?}\n", token);
Ok(())
}
| true
|
37b63b26738e41f86f3741c814a59abb6ae243ef
|
Rust
|
rust-lang/rustlings
|
/exercises/if/if1.rs
|
UTF-8
| 565
| 3.3125
| 3
|
[
"MIT"
] |
permissive
|
// if1.rs
//
// Execute `rustlings hint if1` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE
pub fn bigger(a: i32, b: i32) -> i32 {
// Complete this function to return the bigger number!
// Do not use:
// - another function call
// - additional variables
}
// Don't mind this for now :)
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ten_is_bigger_than_eight() {
assert_eq!(10, bigger(10, 8));
}
#[test]
fn fortytwo_is_bigger_than_thirtytwo() {
assert_eq!(42, bigger(32, 42));
}
}
| true
|
fee443453284be0c30e4cb0ee44b2a15249592d6
|
Rust
|
glurbi/rustwars
|
/count-of-positives-slash-sum-of-negatives/src/lib.rs
|
UTF-8
| 677
| 3.546875
| 4
|
[] |
no_license
|
// https://www.codewars.com/kata/count-of-positives-slash-sum-of-negatives/
#[allow(dead_code)]
fn count_positives_sum_negatives(input: Vec<i32>) -> Vec<i32> {
if input.is_empty() {
return vec![]
}
let positives = input.iter().filter(|&i| *i > 0).count() as i32;
let negatives = input.iter().filter(|&i| *i < 0).sum();
vec![positives, negatives]
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn returns_expected() {
let test_data1 = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, -15];
let expected1 = vec![10, -65];
assert_eq!(count_positives_sum_negatives(test_data1), expected1);
}
}
| true
|
33fefff5a15042aeb73a9df84d159ed088357b01
|
Rust
|
simrit1/scrappybot
|
/src/notification.rs
|
UTF-8
| 1,550
| 2.640625
| 3
|
[] |
no_license
|
use crate::api::telegram_api::{SendMessage, TelegramClient};
use anyhow::Result;
use core::fmt::Display;
use super::state::Diff;
pub trait NotificationService {
fn notify<T: Display>(&mut self, diff: Diff<T>) -> Result<()>;
}
pub struct TelegramService {
client: TelegramClient,
chat_id: String,
}
impl TelegramService {
pub fn new(client: TelegramClient, chat_id: &str) -> Self {
TelegramService {
client: client,
chat_id: chat_id.to_string(),
}
}
pub async fn notify<T: Display>(&mut self, diff: &Diff<T>, desc: &str) -> Result<()> {
if !diff.added.is_empty() {
for item in diff.added.iter() {
let message = SendMessage {
chat_id: self.chat_id.clone(),
text: format!("New {}:\n {}", desc, item),
parse_mode: Some("MarkdownV2".to_string()),
disable_web_page_preview: true,
};
self.client.send_message(&message).await?;
}
}
if !diff.changed.is_empty() {
for item in diff.changed.iter() {
let message = SendMessage {
chat_id: self.chat_id.clone(),
text: format!("Modified {}:\n {}", desc, item),
parse_mode: Some("MarkdownV2".to_string()),
disable_web_page_preview: true,
};
self.client.send_message(&message).await?;
}
}
Ok(())
}
}
| true
|
7201c9cc56d6f80fee5bf21a5a151de9565f7844
|
Rust
|
arvo/arvo
|
/src/lexer/token_test.rs
|
UTF-8
| 5,946
| 3.09375
| 3
|
[
"MIT"
] |
permissive
|
use super::span::{Span};
use super::token::{Token};
#[test]
fn tokenise_literals() {
assert_eq!(
Token::tokenise("", "true"),
vec![Token::Bool(true, Span::new("", 1, 1, 1, 4))]
);
assert_eq!(
Token::tokenise("", "false"),
vec![Token::Bool(false, Span::new("", 1, 1, 1, 5))]
);
assert_eq!(
Token::tokenise("", "'ä'"),
vec![Token::Char('ä', Span::new("", 1, 1, 1, 3))]
);
assert_eq!(
Token::tokenise("", "'\\u00E4'"),
vec![Token::Char('ä', Span::new("", 1, 1, 1, 8))]
);
assert_eq!(
Token::tokenise("", "3.14"),
vec![Token::Float(3.14, Span::new("", 1, 1, 1, 4))]
);
assert_eq!(
Token::tokenise("", "42"),
vec![Token::Int(42, Span::new("", 1, 1, 1, 2))]
);
assert_eq!(
Token::tokenise("", "\"Arvo Pärt\""),
vec![Token::Str("Arvo Pärt".to_string(), Span::new("", 1, 1, 1, 11))]
);
}
#[test]
fn tokenise_operators() {
assert_eq!(
Token::tokenise("", "1 + 2"),
vec![
Token::Int(1, Span::new("", 1, 1, 1, 1)),
Token::Add(Span::new("", 1, 3, 1, 3)),
Token::Int(2, Span::new("", 1, 5, 1, 5))]
);
assert_eq!(
Token::tokenise("", "1 / 2"),
vec![
Token::Int(1, Span::new("", 1, 1, 1, 1)),
Token::Div(Span::new("", 1, 3, 1, 3)),
Token::Int(2, Span::new("", 1, 5, 1, 5))]
);
assert_eq!(
Token::tokenise("", "1 * 2"),
vec![
Token::Int(1, Span::new("", 1, 1, 1, 1)),
Token::Mul(Span::new("", 1, 3, 1, 3)),
Token::Int(2, Span::new("", 1, 5, 1, 5))]
);
assert_eq!(
Token::tokenise("", "1 - 2"),
vec![
Token::Int(1, Span::new("", 1, 1, 1, 1)),
Token::Sub(Span::new("", 1, 3, 1, 3)),
Token::Int(2, Span::new("", 1, 5, 1, 5))]
);
}
#[test]
fn tokenise_function() {
assert_eq!(
Token::tokenise("", "fn main() void -> {\n}"),
vec![
Token::Func(Span::new("", 1, 1, 1, 2)),
Token::Ident("main".to_string(), Span::new("", 1, 4, 1, 7)),
Token::ParenL(Span::new("", 1, 8, 1, 8)),
Token::ParenR(Span::new("", 1, 9, 1, 9)),
Token::Ident("void".to_string(), Span::new("", 1, 11, 1, 14)),
Token::LambdaR(Span::new("", 1, 16, 1, 17)),
Token::BraceL(Span::new("", 1, 19, 1, 19)),
Token::WhitespaceNewline(Span::new("", 1, 20, 1, 20)),
Token::BraceR(Span::new("", 2, 1, 2, 1))
]
);
}
#[test]
fn tokenise_type_enum() {
assert_eq!(
Token::tokenise("", "type Option a = Some a | Nil"),
vec![
Token::Type(Span::new("", 1, 1, 1, 4)),
Token::Ident("Option".to_string(), Span::new("", 1, 6, 1, 11)),
Token::Ident("a".to_string(), Span::new("", 1, 13, 1, 13)),
Token::Equal(Span::new("", 1, 15, 1, 15)),
Token::Ident("Some".to_string(), Span::new("", 1, 17, 1, 20)),
Token::Ident("a".to_string(), Span::new("", 1, 22, 1, 22)),
Token::Pipe(Span::new("", 1, 24, 1, 24)),
Token::Ident("Nil".to_string(), Span::new("", 1, 26, 1, 28))
]
);
}
#[test]
fn tokenise_type_struct() {
assert_eq!(
Token::tokenise("", "type Point { x f64, y f64 }"),
vec![
Token::Type(Span::new("", 1, 1, 1, 4)),
Token::Ident("Point".to_string(), Span::new("", 1, 6, 1, 10)),
Token::BraceL(Span::new("", 1, 12, 1, 12)),
Token::Ident("x".to_string(), Span::new("", 1, 14, 1, 14)),
Token::Ident("f64".to_string(), Span::new("", 1, 16, 1, 18)),
Token::Comma(Span::new("", 1, 19, 1, 19)),
Token::Ident("y".to_string(), Span::new("", 1, 21, 1, 21)),
Token::Ident("f64".to_string(), Span::new("", 1, 23, 1, 25)),
Token::BraceR(Span::new("", 1, 27, 1, 27))
]
);
}
#[test]
fn tokenise_if() {
assert_eq!(
Token::tokenise("", "if true {\n 1\n} else {\n 0\n}"),
vec![
Token::If(Span::new("", 1, 1, 1, 2)),
Token::Bool(true, Span::new("", 1, 4, 1, 7)),
Token::BraceL(Span::new("", 1, 9, 1, 9)),
Token::WhitespaceNewline(Span::new("", 1, 10, 1, 10)),
Token::Int(1, Span::new("", 2, 3, 2, 3)),
Token::WhitespaceNewline(Span::new("", 2, 4, 2, 4)),
Token::BraceR(Span::new("", 3, 1, 3, 1)),
Token::Else(Span::new("", 3, 3, 3, 6)),
Token::BraceL(Span::new("", 3, 8, 3, 8)),
Token::WhitespaceNewline(Span::new("", 3, 9, 3, 9)),
Token::Int(0, Span::new("", 4, 3, 4, 3)),
Token::WhitespaceNewline(Span::new("", 4, 4, 4, 4)),
Token::BraceR(Span::new("", 5, 1, 5, 1))
]
);
}
#[test]
fn tokenise_for() {
assert_eq!(
Token::tokenise("", "for i in 1 .. 100 {\n}"),
vec![
Token::For(Span::new("", 1, 1, 1, 3)),
Token::Ident("i".to_string(), Span::new("", 1, 5, 1, 5)),
Token::In(Span::new("", 1, 7, 1, 8)),
Token::Int(1, Span::new("", 1, 10, 1, 10)),
Token::DotDot(Span::new("", 1, 12, 1, 13)),
Token::Int(100, Span::new("", 1, 15, 1, 17)),
Token::BraceL(Span::new("", 1, 19, 1, 19)),
Token::WhitespaceNewline(Span::new("", 1, 20, 1, 20)),
Token::BraceR(Span::new("", 2, 1, 2, 1))
]
);
}
#[test]
fn tokenise_writeln() {
assert_eq!(
Token::tokenise("", "writeln(\"Hello, Arvo Pärt\")"),
vec![
Token::Ident("writeln".to_string(), Span::new("", 1, 1, 1, 7)),
Token::ParenL(Span::new("", 1, 8, 1, 8)),
Token::Str("Hello, Arvo Pärt".to_string(), Span::new("", 1, 9, 1, 26)),
Token::ParenR(Span::new("", 1, 27, 1, 27))
]
);
}
| true
|
6b31a4fcffb41502d83155fa1249c530257a39bf
|
Rust
|
fhnw-rust-group/begin-rust-book-examples-tricktron
|
/02/chapter2/src/main.rs
|
UTF-8
| 1,119
| 3.796875
| 4
|
[] |
no_license
|
fn main() {
// this is a comment
let apples: i32 = {
println!("I'm about to figure out how many apples there are");
let x = 10 + 5;
println!("Now I know how many apples there are");
x
};
println!("I will be evaluated after the fist statement with its side-effects");
println!("I have {} apples", apples);
println!("I will be evaluated last");
// exercise1();
exercise5();
}
fn exercise1() {
let name = { "Michael" };
println!("My name is {}", name);
}
fn exercise2() {
println!("4 + 5 == {}", {
{
4 + 5
}
});
}
fn exercise5() {
println!("Far over the Misty Mountains cold");
"Dragon!!!";
let dwarves: i32 = 13;
let hobbit: i32 = {
"Not a wizard";
5 - 4
};
dwarves - 3;
println!(
"The Company of Thorin has {} dwarves and {} hobbit, {}
members in all.",
dwarves,
hobbit,
dwarves + hobbit
);
println!(
"After the Battle of the Five Armies, there were only {} dwarves remaining.",
dwarves - 3
);
}
| true
|
b7fdb624e71317a64111066d46298604e739120b
|
Rust
|
facebookexperimental/MIRAI
|
/checker/tests/run-pass/lazy_const_array.rs
|
UTF-8
| 550
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
// Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
//
// A test that generates a ConstValue::Unevaluated reference to a constant array
// and that checks that MIRAI finds the constant in the summary cache via the def_id
use mirai_annotations::*;
const FOO: [u8; 3] = [1, 2, 3];
const BAR: u8 = FOO[0]; // The reference to FOO is unevaluated in the MIR body that computes BAR
pub fn main() {
verify!(BAR == 1);
}
| true
|
574429a5c244100faa599d83072bccf5a862b514
|
Rust
|
rusticata/asn1-rs
|
/src/asn1_types/oid.rs
|
UTF-8
| 16,757
| 2.890625
| 3
|
[
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
use crate::*;
use alloc::borrow::Cow;
#[cfg(not(feature = "std"))]
use alloc::format;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use core::{
convert::TryFrom, fmt, iter::FusedIterator, marker::PhantomData, ops::Shl, str::FromStr,
};
#[cfg(feature = "bigint")]
use num_bigint::BigUint;
use num_traits::Num;
/// An error for OID parsing functions.
#[derive(Debug)]
pub enum OidParseError {
TooShort,
/// Signalizes that the first or second component is too large.
/// The first must be within the range 0 to 6 (inclusive).
/// The second component must be less than 40.
FirstComponentsTooLarge,
ParseIntError,
}
/// Object ID (OID) representation which can be relative or non-relative.
/// An example for an OID in string representation is `"1.2.840.113549.1.1.5"`.
///
/// For non-relative OIDs restrictions apply to the first two components.
///
/// This library contains a procedural macro `oid` which can be used to
/// create oids. For example `oid!(1.2.44.233)` or `oid!(rel 44.233)`
/// for relative oids. See the [module documentation](index.html) for more information.
#[derive(Hash, PartialEq, Eq, Clone)]
pub struct Oid<'a> {
asn1: Cow<'a, [u8]>,
relative: bool,
}
impl<'a> TryFrom<Any<'a>> for Oid<'a> {
type Error = Error;
fn try_from(any: Any<'a>) -> Result<Self> {
TryFrom::try_from(&any)
}
}
impl<'a, 'b> TryFrom<&'b Any<'a>> for Oid<'a> {
type Error = Error;
fn try_from(any: &'b Any<'a>) -> Result<Self> {
// check that any.data.last().unwrap() >> 7 == 0u8
let asn1 = Cow::Borrowed(any.data);
Ok(Oid::new(asn1))
}
}
impl<'a> CheckDerConstraints for Oid<'a> {
fn check_constraints(any: &Any) -> Result<()> {
any.header.assert_primitive()?;
any.header.length.assert_definite()?;
Ok(())
}
}
impl DerAutoDerive for Oid<'_> {}
impl<'a> Tagged for Oid<'a> {
const TAG: Tag = Tag::Oid;
}
#[cfg(feature = "std")]
impl ToDer for Oid<'_> {
fn to_der_len(&self) -> Result<usize> {
// OID/REL-OID tag will not change header size, so we don't care here
let header = Header::new(
Class::Universal,
false,
Self::TAG,
Length::Definite(self.asn1.len()),
);
Ok(header.to_der_len()? + self.asn1.len())
}
fn write_der_header(&self, writer: &mut dyn std::io::Write) -> SerializeResult<usize> {
let tag = if self.relative {
Tag::RelativeOid
} else {
Tag::Oid
};
let header = Header::new(
Class::Universal,
false,
tag,
Length::Definite(self.asn1.len()),
);
header.write_der_header(writer).map_err(Into::into)
}
fn write_der_content(&self, writer: &mut dyn std::io::Write) -> SerializeResult<usize> {
writer.write(&self.asn1).map_err(Into::into)
}
}
fn encode_relative(ids: &'_ [u64]) -> impl Iterator<Item = u8> + '_ {
ids.iter().flat_map(|id| {
let bit_count = 64 - id.leading_zeros();
let octets_needed = ((bit_count + 6) / 7).max(1);
(0..octets_needed).map(move |i| {
let flag = if i == octets_needed - 1 { 0 } else { 1 << 7 };
((id >> (7 * (octets_needed - 1 - i))) & 0b111_1111) as u8 | flag
})
})
}
impl<'a> Oid<'a> {
/// Create an OID from the ASN.1 DER encoded form. See the [module documentation](index.html)
/// for other ways to create oids.
pub const fn new(asn1: Cow<'a, [u8]>) -> Oid {
Oid {
asn1,
relative: false,
}
}
/// Create a relative OID from the ASN.1 DER encoded form. See the [module documentation](index.html)
/// for other ways to create relative oids.
pub const fn new_relative(asn1: Cow<'a, [u8]>) -> Oid {
Oid {
asn1,
relative: true,
}
}
/// Build an OID from an array of object identifier components.
/// This method allocates memory on the heap.
pub fn from(s: &[u64]) -> core::result::Result<Oid<'static>, OidParseError> {
if s.len() < 2 {
if s.len() == 1 && s[0] == 0 {
return Ok(Oid {
asn1: Cow::Borrowed(&[0]),
relative: false,
});
}
return Err(OidParseError::TooShort);
}
if s[0] >= 7 || s[1] >= 40 {
return Err(OidParseError::FirstComponentsTooLarge);
}
let asn1_encoded: Vec<u8> = [(s[0] * 40 + s[1]) as u8]
.iter()
.copied()
.chain(encode_relative(&s[2..]))
.collect();
Ok(Oid {
asn1: Cow::from(asn1_encoded),
relative: false,
})
}
/// Build a relative OID from an array of object identifier components.
pub fn from_relative(s: &[u64]) -> core::result::Result<Oid<'static>, OidParseError> {
if s.is_empty() {
return Err(OidParseError::TooShort);
}
let asn1_encoded: Vec<u8> = encode_relative(s).collect();
Ok(Oid {
asn1: Cow::from(asn1_encoded),
relative: true,
})
}
/// Create a deep copy of the oid.
///
/// This method allocates data on the heap. The returned oid
/// can be used without keeping the ASN.1 representation around.
///
/// Cloning the returned oid does again allocate data.
pub fn to_owned(&self) -> Oid<'static> {
Oid {
asn1: Cow::from(self.asn1.to_vec()),
relative: self.relative,
}
}
/// Get the encoded oid without the header.
#[inline]
pub fn as_bytes(&self) -> &[u8] {
self.asn1.as_ref()
}
/// Get the encoded oid without the header.
#[deprecated(since = "0.2.0", note = "Use `as_bytes` instead")]
#[inline]
pub fn bytes(&self) -> &[u8] {
self.as_bytes()
}
/// Get the bytes representation of the encoded oid
pub fn into_cow(self) -> Cow<'a, [u8]> {
self.asn1
}
/// Convert the OID to a string representation.
/// The string contains the IDs separated by dots, for ex: "1.2.840.113549.1.1.5"
#[cfg(feature = "bigint")]
pub fn to_id_string(&self) -> String {
let ints: Vec<String> = self.iter_bigint().map(|i| i.to_string()).collect();
ints.join(".")
}
#[cfg(not(feature = "bigint"))]
/// Convert the OID to a string representation.
///
/// If every arc fits into a u64 a string like "1.2.840.113549.1.1.5"
/// is returned, otherwise a hex representation.
///
/// See also the "bigint" feature of this crate.
pub fn to_id_string(&self) -> String {
if let Some(arcs) = self.iter() {
let ints: Vec<String> = arcs.map(|i| i.to_string()).collect();
ints.join(".")
} else {
let mut ret = String::with_capacity(self.asn1.len() * 3);
for (i, o) in self.asn1.iter().enumerate() {
ret.push_str(&format!("{:02x}", o));
if i + 1 != self.asn1.len() {
ret.push(' ');
}
}
ret
}
}
/// Return an iterator over the sub-identifiers (arcs).
#[cfg(feature = "bigint")]
pub fn iter_bigint(
&'_ self,
) -> impl Iterator<Item = BigUint> + FusedIterator + ExactSizeIterator + '_ {
SubIdentifierIterator {
oid: self,
pos: 0,
first: false,
n: PhantomData,
}
}
/// Return an iterator over the sub-identifiers (arcs).
/// Returns `None` if at least one arc does not fit into `u64`.
pub fn iter(
&'_ self,
) -> Option<impl Iterator<Item = u64> + FusedIterator + ExactSizeIterator + '_> {
// Check that every arc fits into u64
let bytes = if self.relative {
&self.asn1
} else if self.asn1.is_empty() {
&[]
} else {
&self.asn1[1..]
};
let max_bits = bytes
.iter()
.fold((0usize, 0usize), |(max, cur), c| {
let is_end = (c >> 7) == 0u8;
if is_end {
(max.max(cur + 7), 0)
} else {
(max, cur + 7)
}
})
.0;
if max_bits > 64 {
return None;
}
Some(SubIdentifierIterator {
oid: self,
pos: 0,
first: false,
n: PhantomData,
})
}
pub fn from_ber_relative(bytes: &'a [u8]) -> ParseResult<'a, Self> {
let (rem, any) = Any::from_ber(bytes)?;
any.header.assert_primitive()?;
any.header.assert_tag(Tag::RelativeOid)?;
let asn1 = Cow::Borrowed(any.data);
Ok((rem, Oid::new_relative(asn1)))
}
pub fn from_der_relative(bytes: &'a [u8]) -> ParseResult<'a, Self> {
let (rem, any) = Any::from_der(bytes)?;
any.header.assert_tag(Tag::RelativeOid)?;
Self::check_constraints(&any)?;
let asn1 = Cow::Borrowed(any.data);
Ok((rem, Oid::new_relative(asn1)))
}
/// Returns true if `needle` is a prefix of the OID.
pub fn starts_with(&self, needle: &Oid) -> bool {
self.asn1.len() >= needle.asn1.len() && self.asn1.starts_with(needle.as_bytes())
}
}
trait Repr: Num + Shl<usize, Output = Self> + From<u8> {}
impl<N> Repr for N where N: Num + Shl<usize, Output = N> + From<u8> {}
struct SubIdentifierIterator<'a, N: Repr> {
oid: &'a Oid<'a>,
pos: usize,
first: bool,
n: PhantomData<&'a N>,
}
impl<'a, N: Repr> Iterator for SubIdentifierIterator<'a, N> {
type Item = N;
fn next(&mut self) -> Option<Self::Item> {
use num_traits::identities::Zero;
if self.pos == self.oid.asn1.len() {
return None;
}
if !self.oid.relative {
if !self.first {
debug_assert!(self.pos == 0);
self.first = true;
return Some((self.oid.asn1[0] / 40).into());
} else if self.pos == 0 {
self.pos += 1;
if self.oid.asn1[0] == 0 && self.oid.asn1.len() == 1 {
return None;
}
return Some((self.oid.asn1[0] % 40).into());
}
}
// decode objet sub-identifier according to the asn.1 standard
let mut res = <N as Zero>::zero();
for o in self.oid.asn1[self.pos..].iter() {
self.pos += 1;
res = (res << 7) + (o & 0b111_1111).into();
let flag = o >> 7;
if flag == 0u8 {
break;
}
}
Some(res)
}
}
impl<'a, N: Repr> FusedIterator for SubIdentifierIterator<'a, N> {}
impl<'a, N: Repr> ExactSizeIterator for SubIdentifierIterator<'a, N> {
fn len(&self) -> usize {
if self.oid.relative {
self.oid.asn1.iter().filter(|o| (*o >> 7) == 0u8).count()
} else if self.oid.asn1.len() == 0 {
0
} else if self.oid.asn1.len() == 1 {
if self.oid.asn1[0] == 0 {
1
} else {
2
}
} else {
2 + self.oid.asn1[2..]
.iter()
.filter(|o| (*o >> 7) == 0u8)
.count()
}
}
#[cfg(feature = "exact_size_is_empty")]
fn is_empty(&self) -> bool {
self.oid.asn1.is_empty()
}
}
impl<'a> fmt::Display for Oid<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.relative {
f.write_str("rel. ")?;
}
f.write_str(&self.to_id_string())
}
}
impl<'a> fmt::Debug for Oid<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("OID(")?;
<Oid as fmt::Display>::fmt(self, f)?;
f.write_str(")")
}
}
impl<'a> FromStr for Oid<'a> {
type Err = OidParseError;
fn from_str(s: &str) -> core::result::Result<Self, Self::Err> {
let v: core::result::Result<Vec<_>, _> = s.split('.').map(|c| c.parse::<u64>()).collect();
v.map_err(|_| OidParseError::ParseIntError)
.and_then(|v| Oid::from(&v))
}
}
/// Helper macro to declare integers at compile-time
///
/// Since the DER encoded oids are not very readable we provide a
/// procedural macro `oid!`. The macro can be used the following ways:
///
/// - `oid!(1.4.42.23)`: Create a const expression for the corresponding `Oid<'static>`
/// - `oid!(rel 42.23)`: Create a const expression for the corresponding relative `Oid<'static>`
/// - `oid!(raw 1.4.42.23)`/`oid!(raw rel 42.23)`: Obtain the DER encoded form as a byte array.
///
/// # Comparing oids
///
/// Comparing a parsed oid to a static oid is probably the most common
/// thing done with oids in your code. The `oid!` macro can be used in expression positions for
/// this purpose. For example
/// ```
/// use asn1_rs::{oid, Oid};
///
/// # let some_oid: Oid<'static> = oid!(1.2.456);
/// const SOME_STATIC_OID: Oid<'static> = oid!(1.2.456);
/// assert_eq!(some_oid, SOME_STATIC_OID)
/// ```
/// To get a relative Oid use `oid!(rel 1.2)`.
///
/// Because of limitations for procedural macros ([rust issue](https://github.com/rust-lang/rust/issues/54727))
/// and constants used in patterns ([rust issue](https://github.com/rust-lang/rust/issues/31434))
/// the `oid` macro can not directly be used in patterns, also not through constants.
/// You can do this, though:
/// ```
/// # use asn1_rs::{oid, Oid};
/// # let some_oid: Oid<'static> = oid!(1.2.456);
/// const SOME_OID: Oid<'static> = oid!(1.2.456);
/// if some_oid == SOME_OID || some_oid == oid!(1.2.456) {
/// println!("match");
/// }
///
/// // Alternatively, compare the DER encoded form directly:
/// const SOME_OID_RAW: &[u8] = &oid!(raw 1.2.456);
/// match some_oid.as_bytes() {
/// SOME_OID_RAW => println!("match"),
/// _ => panic!("no match"),
/// }
/// ```
/// *Attention*, be aware that the latter version might not handle the case of a relative oid correctly. An
/// extra check might be necessary.
#[macro_export]
macro_rules! oid {
(raw $( $item:literal ).*) => {
$crate::exports::asn1_rs_impl::encode_oid!( $( $item ).* )
};
(raw $items:expr) => {
$crate::exports::asn1_rs_impl::encode_oid!($items)
};
(rel $($item:literal ).*) => {
$crate::Oid::new_relative($crate::exports::borrow::Cow::Borrowed(
&$crate::exports::asn1_rs_impl::encode_oid!(rel $( $item ).*),
))
};
($($item:literal ).*) => {
$crate::Oid::new($crate::exports::borrow::Cow::Borrowed(
&$crate::oid!(raw $( $item ).*),
))
};
}
#[cfg(test)]
mod tests {
use crate::{FromDer, Oid, ToDer};
use hex_literal::hex;
#[test]
fn declare_oid() {
let oid = super::oid! {1.2.840.113549.1};
assert_eq!(oid.to_string(), "1.2.840.113549.1");
}
const OID_RSA_ENCRYPTION: &[u8] = &oid! {raw 1.2.840.113549.1.1.1};
const OID_EC_PUBLIC_KEY: &[u8] = &oid! {raw 1.2.840.10045.2.1};
#[allow(clippy::match_like_matches_macro)]
fn compare_oid(oid: &Oid) -> bool {
match oid.as_bytes() {
OID_RSA_ENCRYPTION => true,
OID_EC_PUBLIC_KEY => true,
_ => false,
}
}
#[test]
fn test_compare_oid() {
let oid = Oid::from(&[1, 2, 840, 113_549, 1, 1, 1]).unwrap();
assert_eq!(oid, oid! {1.2.840.113549.1.1.1});
let oid = Oid::from(&[1, 2, 840, 113_549, 1, 1, 1]).unwrap();
assert!(compare_oid(&oid));
}
#[test]
fn oid_to_der() {
let oid = super::oid! {1.2.840.113549.1};
assert_eq!(oid.to_der_len(), Ok(9));
let v = oid.to_der_vec().expect("could not serialize");
assert_eq!(&v, &hex! {"06 07 2a 86 48 86 f7 0d 01"});
let (_, oid2) = Oid::from_der(&v).expect("could not re-parse");
assert_eq!(&oid, &oid2);
}
#[test]
fn oid_starts_with() {
const OID_RSA_ENCRYPTION: Oid = oid! {1.2.840.113549.1.1.1};
const OID_EC_PUBLIC_KEY: Oid = oid! {1.2.840.10045.2.1};
let oid = super::oid! {1.2.840.113549.1};
assert!(OID_RSA_ENCRYPTION.starts_with(&oid));
assert!(!OID_EC_PUBLIC_KEY.starts_with(&oid));
}
#[test]
fn oid_macro_parameters() {
// Code inspired from https://github.com/rusticata/der-parser/issues/68
macro_rules! foo {
($a:literal $b:literal $c:literal) => {
super::oid!($a.$b.$c)
};
}
let oid = foo!(1 2 3);
assert_eq!(oid, oid! {1.2.3});
}
}
| true
|
db82cbc3352a20b09ba2588a869e8e86a119cd16
|
Rust
|
ExpressGradient/learn-rust-monorepo
|
/concurrency/src/bin/message_passing.rs
|
UTF-8
| 1,024
| 3.375
| 3
|
[] |
no_license
|
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
fn main() {
let ( tx, rx ) = mpsc::channel();
let tx_clone = mpsc::Sender::clone(&tx);
thread::spawn(move || {
let messages: Vec<String> = vec![
"Hello World!".to_string(),
"I'm Express".to_string(),
"Goodbye".to_string()
];
for message in messages {
tx.send(message).unwrap();
thread::sleep(Duration::from_secs(2));
}
});
thread::spawn(move || {
let messages: Vec<String> = vec![
"Sadness".to_string(),
"Drowning in Sadness".to_string()
];
for message in messages {
tx_clone.send(message).unwrap();
thread::sleep(Duration::from_secs(1));
}
});
/*if let Ok(message) = rx.try_recv() {
println!("Got {}", message);
} else {
println!("No message received");
}*/
for received in rx {
println!("Got: {}", received);
}
}
| true
|
e5e19b219f604c87c699ad26ca338c98971afcbd
|
Rust
|
SnakeSolid/rust-team-activity
|
/src/stream/convert.rs
|
UTF-8
| 5,640
| 3.21875
| 3
|
[
"MIT"
] |
permissive
|
use rand;
use rand::Rng;
use serde_yaml;
use std::collections::HashMap;
use std::collections::HashSet;
use std::hash::Hash;
use config::ActivityConfig;
use config::Config;
use config::IgnoreConfig;
use config::MessageGroup;
use entity::Entry;
use entity::Object;
#[derive(Debug)]
pub struct FeedToActivity<'a> {
ignore: &'a [IgnoreConfig],
activities: &'a [ActivityConfig],
messages: &'a HashMap<String, Vec<String>>,
}
impl<'a> FeedToActivity<'a> {
pub fn new(config: &Config) -> FeedToActivity {
let activity = config.activity();
FeedToActivity {
ignore: activity.ignore(),
activities: activity.activities(),
messages: activity.messages(),
}
}
pub fn convert(&self, entries: &[Entry]) -> HashMap<String, Vec<String>> {
let mut result = HashMap::new();
let group_messages = self.get_group_messages(entries);
for (group, messages) in group_messages.into_iter() {
let messages = messages.values().iter().take(3).cloned().collect();
result.insert(group, messages);
}
result
}
fn get_group_messages(&self, entries: &[Entry]) -> HashMap<String, DistinctGroup<String>> {
let mut result = HashMap::new();
let mut rng = rand::thread_rng();
for entry in entries {
if self.should_ingore_entry(entry) {
continue;
}
let groups = self.get_entry_groups(entry);
if !groups.is_empty() {
for (key, group) in groups {
if let Some(messages) = self.messages.get(key) {
let values = result.entry(group).or_insert_with(|| DistinctGroup::new());
if let Some(message) = rng.choose(messages) {
values.push(message.clone());
}
} else {
warn!("Messages for key `{}` not found", key);
}
}
} else {
if let Ok(text) = serde_yaml::to_string(entry) {
warn!("------- unknown verb list -------");
warn!("{}", text);
}
}
}
result
}
fn get_entry_groups(&self, entry: &Entry) -> HashMap<&str, String> {
let mut result = HashMap::with_capacity(2);
for activity in self.activities {
if is_entry_match(entry, activity.verbs(), activity.application()) {
if let Some(group) = get_entry_group(entry, activity.group()) {
result.insert(activity.key(), group);
}
}
}
result
}
fn should_ingore_entry(&self, entry: &Entry) -> bool {
for ignore in self.ignore {
if is_entry_match(entry, ignore.verbs(), ignore.application()) {
return true;
}
}
false
}
}
#[derive(Debug)]
struct DistinctGroup<T>
where
T: PartialEq + Eq + Hash + Clone,
{
distinct_values: HashSet<T>,
sorted_values: Vec<T>,
}
impl<T> DistinctGroup<T>
where
T: PartialEq + Eq + Hash + Clone,
{
fn new() -> DistinctGroup<T> {
DistinctGroup {
distinct_values: HashSet::new(),
sorted_values: Vec::new(),
}
}
fn push(&mut self, value: T) {
if !self.distinct_values.contains(&value) {
self.distinct_values.insert(value.clone());
self.sorted_values.push(value);
}
}
fn values(&self) -> &[T] {
&self.sorted_values
}
}
fn get_entry_group(entry: &Entry, group: MessageGroup) -> Option<String> {
match group {
MessageGroup::TargetIssue | MessageGroup::TargetReview | MessageGroup::TargetPage => {
entry.target().map(|t| format!("{}", t))
}
MessageGroup::ObjectIssue => entry
.objects()
.iter()
.filter_map(|o| {
if let Object::Issue { .. } = o {
Some(format!("{}", o))
} else {
None
}
})
.next(),
MessageGroup::ObjectReview => entry
.objects()
.iter()
.filter_map(|o| {
if let Object::Review { .. } = o {
Some(format!("{}", o))
} else {
None
}
})
.next(),
MessageGroup::ObjectPage => entry
.objects()
.iter()
.filter_map(|o| {
if let Object::Page { .. } = o {
Some(format!("{}", o))
} else {
None
}
})
.next(),
MessageGroup::Content => entry.content().map(|t| find_link(t).into()),
}
}
fn find_link(text: &str) -> &str {
if let Some(end_index) = text.find("</a>") {
if let Some(start_index) = text[..end_index].rfind(">") {
&text[start_index + 1..end_index]
} else {
text
}
} else {
text
}
}
fn is_entry_match(
entry: &Entry,
match_verbs: &[String],
match_application: Option<&String>,
) -> bool {
let verbs = entry.verbs();
if verbs == match_verbs {
if let Some(application) = match_application {
if application == entry.application() {
true
} else {
false
}
} else {
true
}
} else {
false
}
}
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.