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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
7fd7454bd36ab7255e9f7678f47707cf79e52431
|
Rust
|
Blue-Pix/ezio
|
/src/cookbook/science/mod.rs
|
UTF-8
| 7,941
| 3.140625
| 3
|
[
"Apache-2.0"
] |
permissive
|
use approx::assert_abs_diff_eq;
use ndarray::{arr1, arr2, array, Array, Array1, ArrayView1};
use nalgebra::{Matrix3, DMatrix};
use num::complex::Complex;
use std::cmp::Ordering;
use std::collections::HashMap;
use num::bigint::{BigInt, ToBigInt};
pub fn add_matrix() {
let a = arr2(&[
[1, 2, 3],
[4, 5, 6],
]);
let b = arr2(&[
[6, 5, 4],
[3, 2, 1],
]);
let sum = &a + &b;
println!("{}", a);
println!("+");
println!("{}", b);
println!("=");
println!("{}", sum);
}
pub fn multiple_matrix() {
let a = arr2(&[
[1, 2, 3],
[4, 5, 6],
]);
let b = arr2(&[
[6, 3],
[5, 2],
[4, 1],
]);
println!("{}", a.dot(&b));
}
pub fn multiple_matrix_with_vector_and_scalar() {
let scalar = 4;
let vector = arr1(&[1, 2, 3]);
let matrix = arr2(&[[4, 5, 6],
[7, 8, 9]]);
let new_vector: Array1<_> = scalar * vector;
println!("{}", new_vector);
let new_matrix = matrix.dot(&new_vector);
println!("{}", new_matrix);
}
pub fn compare_vector() {
let a = Array::from(vec![1., 2., 3., 4., 5.]);
let b = Array::from(vec![5., 4., 3., 2., 1.]);
let mut c = Array::from(vec![1., 2., 3., 4., 5.]);
let mut d = Array::from(vec![5., 4., 3., 2., 1.]);
let z = a + b;
let w = &c + &d;
assert_abs_diff_eq!(z, Array::from(vec![6., 6., 6., 6., 6.]));
println!("c = {}", c);
c[0] = 10.;
d[1] = 10.;
assert_abs_diff_eq!(w, Array::from(vec![6., 6., 6., 6., 6.]));
}
pub fn vector_norm() {
let x = array![1., 2., 3., 4., 5.];
println!("||x||_2 = {}", l2_norm(x.view()));
println!("||x||_1 = {}", l1_norm(x.view()));
println!("Normalizing x yields {:?}", normalize(x));
}
fn l1_norm(x: ArrayView1<f64>) -> f64 {
x.fold(0., |acc, elem| acc + elem.abs())
}
fn l2_norm(x: ArrayView1<f64>) -> f64 {
x.dot(&x).sqrt()
}
fn normalize(mut x: Array1<f64>) -> Array1<f64> {
let norm = l2_norm(x.view());
x.mapv_inplace(|e| e/norm);
x
}
pub fn invert_matrix() {
let m1 = Matrix3::new(2., 1., 1., 3., 2., 1., 2., 1., 2.);
println!("m1 = {}", m1);
match m1.try_inverse() {
Some(inv) => {
println!("The inverse of m1 is: {}", inv);
},
None => {
println!("m1 is not invertible!");
}
}
}
// pub fn serialize_matrix() -> Result<(), std::io::Error> {
// let row_slice: Vec<i32> = vec![1, 2, 3, 4, 5, 6, 7,];
// let matrix = DMatrix::from_row_slice(50, 100, &row_slice);
// let serialized_matrix = serde_json::to_string(matrix)?;
// let deserialized_matrix: DMatrix<i32> = serde_json::from_str(&serialized_matrix)?;
// assert!(matrix == deserialized_matrix);
// Ok(())
// }
pub fn calc_triangle_side_length() {
let angle: f64 = 2.0;
let side_length = 80;
let hypotenuse = side_length as f64 / angle.sin();
println!("Hypotenuse: {}", hypotenuse);
}
pub fn tan() {
let x: f64 = 6.0;
let a = x.tan();
let b = x.sin() / x.cos();
println!("{}", a);
assert_eq!(a, b);
}
pub fn distance_two_points() {
let earth_radius_kilometer = 6371.0_f64;
let (paris_latitude_degrees, paris_longtitude_degrees) = (48.85341_f64, -2.34880_f64);
let (london_latitude_degrees, london_longitude_degrees) = (51.50853_f64, -0.12574_f64);
let paris_latitude = paris_latitude_degrees.to_radians();
let london_latitude = london_latitude_degrees.to_radians();
let delta_latitude = (paris_latitude_degrees - london_latitude_degrees).to_radians();
let delta_longtitude = (paris_longtitude_degrees - london_longitude_degrees).to_radians();
let central_angle_inner = (delta_latitude / 2.0).sin().powi(2) + paris_latitude.cos() * london_latitude.cos() * (delta_longtitude / 2.0).sin().powi(2);
let central_angle = 2.0 * central_angle_inner.sqrt().asin();
let distance = earth_radius_kilometer * central_angle;
println!("Distance between Paris and London on the surface of Earth is {:.1} kilometers", distance);
}
pub fn complex_number() {
let complex_integer = Complex::new(10, 20);
let complex_float = Complex::new(10.1, 20.1);
println!("Complex integer: {}", complex_integer);
println!("Complex float: {}", complex_float);
}
pub fn add_complex_number() {
let complex_num1 = Complex::new(10.0, 20.0);
let complex_num2 = Complex::new(3.1, -4.2);
let sum = complex_num1 + complex_num2;
println!("{}", sum);
}
pub fn calc_mean() {
let data = [3, 1, 6, 1, 5, 8, 1, 8, 10, 11];
let sum = data.iter().sum::<i32>() as f32;
let count = data.len();
let mean = match count {
positive if positive > 0 => Some(sum / count as f32),
_ => None
};
println!("Mean of the data is {:?}", mean);
}
pub fn calc_median() {
let data = [3, 1, 6, 1, 5, 8, 1, 8, 10, 11];
let part = partition(&data);
println!("Partition is {:?}", part);
let sel = select(&data, 5);
println!("Selection at ordered index {} is {:?}", 5, sel);
let med = median(&data);
println!("Median is {:?}", med);
}
fn partition(data: &[i32]) -> Option<(Vec<i32>, i32, Vec<i32>)> {
match data.len() {
0 => None,
_ => {
let (pivot_slice, tail) = data.split_at(1);
let pivot = pivot_slice[0];
let (left, right) = tail.iter().fold((vec![], vec![]), |mut splits, next| {
{
let (ref mut left, ref mut right) = &mut splits;
if next < &pivot {
left.push(*next);
} else {
right.push(*next);
}
}
splits
});
Some((left, pivot, right))
}
}
}
fn select(data: &[i32], k: usize) -> Option<i32> {
let part = partition(data);
match part {
None => None,
Some((left, pivot, right)) => {
let pivot_idx = left.len();
match pivot_idx.cmp(&k) {
Ordering::Equal => Some(pivot),
Ordering::Greater => select(&left, k),
Ordering::Less => select(&right, k - (pivot_idx + 1)),
}
},
}
}
fn median(data: &[i32]) -> Option<f32> {
let size = data.len();
match size {
even if even % 2 == 0 => {
let fst_med = select(data, (even / 2) - 1);
let snd_med = select(data, even / 2);
match (fst_med, snd_med) {
(Some(fst), Some(snd)) => Some((fst + snd) as f32 / 2.0),
_ => None
}
},
odd => select(data, odd / 2).map(|x| x as f32)
}
}
pub fn calc_mode() {
let data = [3, 1, 6, 1, 5, 8, 1, 8, 10, 11];
let frequencies = data.iter().fold(HashMap::new(), |mut freqs, value| {
*freqs.entry(value).or_insert(0) += 1;
freqs
});
let mode = frequencies
.into_iter()
.max_by_key(|&(_, count)| count)
.map(|(value, _)| *value);
println!("Mode of the data is {:?}", mode);
}
pub fn calc_standard_deviation() {
let data = [3, 1, 6, 1, 5, 8, 1, 8, 10, 11];
let data_mean = mean(&data);
println!("Mean is {:?}", data_mean);
let data_std_deviation = std_deviation(&data);
println!("Standard deviation is {:?}", data_std_deviation);
let z_score = match (data_mean, data_std_deviation) {
(Some(mean), Some(std_deviation)) => {
let diff = data[4] as f32 - mean;
Some(diff / std_deviation)
},
_ => None
};
println!("Z-score of data at index 4 (with value {}) is {:?}", data[4], z_score);
}
fn std_deviation(data: &[i32]) -> Option<f32> {
match (mean(data), data.len()) {
(Some(data_mean), count) if count > 0 => {
let variance = data.iter().map(|value| {
let diff = data_mean - (*value as f32);
diff * diff
}).sum::<f32>() / count as f32;
Some(variance.sqrt())
},
_ => None
}
}
fn mean(data: &[i32]) -> Option<f32> {
let sum = data.iter().sum::<i32>() as f32;
let count = data.len();
match count {
positive if positive > 0 => Some(sum / count as f32),
_ => None,
}
}
pub fn calc_big_integer() {
println!("{}! equals {}", 100, factorial(100));
}
fn factorial(x: i32) -> BigInt {
if let Some(mut factorial) = 1.to_bigint() {
for i in 1..=x {
factorial = factorial * i
}
factorial
} else {
panic!("Failed to calculate factorial!");
}
}
| true
|
ae4d560740b28a221e8817831302d17827c69721
|
Rust
|
jklina/rusty_space_clawer
|
/src/team.rs
|
UTF-8
| 310
| 2.640625
| 3
|
[] |
no_license
|
use std::fmt;
use serde::{Serialize, Deserialize};
use cli_table::Table;
#[derive(Table, Serialize, Deserialize, Debug)]
pub struct Team {
id: i32,
name: String,
}
impl fmt::Display for Team {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.name)
}
}
| true
|
896363f336251e91555e2cd0d8eac39b06478d6d
|
Rust
|
Krakaw/mock-pop
|
/src/pop/command.rs
|
UTF-8
| 3,086
| 3.203125
| 3
|
[] |
no_license
|
#[derive(Debug)]
pub enum Command {
User(Option<String>),
Pass(Option<String>),
Noop,
Rset,
Quit,
Uidl,
Stat,
List,
Retr(u32),
Dele(u32),
Capa,
Auth,
}
impl Command {
pub fn from_str(s: &str) -> Option<Command> {
let parts = s.trim().to_uppercase();
let parts = parts.split(" ").collect::<Vec<&str>>();
if parts.is_empty() {
return None;
}
match parts[0] {
"USER" => Some(Command::User(parts.get(1).map(|s| s.to_string()))),
"PASS" => Some(Command::Pass(parts.get(1).map(|s| s.to_string()))),
"NOOP" => Some(Command::Noop),
"RSET" => Some(Command::Rset),
"QUIT" => Some(Command::Quit),
"UIDL" => Some(Command::Uidl),
"STAT" => Some(Command::Stat),
"LIST" => Some(Command::List),
"RETR" => Some(Command::Retr(
parts.get(1).map(|i| i.parse().unwrap_or(0)).unwrap_or(0),
)),
"DELE" => Some(Command::Dele(
parts.get(1).map(|i| i.parse().unwrap_or(0)).unwrap_or(0),
)),
"CAPA" => Some(Command::Capa),
"AUTH" => Some(Command::Auth),
_ => None,
}
}
pub fn respond(&self) -> String {
match self {
Command::User(a) => format!("User: {:?}", a.as_ref().unwrap_or(&"".to_string())),
Command::Pass(a) => format!("Pass: {:?}", a.as_ref().unwrap_or(&"".to_string())),
Command::Stat => {
let messages: Vec<String> = vec![];
let message_count = messages.len();
let message_size = messages.iter().fold(0, |a, b| a + b.as_bytes().len());
format!("{} {}", message_count, message_size)
}
Command::List => {
let messages: Vec<String> = vec![];
let message_count = messages.len();
let message_size = messages.iter().fold(0, |a, b| a + b.as_bytes().len());
let message_list = messages
.iter()
.enumerate()
.map(|(i, val)| format!("{} {}", i + 1, val.as_bytes().len()))
.collect::<Vec<String>>()
.join("\n");
format!(
"{} messages ({} octets)\n{}\n.",
message_count, message_size, message_list
)
}
Command::Retr(message_index) => {
let messages: Vec<&str> = vec!["abcd"];
let message = messages.get(*message_index as usize).unwrap_or(&"");
let message_size = message.clone().as_bytes().len();
format!("{} octets\n{}\n.", message_size, message)
}
Command::Dele(message_index) => format!("message {} deleted", message_index),
Command::Capa => "\nPLAIN\n.".to_string(),
Command::Auth => "\nPLAIN\nANONYMOUS\n.".to_string(),
_ => "".to_string(),
}
}
}
| true
|
f230a1e3ad62ff4003d9294551fb2adbeccd5067
|
Rust
|
supython-coder/leetcode-rust
|
/S0451-sort-characters-by-frequency/src/main.rs
|
UTF-8
| 824
| 3.234375
| 3
|
[] |
no_license
|
struct Solution;
use std::cmp::Ordering;
use std::collections::HashMap;
impl Solution {
pub fn frequency_sort(s: String) -> String {
let mut char_cnt = HashMap::new();
s.bytes().for_each(|c| {
char_cnt.entry(c).and_modify(|e| *e += 1).or_insert(1);
});
let mut byte_arr = s.into_bytes();
byte_arr.sort_by(|x, y| {
if char_cnt.get(x).unwrap_or(&0) > char_cnt.get(y).unwrap_or(&0) {
return Ordering::Less;
}
if char_cnt.get(x).unwrap_or(&0) < char_cnt.get(y).unwrap_or(&0) {
return Ordering::Greater;
}
return x.cmp(y);
});
return String::from_utf8(byte_arr).unwrap();
}
}
fn main() {
println!("{}", Solution::frequency_sort("abacd".to_string()));
}
| true
|
4a316fbfd7b54b6e3d44ea042f2207404b0e7a27
|
Rust
|
benwr/exercises
|
/mackay/src/lib.rs
|
UTF-8
| 7,070
| 3.234375
| 3
|
[] |
no_license
|
pub mod encodings {
use std::clone::Clone;
pub trait Encoder<Input: Clone, Output: Clone> {
fn encode(&self, message: &[Input]) -> Vec<Output>;
fn decode(&self, message: &[Output]) -> Vec<Input>;
}
pub struct Composition<Symbol> {
components: Vec<Box<Encoder<Symbol, Symbol>>>,
}
impl<Symbol: Clone> Composition<Symbol> {
pub fn make_composition() -> Composition<Symbol> {
Composition {components: vec![]}
}
pub fn add_encoder(& mut self, new: Box<Encoder<Symbol, Symbol>>) {
self.components.push(new);
}
}
impl<Symbol: Clone> Encoder<Symbol, Symbol> for Composition<Symbol> {
fn encode(&self, message: &[Symbol]) -> Vec<Symbol> {
let mut result = vec![];
result.extend_from_slice(message);
let mut intermediate;
for e in &self.components {
intermediate = (*e).encode(&result);
result = intermediate;
}
result
}
fn decode(&self, message: &[Symbol]) -> Vec<Symbol> {
let mut result = vec![];
result.extend_from_slice(message);
let mut intermediate;
for e in (&self.components).iter().rev() {
intermediate = (*e).encode(&result);
result = intermediate;
}
result
}
}
#[derive(Debug, Clone)]
pub struct RN {
n: u8,
}
impl RN {
pub fn make_rn(n: u8) -> Result<RN, ()> {
if n % 2 == 0 {
Err(())
} else {
Ok(RN {n: n})
}
}
}
impl Encoder<bool, bool> for RN {
fn encode(&self, message: &[bool]) -> Vec<bool> {
let mut result = vec![];
result.reserve(self.n as usize * message.len());
for &c in message {
match c {
true => {
for _ in 0..self.n {
result.push(true)
}},
false => {
for _ in 0..self.n {
result.push(false)
}
}
}
}
result
}
fn decode(&self, message: &[bool]) -> Vec<bool> {
let mut result = vec![];
let decoded_length = message.len() / (self.n as usize);
result.reserve(decoded_length);
if (message.len() % (self.n as usize)) != 0 || self.n == 0 {
result
} else {
for i in 0..decoded_length {
let mut count: usize = 0;
for j in 0..self.n {
count += if message[i * self.n as usize + j as usize] == true {1} else {0};
}
result.push(count >= self.n as usize / 2);
}
result
}
}
}
#[derive(Clone, Debug)]
pub struct Hamming74 {
}
impl Hamming74 {
pub fn make_hamming74() -> Hamming74 {
Hamming74 {}
}
}
impl Encoder<bool, bool> for Hamming74 {
/* This is not quite the Hamming(7,4) code as it was presented
to me in MacKay. It has identical properties and is primarily
a reordering that makes the code easier.
*/
fn encode(&self, message: &[bool]) -> Vec<bool> {
let mut result = vec![];
for i in 0..message.len() / 4 {
for j in 0..4 {
if i * 4 + j < message.len() {
result.push(message[i * 4 + j]);
} else {
result.push(false);
}
}
for j in 0..3 {
let mut acc = false;
for k in 0..4 {
if k != j {
acc ^= message[i * 4 + k];
}
}
result.push(acc);
}
}
result
}
fn decode(&self, message: &[bool]) -> Vec<bool> {
let mut result = vec![];
for i in 0..(message.len() / 7) {
for j in 0..4 {
result.push(message[i * 7 + j]);
}
let mut syndrome: u8 = 0;
for j in 0..3 {
let mut syndrome_i = message[i * 7 + 4 + j];
for k in 0..4 {
if k != j {
syndrome_i ^= message[i * 7 + k];
}
}
syndrome |= (syndrome_i as u8) << j;
}
let flipped_bit : usize = match syndrome {
0b011 => 0b10,
0b101 => 0b01,
0b110 => 0b00,
0b111 => 0b11,
_ => 0b11111111,
};
if flipped_bit != 0b11111111 {
result[i * 7 + flipped_bit] = !result[i * 7 + flipped_bit];
}
}
result
}
}
}
#[cfg(test)]
mod tests {
use encodings;
use encodings::Encoder;
#[test]
fn rn() {
let r3 = encodings::RN::make_rn(3).unwrap();
let cleartext1 = vec![];
let result1 = r3.encode(&cleartext1);
assert_eq!(result1, []);
assert_eq!(&r3.decode(&result1), &cleartext1);
let cleartext2 = vec![true];
let result2 = r3.encode(&cleartext2);
assert_eq!(result2, [true, true, true]);
assert_eq!(&r3.decode(&result2), &cleartext2);
let cleartext3 = vec![true, false, true];
let result3 = r3.encode(&cleartext3);
assert_eq!(result3, [true, true, true, false, false, false, true, true, true]);
assert_eq!(&r3.decode(&result3), &cleartext3);
let result4 = r3.decode(&cleartext3);
assert_eq!(result4, [true]);
}
#[test]
fn h74() {
let h = encodings::Hamming74::make_hamming74();
let cleartext1 = vec![];
let result1 = h.encode(&cleartext1);
assert_eq!(result1, []);
assert_eq!(&h.decode(&result1), &cleartext1);
let cleartext2 = vec![true, true, true, true];
let result2 = h.encode(&cleartext2);
assert_eq!(result2, [true, true, true, true, true, true, true]);
assert_eq!(&h.decode(&result2), &cleartext2);
let cleartext3 = vec![true, false, true, false, true, false, true,
false];
let result3 = h.encode(&cleartext3);
assert_eq!(result3, [true, false, true, false, true, false, true, true,
false, true, false, true, false, true]);
assert_eq!(&h.decode(&result3), &cleartext3);
let flipped = vec![true, true, true, true, true, false, false];
assert_eq!(h.decode(&flipped), [false, true, true, true]);
let flipped2 = vec![true, true, true, true, false, false, false];
assert_eq!(h.decode(&flipped2), [true, true, true, false]);
}
#[test]
fn composition() {
let h = Box::new(encodings::Hamming74::make_hamming74());
let r = Box::new(encodings::RN::make_rn(3).unwrap());
let mut c = encodings::Composition::make_composition();
c.add_encoder(r);
c.add_encoder(h);
let cleartext1 = vec![];
let result1 = c.encode(&cleartext1);
assert_eq!(result1, []);
// TODO Actually test this composition
}
}
| true
|
eb9d76e0999b2b35250a88f2f20767913b0c016e
|
Rust
|
RoccoDev/bson-rust
|
/src/datetime.rs
|
UTF-8
| 7,646
| 3.34375
| 3
|
[
"MIT"
] |
permissive
|
use std::{
fmt::{self, Display},
time::{Duration, SystemTime},
};
use chrono::{LocalResult, TimeZone, Utc};
/// Struct representing a BSON datetime.
/// Note: BSON datetimes have millisecond precision.
///
/// To enable conversions between this type and [`chrono::DateTime`], enable the `"chrono-0_4"`
/// feature flag in your `Cargo.toml`.
/// ```
/// use chrono::prelude::*;
/// # fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
/// # #[cfg(feature = "chrono-0_4")]
/// # {
/// let chrono_dt: chrono::DateTime<Utc> = "2014-11-28T12:00:09Z".parse()?;
/// let bson_dt: bson::DateTime = chrono_dt.into();
/// let bson_dt = bson::DateTime::from_chrono(chrono_dt);
/// let back_to_chrono: chrono::DateTime<Utc> = bson_dt.into();
/// let back_to_chrono = bson_dt.to_chrono();
/// # }
/// # Ok(())
/// # }
/// ```
///
/// This type differs from [`chrono::DateTime`] in that it serializes to and deserializes from a
/// BSON datetime rather than an RFC 3339 formatted string. Additionally, in non-BSON formats, it
/// will serialize to and deserialize from that format's equivalent of the
/// [extended JSON representation](https://docs.mongodb.com/manual/reference/mongodb-extended-json/) of a datetime.
/// To serialize a [`chrono::DateTime`] as a BSON datetime, you can use
/// [`crate::serde_helpers::chrono_datetime_as_bson_datetime`].
///
/// ```rust
/// # #[cfg(feature = "chrono-0_4")]
/// # {
/// use serde::{Serialize, Deserialize};
///
/// #[derive(Serialize, Deserialize)]
/// struct Foo {
/// // serializes as a BSON datetime.
/// date_time: bson::DateTime,
///
/// // serializes as an RFC 3339 / ISO-8601 string.
/// chrono_datetime: chrono::DateTime<chrono::Utc>,
///
/// // serializes as a BSON datetime.
/// // this requires the "chrono-0_4" feature flag
/// #[serde(with = "bson::serde_helpers::chrono_datetime_as_bson_datetime")]
/// chrono_as_bson: chrono::DateTime<chrono::Utc>,
/// }
/// # }
/// ```
#[derive(Eq, PartialEq, Ord, PartialOrd, Hash, Copy, Clone)]
pub struct DateTime(i64);
impl crate::DateTime {
/// The latest possible date that can be represented in BSON.
pub const MAX: Self = Self::from_millis(i64::MAX);
/// The earliest possible date that can be represented in BSON.
pub const MIN: Self = Self::from_millis(i64::MIN);
/// Makes a new [`DateTime`] from the number of non-leap milliseconds since
/// January 1, 1970 0:00:00 UTC (aka "UNIX timestamp").
pub const fn from_millis(date: i64) -> Self {
Self(date)
}
/// Returns a [`DateTime`] which corresponds to the current date and time.
pub fn now() -> DateTime {
Self::from_system_time(SystemTime::now())
}
#[cfg(not(feature = "chrono-0_4"))]
pub(crate) fn from_chrono<T: chrono::TimeZone>(dt: chrono::DateTime<T>) -> Self {
Self::from_millis(dt.timestamp_millis())
}
/// Convert the given `chrono::DateTime` into a `bson::DateTime`, truncating it to millisecond
/// precision.
#[cfg(feature = "chrono-0_4")]
#[cfg_attr(docsrs, doc(cfg(feature = "chrono-0_4")))]
pub fn from_chrono<T: chrono::TimeZone>(dt: chrono::DateTime<T>) -> Self {
Self::from_millis(dt.timestamp_millis())
}
fn to_chrono_private(self) -> chrono::DateTime<Utc> {
match Utc.timestamp_millis_opt(self.0) {
LocalResult::Single(dt) => dt,
_ => {
if self.0 < 0 {
chrono::MIN_DATETIME
} else {
chrono::MAX_DATETIME
}
}
}
}
#[cfg(not(feature = "chrono-0_4"))]
#[allow(unused)]
pub(crate) fn to_chrono(self) -> chrono::DateTime<Utc> {
self.to_chrono_private()
}
/// Convert this [`DateTime`] to a [`chrono::DateTime<Utc>`].
///
/// Note: Not every BSON datetime can be represented as a [`chrono::DateTime`]. For such dates,
/// [`chrono::MIN_DATETIME`] or [`chrono::MAX_DATETIME`] will be returned, whichever is closer.
///
/// ```
/// let bson_dt = bson::DateTime::now();
/// let chrono_dt = bson_dt.to_chrono();
/// assert_eq!(bson_dt.timestamp_millis(), chrono_dt.timestamp_millis());
///
/// let big = bson::DateTime::from_millis(i64::MAX);
/// let chrono_big = big.to_chrono();
/// assert_eq!(chrono_big, chrono::MAX_DATETIME)
/// ```
#[cfg(feature = "chrono-0_4")]
#[cfg_attr(docsrs, doc(cfg(feature = "chrono-0_4")))]
pub fn to_chrono(self) -> chrono::DateTime<Utc> {
self.to_chrono_private()
}
/// Convert the given [`std::time::SystemTime`] to a [`DateTime`].
///
/// If the provided time is too far in the future or too far in the past to be represented
/// by a BSON datetime, either [`DateTime::MAX`] or [`DateTime::MIN`] will be
/// returned, whichever is closer.
pub fn from_system_time(st: SystemTime) -> Self {
match st.duration_since(SystemTime::UNIX_EPOCH) {
Ok(d) => {
if d.as_millis() <= i64::MAX as u128 {
Self::from_millis(d.as_millis() as i64)
} else {
Self::MAX
}
}
// handle SystemTime from before the Unix Epoch
Err(e) => {
let millis = e.duration().as_millis();
if millis > i64::MAX as u128 {
Self::MIN
} else {
Self::from_millis(-(millis as i64))
}
}
}
}
/// Convert this [`DateTime`] to a [`std::time::SystemTime`].
pub fn to_system_time(self) -> SystemTime {
if self.0 >= 0 {
SystemTime::UNIX_EPOCH + Duration::from_millis(self.0 as u64)
} else {
// need to convert to i128 before calculating absolute value since i64::MIN.abs()
// overflows and panics.
SystemTime::UNIX_EPOCH - Duration::from_millis((self.0 as i128).abs() as u64)
}
}
/// Returns the number of non-leap-milliseconds since January 1, 1970 UTC.
pub const fn timestamp_millis(self) -> i64 {
self.0
}
pub(crate) fn to_rfc3339(self) -> String {
self.to_chrono()
.to_rfc3339_opts(chrono::SecondsFormat::AutoSi, true)
}
}
impl fmt::Debug for crate::DateTime {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut tup = f.debug_tuple("DateTime");
match Utc.timestamp_millis_opt(self.0) {
LocalResult::Single(ref dt) => tup.field(dt),
_ => tup.field(&self.0),
};
tup.finish()
}
}
impl Display for crate::DateTime {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match Utc.timestamp_millis_opt(self.0) {
LocalResult::Single(ref dt) => Display::fmt(dt, f),
_ => Display::fmt(&self.0, f),
}
}
}
impl From<SystemTime> for crate::DateTime {
fn from(st: SystemTime) -> Self {
Self::from_system_time(st)
}
}
impl From<crate::DateTime> for SystemTime {
fn from(dt: crate::DateTime) -> Self {
dt.to_system_time()
}
}
#[cfg(feature = "chrono-0_4")]
#[cfg_attr(docsrs, doc(cfg(feature = "chrono-0_4")))]
impl From<crate::DateTime> for chrono::DateTime<Utc> {
fn from(bson_dt: DateTime) -> Self {
bson_dt.to_chrono()
}
}
#[cfg(feature = "chrono-0_4")]
#[cfg_attr(docsrs, doc(cfg(feature = "chrono-0_4")))]
impl<T: chrono::TimeZone> From<chrono::DateTime<T>> for crate::DateTime {
fn from(x: chrono::DateTime<T>) -> Self {
Self::from_chrono(x)
}
}
| true
|
475fd221d18413b00e3a1b7fef7bb13a1ddaac4e
|
Rust
|
kunicmarko20/exercism.io
|
/rust/prime-factors/src/lib.rs
|
UTF-8
| 560
| 3.296875
| 3
|
[] |
no_license
|
pub fn factors(n: u64) -> Vec<u64> {
if n < 2 {
return vec!();
}
let mut prime_factors: Vec<u64> = Vec::new();
let mut result = n.clone();
while result != 1 {
let next_prime_factor = next_prime_factor(result, n).unwrap();
result = result / next_prime_factor;
prime_factors.push(next_prime_factor);
}
prime_factors
}
fn next_prime_factor(result: u64, n: u64) -> Option<u64> {
for number in 2..n+1 {
if result % number == 0 {
return Some(number);
}
}
None
}
| true
|
35210a336c22971c5bf20fe1d867ec9aba21a131
|
Rust
|
brnkes/2019-aoc-stuff
|
/d15/src/lib/arcade.rs
|
UTF-8
| 1,785
| 3.1875
| 3
|
[] |
no_license
|
use super::robot::{Canvas, Coords};
use std::collections::HashMap;
use std::hash::Hash;
use wasm_bindgen::prelude::*;
use super::robot::get_canvas_from_coords;
#[wasm_bindgen]
pub struct Arcade {
visited_coords: HashMap<Coords,u64>,
// joystick: i8,
score: u64
}
#[wasm_bindgen]
impl Arcade {
pub fn new() -> Arcade {
Arcade {
visited_coords: HashMap::new(),
// joystick: 0,
score: 0
}
}
pub fn draw_stuff(&mut self, x:i64, y:i64, tile_id: u64) {
if x == -1 && y == 0 {
self.score = tile_id;
return;
}
let mut slot = self.visited_coords.entry(Coords{x,y}).or_insert(0);
*slot = tile_id;
}
// joystick handled by browser...
// pub fn read_joystick(&mut self, stick_pos: i8) {
// self.joystick = stick_pos;
// }
pub fn get_canvas_size(&self) -> Canvas {
get_canvas_from_coords(self.visited_coords.keys())
}
pub fn get_count_of(&self, tile_id:u64) -> u64 {
let mut counts:HashMap<u64,u64> = HashMap::new();
self.visited_coords
.values()
.for_each(
|next| {
let mut count = counts.entry(*next).or_insert(0);
*count += 1;
}
);
*counts.get(&tile_id).unwrap_or(&0)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_arcade() {
let mut arcade = Arcade::new();
arcade.draw_stuff(1,3,1);
arcade.draw_stuff(1,4,2);
arcade.draw_stuff(1,3,2);
arcade.draw_stuff(-2,6,3);
assert_eq!(arcade.get_count_of(1), 0);
assert_eq!(arcade.get_count_of(2), 2);
assert_eq!(arcade.get_count_of(3), 1);
}
}
| true
|
47bec3f909d70ba587b2ff7aa01c2faf2ce4871a
|
Rust
|
yeochinyi/codetest
|
/exercism/rust/minesweeper/src/lib.rs
|
UTF-8
| 1,316
| 2.984375
| 3
|
[] |
no_license
|
use std::collections::HashMap;
pub fn annotate(minefield: &[&str]) -> Vec<String> {
let mut m: HashMap<(isize, isize), usize> = HashMap::new();
(0..minefield.len()).for_each(|x| {
(0..minefield[x].len()).for_each(|y| {
count(&mut m, minefield, x, y);
})
});
//println!("{:?}", m);
(0..minefield.len())
.map(|x| {
(0..minefield[x].len())
.map(|y| repr(minefield[x].chars().nth(y).unwrap(), &m, x, y))
.collect()
})
.collect()
}
fn repr(c: char, map: &HashMap<(isize, isize), usize>, x: usize, y: usize) -> String {
match c {
'*' => "*".to_string(),
_ => {
return match map.get(&(x as isize, y as isize)) {
None => " ".to_owned(),
Some(x) => x.to_string(),
};
}
}
}
fn count(map: &mut HashMap<(isize, isize), usize>, minefield: &[&str], x: usize, y: usize) {
if minefield[x].chars().nth(y) != Some('*') {
return;
}
let x = x as isize;
let y = y as isize;
(-1..=1).map(|i| i as isize).for_each(|m| {
(-1..=1).map(|i| i as isize).for_each(|n| {
let c = ((x + m), (y + n));
let _ = *map.entry(c).and_modify(|x| *x += 1).or_insert(1);
})
});
}
| true
|
522404584fbf4313842d5bc59dc14f77d0d3d685
|
Rust
|
Jaic1/xv6-riscv-rust
|
/src/register/mie.rs
|
UTF-8
| 375
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
//! mie register
use bit_field::BitField;
#[inline]
unsafe fn read() -> usize {
let ret: usize;
llvm_asm!("csrr $0, mie":"=r"(ret):::"volatile");
ret
}
#[inline]
unsafe fn write(x: usize) {
llvm_asm!("csrw mie, $0"::"r"(x)::"volatile");
}
/// set MTIE field
pub unsafe fn set_mtie() {
let mut mie = read();
mie.set_bit(7, true);
write(mie);
}
| true
|
a60d9f7ced293fdc3305541bcdcea48f5d125b6c
|
Rust
|
emmiegit/slog-mock
|
/src/lib.rs
|
UTF-8
| 1,574
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
/*
* lib.rs
*
* slog-mock - Mock crate for slog to compile out all logging.
* Copyright (c) 2021 Ammon Smith
*
* slog-mock is available free of charge under the terms of the MIT
* License. You are free to redistribute and/or modify it under those
* terms. It is distributed in the hopes that it will be useful, but
* WITHOUT ANY WARRANTY. See the LICENSE file for more details.
*
*/
//! Crate to mock [`slog`] objects and macros.
//!
//! This exports many expected pieces of functionality
//! from the `slog` crate, but has them compile into no-ops.
//!
//! The goal is to allow a crate consumer to have a feature where
//! this crate is used instead of `slog`, and all logging calls
//! resolve cleanly but don't produce any code in the final binary.
//!
//! Not all of `slog`'s functionality is mocked: you will need to
//! gate any actual requirements on its traits or structures
//! behind `#[cfg(feature)]` checks.
//!
//! [`slog`]: https://crates.io/crates/slog
#![deny(missing_debug_implementations, missing_docs)]
#![forbid(unsafe_code)]
extern crate slog_mock_proc_macros;
pub use slog_mock_proc_macros::*;
/// Dummy logging macro, mimics `slog::slog_o!`.
#[macro_export]
macro_rules! slog_o {
($($key:expr => $value:expr,)+) => {};
($($key:expr => $value:expr),*) => {};
}
/// Dummy logging macro, mimics `slog::o!`.
///
/// See `slog_o!`.
#[macro_export]
macro_rules! o {
($($key:expr => $value:expr,)+) => {
slog_o!($($key => $value),+)
};
($($key:expr => $value:expr),*) => {
slog_o!($(key => $value),*)
};
}
| true
|
bc383163d9346a9430becd97ca37f475a9474985
|
Rust
|
paritytech/substrate
|
/primitives/core/src/hash.rs
|
UTF-8
| 3,887
| 2.734375
| 3
|
[
"Apache-2.0",
"GPL-3.0-or-later",
"Classpath-exception-2.0",
"GPL-1.0-or-later",
"GPL-3.0-only"
] |
permissive
|
// This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! A fixed hash type.
pub use primitive_types::{H160, H256, H512};
/// Hash conversion. Used to convert between unbound associated hash types in traits,
/// implemented by the same hash type.
/// Panics if used to convert between different hash types.
pub fn convert_hash<H1: Default + AsMut<[u8]>, H2: AsRef<[u8]>>(src: &H2) -> H1 {
let mut dest = H1::default();
assert_eq!(dest.as_mut().len(), src.as_ref().len());
dest.as_mut().copy_from_slice(src.as_ref());
dest
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_h160() {
let tests = vec![
(Default::default(), "0x0000000000000000000000000000000000000000"),
(H160::from_low_u64_be(2), "0x0000000000000000000000000000000000000002"),
(H160::from_low_u64_be(15), "0x000000000000000000000000000000000000000f"),
(H160::from_low_u64_be(16), "0x0000000000000000000000000000000000000010"),
(H160::from_low_u64_be(1_000), "0x00000000000000000000000000000000000003e8"),
(H160::from_low_u64_be(100_000), "0x00000000000000000000000000000000000186a0"),
(H160::from_low_u64_be(u64::MAX), "0x000000000000000000000000ffffffffffffffff"),
];
for (number, expected) in tests {
assert_eq!(
format!("{:?}", expected),
serde_json::to_string_pretty(&number).expect("Json pretty print failed")
);
assert_eq!(number, serde_json::from_str(&format!("{:?}", expected)).unwrap());
}
}
#[test]
fn test_h256() {
let tests = vec![
(
Default::default(),
"0x0000000000000000000000000000000000000000000000000000000000000000",
),
(
H256::from_low_u64_be(2),
"0x0000000000000000000000000000000000000000000000000000000000000002",
),
(
H256::from_low_u64_be(15),
"0x000000000000000000000000000000000000000000000000000000000000000f",
),
(
H256::from_low_u64_be(16),
"0x0000000000000000000000000000000000000000000000000000000000000010",
),
(
H256::from_low_u64_be(1_000),
"0x00000000000000000000000000000000000000000000000000000000000003e8",
),
(
H256::from_low_u64_be(100_000),
"0x00000000000000000000000000000000000000000000000000000000000186a0",
),
(
H256::from_low_u64_be(u64::MAX),
"0x000000000000000000000000000000000000000000000000ffffffffffffffff",
),
];
for (number, expected) in tests {
assert_eq!(
format!("{:?}", expected),
serde_json::to_string_pretty(&number).expect("Json pretty print failed")
);
assert_eq!(number, serde_json::from_str(&format!("{:?}", expected)).unwrap());
}
}
#[test]
fn test_invalid() {
assert!(serde_json::from_str::<H256>(
"\"0x000000000000000000000000000000000000000000000000000000000000000\""
)
.unwrap_err()
.is_data());
assert!(serde_json::from_str::<H256>(
"\"0x000000000000000000000000000000000000000000000000000000000000000g\""
)
.unwrap_err()
.is_data());
assert!(serde_json::from_str::<H256>(
"\"0x00000000000000000000000000000000000000000000000000000000000000000\""
)
.unwrap_err()
.is_data());
assert!(serde_json::from_str::<H256>("\"\"").unwrap_err().is_data());
assert!(serde_json::from_str::<H256>("\"0\"").unwrap_err().is_data());
assert!(serde_json::from_str::<H256>("\"10\"").unwrap_err().is_data());
}
}
| true
|
fcd0c747ff6496308e15a50b2edf871ddce38041
|
Rust
|
CodeSandwich/rust-cardano
|
/chain-impl-mockchain/src/block.rs
|
UTF-8
| 5,255
| 3.078125
| 3
|
[
"MIT"
] |
permissive
|
//! Representation of the block in the mockchain.
use crate::key::*;
use crate::transaction::*;
use bincode;
use chain_core::property;
/// Non unique identifier of the transaction position in the
/// blockchain. There may be many transactions related to the same
/// `SlotId`.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize)]
pub struct SlotId(u32, u32);
impl property::BlockDate for SlotId {}
/// `Block` is an element of the blockchain it contains multiple
/// transaction and a reference to the parent block. Alongside
/// with the position of that block in the chain.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
pub struct Block {
pub slot_id: SlotId,
pub parent_hash: Hash,
pub transactions: Vec<SignedTransaction>,
}
impl property::Block for Block {
type Id = Hash;
type Date = SlotId;
/// Identifier of the block, currently the hash of the
/// serialized transaction.
fn id(&self) -> Self::Id {
let bytes = bincode::serialize(self).expect("unable to serialize block");
Hash::hash_bytes(&bytes)
}
/// Id of the parent block.
fn parent_id(&self) -> Self::Id {
self.parent_hash
}
/// Date of the block.
fn date(&self) -> Self::Date {
self.slot_id
}
}
impl property::Serialize for Block {
// FIXME: decide on appropriate format for mock blockchain
type Error = bincode::Error;
fn serialize<W: std::io::Write>(&self, writer: W) -> Result<(), Self::Error> {
bincode::serialize_into(writer, self)
}
}
impl property::Deserialize for Block {
// FIXME: decide on appropriate format for mock blockchain
type Error = bincode::Error;
fn deserialize<R: std::io::Read>(reader: R) -> Result<Block, bincode::Error> {
bincode::deserialize_from(reader)
}
}
impl property::HasTransaction<SignedTransaction> for Block {
fn transactions<'a>(&'a self) -> std::slice::Iter<'a, SignedTransaction> {
self.transactions.iter()
}
}
/// `Block` is an element of the blockchain it contains multiple
/// transaction and a reference to the parent block. Alongside
/// with the position of that block in the chain.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
pub struct SignedBlock {
/// Internal block.
block: Block,
/// Public key used to sign the block.
public_key: PublicKey,
/// List of cryptographic signatures that verifies the block.
signature: Signature,
}
impl SignedBlock {
/// Create a new signed block.
pub fn new(block: Block, pkey: PrivateKey) -> Self {
use chain_core::property::Block;
let block_id = block.id();
SignedBlock {
block: block,
public_key: pkey.public(),
signature: pkey.sign(block_id.as_ref()),
}
}
/// Verify if block is correctly signed by the key.
/// Return `false` if there is no such signature or
/// if it can't be verified.
pub fn verify(&self) -> bool {
use chain_core::property::Block;
let block_id = self.block.id();
self.public_key.verify(block_id.as_ref(), &self.signature)
}
}
impl property::Serialize for SignedBlock {
type Error = bincode::Error;
fn serialize<W: std::io::Write>(&self, writer: W) -> Result<(), Self::Error> {
bincode::serialize_into(writer, self)
}
}
impl property::Deserialize for SignedBlock {
type Error = bincode::Error;
fn deserialize<R: std::io::Read>(reader: R) -> Result<Self, bincode::Error> {
bincode::deserialize_from(reader)
}
}
impl property::Block for SignedBlock {
type Id = <Block as property::Block>::Id;
type Date = <Block as property::Block>::Date;
/// Identifier of the block, currently the hash of the
/// serialized transaction.
fn id(&self) -> Self::Id {
self.block.id()
}
/// Id of the parent block.
fn parent_id(&self) -> Self::Id {
self.block.parent_id()
}
/// Date of the block.
fn date(&self) -> Self::Date {
self.block.date()
}
}
#[cfg(test)]
mod test {
use super::*;
use quickcheck::{Arbitrary, Gen};
quickcheck! {
fn block_serialization_bijection(b: Block) -> bool {
property::testing::serialization_bijection(b)
}
fn signed_block_serialization_bijection(b: SignedBlock) -> bool {
property::testing::serialization_bijection(b)
}
}
impl Arbitrary for Block {
fn arbitrary<G: Gen>(g: &mut G) -> Self {
Block {
slot_id: Arbitrary::arbitrary(g),
parent_hash: Arbitrary::arbitrary(g),
transactions: Arbitrary::arbitrary(g),
}
}
}
impl Arbitrary for SignedBlock {
fn arbitrary<G: Gen>(g: &mut G) -> Self {
SignedBlock {
block: Arbitrary::arbitrary(g),
public_key: Arbitrary::arbitrary(g),
signature: Arbitrary::arbitrary(g),
}
}
}
impl Arbitrary for SlotId {
fn arbitrary<G: Gen>(g: &mut G) -> Self {
SlotId(Arbitrary::arbitrary(g), Arbitrary::arbitrary(g))
}
}
}
| true
|
a82e62cd2651aa21172ec09f6f29bdf66d480625
|
Rust
|
twtvfhpfm/rust_exercise
|
/exercise/src/vec_.rs
|
UTF-8
| 465
| 2.921875
| 3
|
[] |
no_license
|
pub fn test_vec()
{
let mut v = vec![Vec::new(),Vec::new(),Vec::new()];
let mut v1 = &mut v[1];
v1.push(1);
let mut v0 = &mut v[0];
v0.push(0);
println!("{:?}", v);
println!("{}", v[0][0]);
let mut s1 = String::from("hello");
let mut s2 = String::from("world");
let mut s3 = s1 + &s2;
println!("{}", s3);
let s4 = String::from("徐建南");
//let s4 = "徐建南";
let c = &s4[0..3];
println!("{}", c);
}
| true
|
a614c9e820449d5429fc083bb97e2742400f0ec5
|
Rust
|
tanacchi/actix-webapp
|
/src/handlers.rs
|
UTF-8
| 5,359
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
use actix_web::{
web, HttpResponse, Result
};
use crate::state;
use crate::param;
use crate::templates;
pub async fn index(data: web::Data<state::AppState>) -> String {
let app_name = &data.app_name;
format!("Hello {}!", app_name)
}
pub async fn dashboard(id: Identity) -> Result<HttpResponse> {
let logged_in: bool = id.identity().is_some();
let html: String = templates::dashboard(logged_in);
Ok(HttpResponse::Ok().body(html))
}
pub async fn user_list(db_pool: web::Data<Pool>) -> Result<HttpResponse> {
let client: Client = db_pool.get().await.map_err(MyError::PoolError)?;
let users = db::get_all_users(&client).await?;
Ok(HttpResponse::Ok().json(users))
}
pub async fn user_show(web::Path(user_name): web::Path<String>, db_pool: web::Data<Pool>) -> Result<HttpResponse> {
let client: Client = db_pool.get().await.map_err(MyError::PoolError)?;
let user = db::search_user(&client, user_name).await?;
Ok(HttpResponse::Ok().json(user))
}
pub async fn category_list(db_pool: web::Data<Pool>) -> Result<HttpResponse> {
let client: Client = db_pool.get().await.map_err(MyError::PoolError)?;
let categories = db::get_all_categories(&client).await?;
Ok(HttpResponse::Ok().json(categories))
}
pub async fn category_form() -> Result<HttpResponse> {
let html: String = templates::category_form();
Ok(HttpResponse::Ok().body(html))
}
use crate::{models::Category};
pub async fn add_category(params: web::Form<param::ParamsForNewCategory>, db_pool: web::Data<Pool>) -> Result<HttpResponse> {
let client: Client = db_pool.get().await.map_err(MyError::PoolError)?;
let _new_category = Category {id: -1, name: params.name.clone()};
let new_category = db::add_category(&client, _new_category).await?;
Ok(HttpResponse::Ok().json(new_category))
}
pub async fn signup_form() -> Result<HttpResponse> {
let html: String = templates::signup_form();
Ok(HttpResponse::Ok()
.content_type("text/html; charset=utf-8")
.body(html))
}
use crate::{
db,
models::User,
error::{MyError, AccountError},
};
use deadpool_postgres::{Client, Pool};
pub async fn signup(params : web::Form<param::ParamsForSignUp>, db_pool: web::Data<Pool>) -> Result<HttpResponse> {
let user_info = User {id: -1, name: params.name.clone()};
let client: Client = db_pool.get().await.map_err(MyError::PoolError)?;
let new_user = db::add_user(&client, user_info)
.await
.map_err(AccountError::SignUpFailed)?;
Ok(HttpResponse::Ok().json(new_user))
}
pub async fn signin_form() -> Result<HttpResponse> {
let html: String = templates::signin_form();
Ok(HttpResponse::Ok().body(html))
}
use actix_identity::Identity;
pub async fn signin(params: web::Form<param::ParamsForSignIn>,
db_pool: web::Data<Pool>,
id: Identity) -> Result<HttpResponse> {
let client: Client = db_pool.get().await.map_err(MyError::PoolError)?;
let user = db::search_user(&client, params.name.clone())
.await
.map_err(|_err| AccountError::SignInFailed)?; // FIXME
id.remember(user.id.to_string());
Ok(HttpResponse::Ok().json(user))
}
pub async fn signout(id: Identity) -> HttpResponse {
id.forget();
HttpResponse::Ok().finish()
}
pub async fn new_report_form(id: Identity, db_pool: web::Data<Pool>) -> Result<HttpResponse> {
let logged_in: bool = id.identity().is_some();
let client: Client = db_pool.get().await.map_err(MyError::PoolError)?;
let categories: Vec<Category> = db::get_all_categories(&client).await?;
let html: String = templates::report_form(logged_in, categories);
Ok(HttpResponse::Ok().body(html))
}
pub async fn new_report(params: web::Form<param::ParamsForNewReport>,
db_pool: web::Data<Pool>,
id: Identity) -> Result<HttpResponse> {
use chrono::{Date, NaiveDateTime, Local, TimeZone, LocalResult};
use crate::models::Report;
let date: Date<Local> = NaiveDateTime::parse_from_str(
&format!("{} 00:00:00", ¶ms.date),
"%Y-%m-%d %H:%M:%S")
.map(|dt| Local.from_local_datetime(&dt))
.unwrap()
.map(|dt| dt.date())
.unwrap();
// if date > Local::today() {
// return MyError::InvalidDateOfReport;
// }
let user_id: i64 = id.identity()
.and_then(|id_str| id_str.parse::<i64>().ok())
.unwrap();
let _new_report = Report {
id: -1,
user_id: 1,
comment: params.comment.clone(),
date: date.format("%Y-%m-%d").to_string(),
category_id: params.category.clone()
// user_id: user_id,
};
let client: Client = db_pool.get().await.map_err(MyError::PoolError)?;
let new_report = db::add_report(&client, _new_report).await?;
println!("comment: {}\ndate:{:?}\ncategory:{}",
params.comment.clone(),
date,
// params.category.clone()
1
);
Ok(HttpResponse::Ok().json(new_report))
}
pub async fn report_show(web::Path(report_id): web::Path<i64>,
db_pool: web::Data<Pool>) -> Result<HttpResponse> {
let client: Client = db_pool.get().await.map_err(MyError::PoolError)?;
let report = db::get_report(&client, report_id).await?;
Ok(HttpResponse::Ok().json(report))
}
| true
|
66d81f0da1cf74053cd49f640f5721d3925c5f1c
|
Rust
|
ci123chain/ci123chain-cdk
|
/src/runtime.rs
|
UTF-8
| 8,523
| 2.59375
| 3
|
[] |
no_license
|
use crate::codec::Sink;
use crate::types::{Address, ContractResult, Response};
use crate::prelude::{panic, vec, Vec};
const INPUT_TOKEN: i32 = 0;
static mut PANIC_HOOK: bool = false;
pub fn make_dependencies() -> Dependencies {
unsafe {
if PANIC_HOOK == false {
panic::set_hook(Box::new(|panic_info| {
panic(&panic_info.to_string());
}));
PANIC_HOOK = true;
}
};
Dependencies {
storage: Store::new(),
api: ExternalApi::new(),
}
}
pub(crate) fn panic(data: &str) {
unsafe {
panic_contract(data.as_ptr(), data.len());
}
}
pub struct Event<'a> {
pub r#type: &'a str,
pub attr: Vec<(&'a str, ItemValue<'a>)>,
}
impl<'a> Event<'a> {
pub fn new(event_type: &'a str) -> Event {
Event {
r#type: event_type,
attr: vec![],
}
}
pub fn add(&mut self, key: &'a str, value: ItemValue<'a>) {
self.attr.push((key, value));
}
pub(crate) fn to_vec(&self) -> Vec<u8> {
// [type, size of attr, [key, type of value, value ]...]
// [string, usize, [string, byte, ItemValue]...]
let mut sink = Sink::new(0);
sink.write_str(&self.r#type);
sink.write_usize(self.attr.len());
for (k, v) in self.attr.iter() {
sink.write_str(k);
match v {
ItemValue::Int64(i) => {
sink.write_byte(0);
sink.write_i64(*i);
}
ItemValue::Str(s) => {
sink.write_byte(1);
sink.write_str(s);
}
}
}
sink.into()
}
}
pub enum ItemValue<'a> {
Str(&'a str),
Int64(i64),
}
pub struct Dependencies {
pub storage: Store,
pub api: ExternalApi,
}
pub struct Store {
prefix: &'static str,
}
impl Store {
fn new() -> Store {
Store { prefix: "" }
}
pub fn set(&self, key: &[u8], value: &[u8]) {
let key = self.gen_key(key);
let key_ptr = key.as_ptr();
let key_size = key.len();
let value_ptr = value.as_ptr();
let value_size = value.len();
unsafe {
write_db(key_ptr, key_size, value_ptr, value_size);
}
}
pub fn get(&self, key: &[u8]) -> Option<Vec<u8>> {
const INITIAL: usize = 32;
let key = self.gen_key(key);
let mut value = vec![0; INITIAL];
let key_ptr = key.as_ptr();
let key_size = key.len();
let value_ptr = value.as_mut_ptr();
let value_size = value.len();
let size = unsafe { read_db(key_ptr, key_size, value_ptr, value_size, 0) };
if size < 0 {
return None;
}
let size = size as usize;
value.resize(size, 0);
if size > INITIAL {
let value = &mut value[INITIAL..];
unsafe { read_db(key_ptr, key_size, value.as_mut_ptr(), value.len(), INITIAL) };
}
Some(value)
}
pub fn delete(&self, key: &[u8]) {
let key = self.gen_key(key);
let key_ptr = key.as_ptr();
let key_size = key.len();
unsafe {
delete_db(key_ptr, key_size);
}
}
fn gen_key(&self, key: &[u8]) -> Vec<u8> {
let mut real_key: Vec<u8> = self.prefix.as_bytes().iter().cloned().collect();
for &ele in key {
real_key.push(ele);
}
real_key
}
}
pub struct ExternalApi {}
impl<'a> ExternalApi {
fn new() -> ExternalApi {
ExternalApi {}
}
// 获取合约输入
pub fn input(&self) -> Vec<u8> {
self.get_input(INPUT_TOKEN)
}
// 代币转账
pub fn send(&self, to: &Address, amount: u64) -> bool {
unsafe { send(to.as_ptr(), amount) }
}
// 获取合约创建者(用户地址)
pub fn get_creator(&self) -> Address {
let creator = Address::default();
unsafe { get_creator(creator.as_ptr() as *mut u8) };
creator
}
// 获取合约调用者(用户地址)
pub fn get_invoker(&self) -> Address {
let invoker = Address::default();
unsafe { get_invoker(invoker.as_ptr() as *mut u8) };
invoker
}
// 获取合约调用者(用户地址或合约地址)
pub fn get_pre_caller(&self) -> Address {
let caller = Address::default();
unsafe { get_pre_caller(caller.as_ptr() as *mut u8) };
caller
}
// 获取当前合约地址
pub fn self_address(&self) -> Address {
let contract = Address::default();
unsafe { self_address(contract.as_ptr() as *mut u8) };
contract
}
// 获取当前block header时间戳
pub fn get_timestamp(&self) -> u64 {
unsafe { get_time() }
}
// 合约返回
pub fn ret(&self, result: Result<Response, &'a str>) {
match result {
Ok(response) => {
let output = ContractResult::Ok(response).to_vec();
unsafe { return_contract(output.as_ptr(), output.len()) };
}
Err(err) => {
let output = ContractResult::Err(err).to_vec();
unsafe { return_contract(output.as_ptr(), output.len()) };
}
}
}
// 事件通知
pub fn notify(&self, event: &Event) {
let raw = event.to_vec();
unsafe { notify_contract(raw.as_ptr(), raw.len()) };
}
// 调用合约
pub fn call_contract(&self, addr: &Address, input: &[u8]) -> Option<Vec<u8>> {
let addr_ptr = addr.as_ptr();
let input_ptr = input.as_ptr();
let size = input.len();
let token = unsafe { call_contract(addr_ptr, input_ptr, size) };
if token < 0 {
return None;
}
Some(self.get_input(token))
}
// // 销毁本合约
// pub fn destroy_contract(&self) {
// unsafe { destroy_contract() }
// }
// 获取指定验证者的权益
pub fn get_validator_power(&self, validators: &[&Address]) -> Vec<u64> {
let mut sink = Sink::new(0);
sink.write_usize(validators.len());
for &validator in validators.iter() {
sink.write_bytes(validator.as_bytes());
}
let mut power = vec![0u64; validators.len()];
unsafe {
get_validator_power(
sink.as_bytes().as_ptr(),
sink.as_bytes().len(),
power.as_mut_ptr() as *mut u8,
)
};
power
}
// 获取所有验证者的权益之和
pub fn total_power(&self) -> u64 {
unsafe { total_power() }
}
fn get_input(&self, token: i32) -> Vec<u8> {
let input_size = unsafe { get_input_length(token) };
let input: Vec<u8> = vec![0; input_size];
let input_ptr = input.as_ptr();
unsafe { get_input(token, input_ptr, input_size) };
input
}
}
// This interface will compile into required Wasm imports.
extern "C" {
fn get_input_length(token: i32) -> usize;
fn get_input(token: i32, input_ptr: *const u8, input_size: usize);
fn notify_contract(msg_ptr: *const u8, msg_size: usize);
fn return_contract(value_ptr: *const u8, value_size: usize);
fn read_db(
key_ptr: *const u8,
key_size: usize,
value_ptr: *mut u8,
value_size: usize,
offset: usize,
) -> i32;
fn write_db(key_ptr: *const u8, key_size: usize, value_ptr: *const u8, value_size: usize);
fn delete_db(key_ptr: *const u8, key_size: usize);
fn send(to_ptr: *const u8, amount: u64) -> bool;
fn get_creator(creator_ptr: *mut u8);
fn get_invoker(invoker_ptr: *mut u8);
fn self_address(contract_ptr: *mut u8);
fn get_pre_caller(caller_ptr: *mut u8);
fn get_time() -> u64;
fn call_contract(addr_ptr: *const u8, input_ptr: *const u8, input_size: usize) -> i32;
// fn destroy_contract();
fn panic_contract(data_ptr: *const u8, data_size: usize);
fn get_validator_power(data_ptr: *const u8, data_size: usize, value_ptr: *mut u8);
fn total_power() -> u64;
#[cfg(debug_assertions)]
pub fn debug_print(str_ptr: *const u8, str_size: usize);
}
#[macro_export]
macro_rules! debug {
($($arg:tt)*) => {
#[cfg(debug_assertions)]
{
use crate::runtime::debug_print;
let s = format!($($arg)*);
unsafe { debug_print(s.as_ptr(), s.len()) };
}
}
}
| true
|
2dc1e1a0479524f95f3e62afc478d6debde020fa
|
Rust
|
MingweiChen/SAT_Solver
|
/src/test/mod.rs
|
UTF-8
| 6,039
| 2.5625
| 3
|
[] |
no_license
|
use sat::sat_lib::*;
use std::vec::Vec;
use rand::Rng;
use time::now;
extern crate sat;
extern crate rand;
extern crate time;
pub fn test() {
sat_test();
println!("Correctness Test: ");
random_correctness_test(1000);
println!("\nEfficiency Test: ");
random_efficiency_test(3);
}
fn sat_test() {
// (1\/~6\/8)/\(2\/~8\/4)/\(9\/~4\/1)/\(8\/~4)/\(7\/5\/0)/\(~0\/8\/~5)/\(~9\/~1)/\(1\/6)/\
// (8\/2)/\(2\/5\/~3)/\(~1\/9\/9)/\(1\/6\/~2)/\(7\/~4\/9)/\(~0\/~8)/\(2\/~2)/\(2\/7\/~0)/\(4\/6)
let mut solver = Solver::new();
let v = solver.create_vars(10);
let x = Lit::create_lits(&v);
solver.add_clause_from_lits(vec![x[1], !x[6], x[8]]).unwrap();
solver.add_clause_from_lits(vec![x[2], !x[8], x[4]]).unwrap();
solver.add_clause_from_lits(vec![x[9], !x[4], x[1]]).unwrap();
solver.add_clause_from_lits(vec![x[8], !x[4]]).unwrap();
solver.add_clause_from_lits(vec![x[7], x[5], x[0]]).unwrap();
solver.add_clause_from_lits(vec![!x[0], x[8], !x[5]]).unwrap();
solver.add_clause_from_lits(vec![!x[9], !x[1]]).unwrap();
solver.add_clause_from_lits(vec![x[1], x[6]]).unwrap();
solver.add_clause_from_lits(vec![x[8], x[2]]).unwrap();
solver.add_clause_from_lits(vec![x[2], x[5], !x[3]]).unwrap();
solver.add_clause_from_lits(vec![!x[1], x[9], x[9]]).unwrap();
solver.add_clause_from_lits(vec![x[1], x[6], !x[2]]).unwrap();
solver.add_clause_from_lits(vec![x[7], !x[4], x[9]]).unwrap();
solver.add_clause_from_lits(vec![!x[0], !x[8]]).unwrap();
solver.add_clause_from_lits(vec![x[2], !x[2]]).unwrap();
solver.add_clause_from_lits(vec![x[2], x[7], !x[0]]).unwrap();
solver.add_clause_from_lits(vec![x[4], x[6]]).unwrap();
solver.add_clause_from_lits(vec![]).unwrap();
println!("{}", solver);
// solver.simplify();
// println!("{}", solver);
println!("{}", solver.solve());
solver.print_model();
}
fn random_correctness_test(num: usize) {
let mut sat_case = 0;
let mut unsat_case = 0;
for i in 0..num {
if i % 1000 == 0 {
println!("Correctness test num: {}", i);
}
let mut solver = Solver::new();
let var_n = 10; // number of variables
{
let clause_ms = 5.; // max size of each clause
let clause_mn = 50.; // number of clauses
let assign_mn = 0.; // number of assignments (unit clauses)
let mut lits = Vec::<Lit>::new();
for i in solver.create_vars(var_n) {
lits.push(Lit::new(i));
}
random_clauses(&mut solver, lits, var_n as f32, clause_ms, clause_mn, assign_mn, false);
}
let clauses = solver.get_oringin_clauses();
let sat = solver.solve();
if sat {
sat_case += 1;
if !verify(&clauses, solver.get_model()) {
println!("Wrong Model");
return;
}
}else {
unsat_case += 1;
if !verify_unsat(&clauses, var_n) {
println!("CNF is sat");
return;
}
}
}
println!("Num of sat: {}\tNum of unsat: {}", sat_case, unsat_case);
println!("Test Passed");
}
fn random_efficiency_test(num: usize) {
for i in 0..num {
let mut solver = Solver::new();
{
let var_n = 10000; // number of variables
let clause_ms = 40.; // max size of each clause
let clause_mn = 100000.; // number of clauses
let assign_mn = 20.; // number of assignments (unit clauses)
solver.set_iter_num(var_n * 2);
println!("Random Test {}: \n\tVar num: {}\n\tMax clause num: {}\n\tMax clause size: {}\n\tMax assignment num: {}\n", i + 1, var_n, clause_mn, clause_ms as usize, assign_mn as usize);
let mut lits = Vec::<Lit>::new();
for i in solver.create_vars(var_n) {
lits.push(Lit::new(i));
}
println!("Generating CNF...\n");
random_clauses(&mut solver, lits, var_n as f32, clause_ms, clause_mn, assign_mn, true);
// println!("{}", solver);
}
let clauses = solver.get_oringin_clauses();
println!("Solving...\n");
let start_time = now();
let sat = solver.solve();
let end_time = now();
let duration = end_time - start_time;
print!("Total time: {}.{} s\t", duration.num_seconds(), duration.num_milliseconds() - duration.num_seconds() * 1000);
// solver.print_model();
print!("SAT: {}\t", sat);
println!("Result Match: {}\n\n======================================================\n", if sat {verify(&clauses, solver.get_model())} else {true});
solver.reset();
}
}
fn verify_unsat(clauses: &[Clause], var_num: usize) -> bool {
for i in 0..1024 {
let mut model = Vec::<VarValue>::new();
for j in 0..var_num {
if i >> j & 1 == 0 {
model.push(VarValue::VTrue);
}else {
model.push(VarValue::VFalse);
}
}
if verify(clauses, &model) {
return false;
}
}
true
}
fn verify(clauses: &[Clause], model: &[VarValue]) -> bool {
for clause in clauses {
let lits = clause.get_all_lits();
let mut result = false;
for j in lits {
let lit = j.0;
if lit.get_value() == model[lit.var_num()] {
result = true;
break;
}
}
if !result {
return false;
}
}
true
}
fn random_clauses(solver: &mut Solver, x: Vec<Lit>, lit_n: f32, clause_ms: f32, clause_mn: f32, assign_mn: f32, print: bool) {
let mut rng = rand::thread_rng();
let assign_n = (rng.next_f32() * assign_mn).floor() as usize;
for _ in 0..assign_n {
let lit_num = (rng.next_f32() * lit_n).floor() as usize;
if rng.gen() {
solver.add_clause_from_lits(vec![x[lit_num]]).unwrap();
}else {
solver.add_clause_from_lits(vec![!x[lit_num]]).unwrap();
}
}
let clause_n = (rng.next_f32() * clause_mn + 1. + clause_mn * 3.).floor() as usize / 4;
let mut total_size = 0;
for _ in 0..clause_n {
let mut clause = Clause::new();
let clause_s = (rng.next_f32() * (clause_ms - 1.) + 2.).floor() as usize;
total_size += clause_s;
for _ in 0..clause_s {
let lit_num = (rng.next_f32() * lit_n).floor() as usize;
if rng.gen() {
clause.push(x[lit_num]);
}else {
clause.push(!x[lit_num]);
}
}
// println!("{}", clause);
solver.add_clause(clause).unwrap();
}
if print {
println!("\tClause num: {}\n\tTotal clause size: {}\n\tAssignment num: {}\n", clause_n, total_size, assign_n);
}
// println!("{}", solver);
}
| true
|
697ba8a0007559e29374902f0eb3c9ee1c6080d1
|
Rust
|
PWhiddy/nannou
|
/nannou-new/src/main.rs
|
UTF-8
| 6,304
| 3.140625
| 3
|
[
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
//! A simple tool for creating a new nannou project.
//!
//! 1. Determines whether the user is just sketching or wants an App (with model and event `fn`s).
//! 2. Asks for a sketch/app name.
extern crate names;
extern crate rand;
use std::env;
use std::io::{self, BufRead, Write};
use std::fs::{self, File};
use std::path::Path;
use std::process::{Command, Stdio};
use std::sync::mpsc;
use std::thread;
enum Goal { Sketch, App }
const TEMPLATE_SKETCH: &[u8] = include_bytes!("../../examples/template_sketch.rs");
const TEMPLATE_APP: &[u8] = include_bytes!("../../examples/template_app.rs");
impl Goal {
fn template_bytes(&self) -> &[u8] {
match *self {
Goal::Sketch => TEMPLATE_SKETCH,
Goal::App => TEMPLATE_APP,
}
}
}
// Ask the user the given question, get a trimmed response.
fn ask_user(question: &str) -> io::Result<String> {
print!("{}", question);
io::stdout().flush()?;
let mut response = String::new();
io::stdin().read_line(&mut response)?;
Ok(response.trim().to_string())
}
enum Response { Yes, No }
fn yes_or_no(s: &str) -> Option<Response> {
let s = s.to_ascii_lowercase();
match &s[..] {
"" | "y" | "yes" | "yeah" | "yep" | "flip yes" => Some(Response::Yes),
"n" | "no" | "nah" | "nope" | "flip no" => Some(Response::No),
_ => None,
}
}
fn random_beverage() -> &'static str {
if rand::random() {
"cup of coffee"
} else {
"cup of tea"
}
}
fn main() {
// Retrieve the name of the exe that the user wishes to package.
let response = ask_user("Are you sketching? (Y/n): ").expect("failed to get user input");
let goal = match yes_or_no(&response) {
Some(Response::Yes) => Goal::Sketch,
Some(Response::No) => Goal::App,
_ => {
println!("I don't understand \"{}\", I was expecting \"y\" or \"n\". Exiting", response);
return;
}
};
// Get a name for the sketch.
let name = loop {
let response = ask_user("Name your sketch: ").expect("failed to get user input");
if !response.is_empty() {
break response;
}
let random_name = names::Generator::default().next().expect("failed to generate name");
let question = format!("Hmmm... How about the name, \"{}\"? (Y/n): ", random_name);
let response = ask_user(&question).expect("failed to get user input");
if let Some(Response::Yes) = yes_or_no(&response) {
break random_name;
}
};
// TODO: Ask the user for additional cargo args.
// TODO: Find the current version of nannou.
let nannou_version = "0.5";
let nannou_dependency = format!("nannou = \"{}\"", nannou_version);
// TODO: Load the template example or fallback to compiled template.
let template_bytes = goal.template_bytes();
// Get the current directory.
let current_directory = env::current_dir()
.expect("could not retrieve current directory");
// Create the project path.
let project_path = current_directory.join(&name);
println!("Creating cargo project: \"{}\"", project_path.display());
Command::new("cargo")
.arg("new")
.arg("--bin")
.arg(&name)
.output()
.expect("failed to create cargo project");
// Assert the path now exists.
assert!(project_path.exists());
assert!(project_path.is_dir());
// Remove the existing main file.
let src_path = project_path.join("src");
let main_path = src_path.join(Path::new("main").with_extension("rs"));
fs::remove_file(&main_path).expect("failed to remove existing \"main.rs\" file");
// Create the file from the template string.
{
println!("Writing template file \"{}\"", main_path.display());
let mut file = File::create(main_path).expect("failed to create new main file");
file.write_all(template_bytes).expect("failed to write to new main file");
}
// Append the nannou dependency to the "Cargo.toml" file.
{
println!("Adding nannou dependency \"{}\"", nannou_dependency);
let cargo_toml_path = project_path.join("Cargo").with_extension("toml");
let mut file = fs::OpenOptions::new()
.write(true)
.append(true)
.open(&cargo_toml_path)
.expect("failed to open \"Cargo.toml\" to add nannou dependency");
writeln!(file, "\n{}", nannou_dependency).expect("failed to append nannou dependency");
}
// Change the directory to the newly created path.
println!("Changing the current directory to \"{}\"", project_path.display());
env::set_current_dir(&project_path).expect("failed to change directories");
// Building and running.
let bev = random_beverage();
println!("Building `{}`. This might take a while for the first time. Grab a {}?", name, bev);
let mut child = Command::new("cargo")
.arg("build")
.arg("--release")
.stderr(Stdio::piped())
.stdout(Stdio::piped())
.spawn()
.expect("failed to spawn cargo build and run process");
// Read from cargo's stdout and stderr.
let err = io::BufReader::new(child.stderr.take().unwrap());
let out = io::BufReader::new(child.stdout.take().unwrap());
let (tx, rx) = mpsc::channel();
let tx_err = tx.clone();
let err_handle = thread::spawn(move || {
for line in err.lines().filter_map(|l| l.ok()) {
tx_err.send(Err(line)).expect("failed to send piped stderr");
}
});
let out_handle = thread::spawn(move || {
for line in out.lines().filter_map(|l| l.ok()) {
tx.send(Ok(line)).expect("failed to send piped stdout");
}
});
// Print the stdout and stderr from cargo.
for result in rx {
match result {
Ok(line) => println!("[cargo] {}", line),
Err(line) => eprintln!("[cargo] {}", line),
}
}
err_handle.join().unwrap();
out_handle.join().unwrap();
// If the exe is where it should be, assume the build succeeded.
let exe_path = project_path.join("target").join("release").join(&name);
if exe_path.exists() {
println!("Successfully built \"{}\"! Go forth and create!", name);
}
}
| true
|
b584ed861844bdccbfe65efc47e5af0ebecef478
|
Rust
|
yohandev/voxels
|
/voxels/src/common/block/face.rs
|
UTF-8
| 2,468
| 3.90625
| 4
|
[] |
no_license
|
use ezmath::*;
/// block face enum, in global coordinates.
/// that means a block's right face, for example
/// is always right no matter how it's rotated.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
#[allow(dead_code)]
#[repr(u8)]
pub enum BlockFace
{
/// -z
North = 0,
/// +z
South = 1,
/// -x
West = 2,
/// +x
East = 3,
/// -y
Down = 4,
/// +y
Up = 5,
}
impl BlockFace
{
/// get the normalized direction
/// of this block face, that is,
/// the up block face yields a
/// <0, 1, 0> vector. adding a
/// block face's normal vector
/// to a block's position yields
/// the position of the block
/// adjacent to that face.
/// # example
/// ```rust
/// let foo = int3::new(0, 3, 1);
/// let baz = foo + BlockFace::North::normal();
///
/// // baz is the block that touches foo's
/// // north face.
/// ```
pub fn normal(self) -> int3
{
match self
{
BlockFace::North => int3::new(0, 0, -1),
BlockFace::South => int3::new(0, 0, 1),
BlockFace::West => int3::new(-1, 0, 0),
BlockFace::East => int3::new(1, 0, 0),
BlockFace::Down => int3::new(0, -1, 0),
BlockFace::Up => int3::new(0, 1, 0),
}
}
/// get the block face opposite to this
/// one
pub fn opposite(self) -> BlockFace
{
match self
{
BlockFace::North => BlockFace::South,
BlockFace::South => BlockFace::North,
BlockFace::West => BlockFace::East,
BlockFace::East => BlockFace::West,
BlockFace::Down => BlockFace::Up,
BlockFace::Up => BlockFace::Down,
}
}
}
impl From<usize> for BlockFace
{
fn from(num: usize) -> Self
{
match num
{
0 => Self::North,
1 => Self::South,
2 => Self::West,
3 => Self::East,
4 => Self::Down,
5 => Self::Up,
_ => panic!("direction cannot be inferred from {}!", num)
}
}
}
impl From<u8> for BlockFace
{
fn from(num: u8) -> Self
{
Self::from(num as usize)
}
}
impl From<u16> for BlockFace
{
fn from(num: u16) -> Self
{
Self::from(num as usize)
}
}
impl From<u32> for BlockFace
{
fn from(num: u32) -> Self
{
Self::from(num as usize)
}
}
| true
|
310742bfdc369bf17f2b3632a9ad61869c71f7cc
|
Rust
|
jthelin/demikernel
|
/src/rust/scheduler/yielder.rs
|
UTF-8
| 4,499
| 2.953125
| 3
|
[
"MIT"
] |
permissive
|
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
//======================================================================================================================
// Imports
//======================================================================================================================
use crate::{
runtime::fail::Fail,
scheduler::handle::YielderHandle,
};
use ::std::{
future::Future,
pin::Pin,
task::{
Context,
Poll,
},
};
//======================================================================================================================
// Structures
//======================================================================================================================
/// Yield is a future that lets the currently running coroutine cooperatively yield because it cannot make progress.
/// Coroutines are expected to use the standalone async functions to create yield points.
struct Yield {
/// How many times have we already yielded?
already_yielded: usize,
/// How many times should we yield? If none, then we yield until a wake signal.
yield_quanta: Option<usize>,
/// Shared references to wake a yielded coroutine and return either an Ok to indicate there is work to be done or //
/// an error to stop the coroutine.
yielder_handle: YielderHandle,
}
/// Yielder lets a single coroutine yield to the scheduler. The yield handle can be used to wake the coroutine.
pub struct Yielder {
yielder_handle: YielderHandle,
}
//======================================================================================================================
// Associate Functions
//======================================================================================================================
impl Yield {
/// Create new Yield future that can be used to yield.
fn new(yield_quanta: Option<usize>, yielder_handle: YielderHandle) -> Self {
Self {
already_yielded: 0,
yield_quanta,
yielder_handle,
}
}
}
impl Yielder {
/// Create a new Yielder object for a specific coroutine to yield.
pub fn new() -> Self {
Self {
yielder_handle: YielderHandle::new(),
}
}
/// Return a handle to this Yielder for waking the yielded coroutine.
pub fn get_handle(&self) -> YielderHandle {
self.yielder_handle.clone()
}
/// Create a Yield Future that yields for just one quanta.
pub async fn yield_once(&self) -> Result<(), Fail> {
Yield::new(Some(1), self.yielder_handle.clone()).await
}
/// Create a Yield future that yields for n quanta.
pub async fn yield_times(&self, n: usize) -> Result<(), Fail> {
Yield::new(Some(n), self.yielder_handle.clone()).await
}
/// Create a Yield Future that yields until woken with a signal.
pub async fn yield_until_wake(&self) -> Result<(), Fail> {
Yield::new(None, self.yielder_handle.clone()).await
}
}
//======================================================================================================================
// Trait Implementations
//======================================================================================================================
impl Future for Yield {
type Output = Result<(), Fail>;
/// Polls the underlying accept operation.
fn poll(self: Pin<&mut Self>, context: &mut Context) -> Poll<Self::Output> {
let self_: &mut Self = self.get_mut();
// First check if we've been woken to do some work.
if let Some(result) = self_.yielder_handle.get_result() {
return Poll::Ready(result);
}
// Stash the waker.
self_.yielder_handle.set_waker(context.waker().clone());
// If we are waiting for a fixed quanta, then always wake up.
if let Some(budget) = self_.yield_quanta {
// Add one to our quanta that we've woken up for.
self_.already_yielded += 1;
// If we haven't reached our quanta, wake up and check again.
// TODO: Find a more efficient way to do this than waking up on every quanta.
// See: https://github.com/demikernel/demikernel/issues/560
if self_.already_yielded < budget {
context.waker().wake_by_ref();
} else {
self_.yielder_handle.wake_with(Ok(()));
}
}
Poll::Pending
}
}
| true
|
d667b7b6120d6be07db0d0c3f1db42d5efd1a45a
|
Rust
|
DuncanCasteleyn/07th-mod-python-patcher
|
/install_loader/src/config.rs
|
UTF-8
| 795
| 2.6875
| 3
|
[] |
no_license
|
use crate::windows_utilities;
use imgui::ImString;
use std::path::PathBuf;
// Please define these as paths relative to the current directory
pub struct InstallerConfig {
pub sub_folder: PathBuf,
pub sub_folder_display: ImString,
pub logs_folder: PathBuf,
pub python_path: PathBuf,
pub is_retry: bool,
}
impl InstallerConfig {
pub fn new(root: &PathBuf, is_retry: bool) -> InstallerConfig {
let sub_folder = PathBuf::from(root);
let sub_folder_display = ImString::new(windows_utilities::absolute_path_str(
&sub_folder,
"couldn't determine path",
));
let logs_folder = sub_folder.join("INSTALLER_LOGS");
let python_path = sub_folder.join("python/python.exe");
InstallerConfig {
sub_folder,
sub_folder_display,
logs_folder,
python_path,
is_retry,
}
}
}
| true
|
4b01d6c8c273b25658b46c0e1f2db1c154c4d1ba
|
Rust
|
brunoczim/lockfree
|
/src/channel/spmc.rs
|
UTF-8
| 13,403
| 2.96875
| 3
|
[
"MIT"
] |
permissive
|
pub use super::{
NoRecv,
RecvErr::{self, *},
};
use incin::Pause;
use owned_alloc::OwnedAlloc;
use ptr::{bypass_null, check_null_align};
use removable::Removable;
use std::{
fmt,
ptr::{null_mut, NonNull},
sync::{
atomic::{AtomicPtr, Ordering::*},
Arc,
},
};
/// Creates an asynchronous lock-free Single-Producer-Multi-Consumer (SPMC)
/// channel. In order to allow multiple consumers, [`Receiver`] is clonable and
/// does not require mutability.
pub fn create<T>() -> (Sender<T>, Receiver<T>) {
with_incin(SharedIncin::new())
}
/// Same as [`create`], but use a passed incinerator instead of creating a new
/// one.
pub fn with_incin<T>(incin: SharedIncin<T>) -> (Sender<T>, Receiver<T>) {
check_null_align::<Node<T>>();
// First we create a single node shared between two ends.
let alloc = OwnedAlloc::new(Node {
message: Removable::empty(),
next: AtomicPtr::new(null_mut()),
});
let single_node = alloc.into_raw();
// Then put it on back and on the front.
let sender = Sender { back: single_node };
let receiver = Receiver {
inner: Arc::new(ReceiverInner {
front: AtomicPtr::new(single_node.as_ptr()),
incin,
}),
};
(sender, receiver)
}
/// The [`Sender`] handle of a SPMC channel. Created by [`create`] or
/// [`with_incin`] function.
pub struct Sender<T> {
back: NonNull<Node<T>>,
}
impl<T> Sender<T> {
/// Sends a message and if the receiver disconnected, an error is returned.
pub fn send(&mut self, message: T) -> Result<(), NoRecv<T>> {
// First we allocate the node for our message.
let alloc = OwnedAlloc::new(Node {
message: Removable::new(message),
next: AtomicPtr::new(null_mut()),
});
let nnptr = alloc.into_raw();
// This dereferral is safe because the queue has at least one node. We
// possess a single node in the back, and if the queue has just one
// node, it is stored in the back (and in the front). Also, we are the
// only ones with access to the back.
let res = unsafe {
// We try to update the back's next pointer. We want to catch any
// bit marking here. A marked lower bit means the receiver
// disconnected.
self.back.as_ref().next.compare_exchange(
null_mut(),
nnptr.as_ptr(),
Release,
Relaxed,
)
};
if res.is_ok() {
// If we succeeded, let's update the back so we keep the invariant
// "the back has a single node".
self.back = nnptr;
Ok(())
} else {
// If we failed, receiver disconnected. It is safe to dealloc
// because this is the node we just allocated, and we did not share
// it with anyone (cas failed).
let mut alloc = unsafe { OwnedAlloc::from_raw(nnptr) };
let message = alloc.message.replace(None).unwrap();
Err(NoRecv { message })
}
}
/// Tests if there are any [`Receiver`]s still connected. There are no
/// guarantees that [`send`](Sender::send) will succeed if this method
/// returns `true` because the [`Receiver`] may disconnect meanwhile.
pub fn is_connected(&self) -> bool {
// Safe because we always have at least one node, which is only dropped
// in the last side to disconnect's drop.
let back = unsafe { self.back.as_ref() };
back.next.load(Relaxed).is_null()
}
}
impl<T> Drop for Sender<T> {
fn drop(&mut self) {
// This dereferral is safe because the queue always have at least one
// node. This single node is only dropped when the last side to
// disconnect drops.
let res = unsafe {
// Let's try to mark next's bit so that receiver will see we
// disconnected, if it hasn't disconnected by itself. It is ok to
// just swap, since we have only two possible values (null and
// null | 1) and we everyone will be setting to the same value
// (null | 1).
self.back
.as_ref()
.next
.swap((null_mut::<Node<T>>() as usize | 1) as *mut _, Relaxed)
};
// If the previously stored value was not null, receiver has already
// disconnected. It is safe to drop because we are the only ones that
// have a pointer to the node.
if !res.is_null() {
unsafe { OwnedAlloc::from_raw(self.back) };
}
}
}
impl<T> fmt::Debug for Sender<T> {
fn fmt(&self, fmtr: &mut fmt::Formatter) -> fmt::Result {
fmtr.write_str("spmc::Sender")
}
}
unsafe impl<T> Send for Sender<T> where T: Send {}
unsafe impl<T> Sync for Sender<T> where T: Send {}
/// The [`Receiver`] handle of a SPMC channel. Created by [`create`] or
/// [`with_incin`] function. It is clonable and does not require mutability.
pub struct Receiver<T> {
inner: Arc<ReceiverInner<T>>,
}
impl<T> Receiver<T> {
/// Tries to receive a message. If no message is available,
/// [`Err`]`(`[`RecvErr::NoMessage`]`)` is returned. If the sender
/// disconnected, [`Err`]`(`[`RecvErr::NoSender`]`)` is returned.
#[allow(unused_must_use)]
pub fn recv(&self) -> Result<T, RecvErr> {
// We have to pause the incinerator due to ABA problem. This channel
// suffers from it, yeah.
let pause = self.inner.incin.inner.pause();
// Bypassing null check is safe because we never store null in
// the front.
let mut front_nnptr = unsafe {
// First we load pointer stored in the front.
bypass_null(self.inner.front.load(Relaxed))
};
loop {
// Let's remove the node logically first. Safe to derefer this
// pointer because we paused the incinerator and we only
// delete nodes via incinerator.
match unsafe { front_nnptr.as_ref().message.take(AcqRel) } {
Some(val) => {
// Safe to call because we passed a pointer from the front
// which was loaded during the very same pause we are
// passing.
unsafe { self.try_clear_first(front_nnptr, &pause) };
break Ok(val);
},
// Safe to call because we passed a pointer from the front
// which was loaded during the very same pause we are passing.
None => unsafe {
front_nnptr = self.try_clear_first(front_nnptr, &pause)?;
},
}
}
}
/// Tests if there are any [`Sender`]s still connected. There are no
/// guarantees that [`recv`](Receiver::recv) will succeed if this method
/// returns `true` because the [`Receiver`] may disconnect meanwhile.
/// This method may also return `true` if the [`Sender`] disconnected
/// but there are messages pending in the buffer. Note that another
/// [`Receiver`] may pop out the pending messages after this method was
/// called.
pub fn is_connected(&self) -> bool {
// We need this pause because of use-after-free.
let _pause = self.inner.incin.inner.pause();
// Safe to derefer this pointer because we paused the incinerator and we
// only delete nodes via incinerator.
let front = unsafe { &*self.inner.front.load(Relaxed) };
front.message.is_present(Relaxed)
|| front.next.load(Relaxed) as usize & 1 == 0
}
/// The shared incinerator used by this [`Receiver`].
pub fn incin(&self) -> SharedIncin<T> {
self.inner.incin.clone()
}
// This function is unsafe because passing the wrong pointer will lead to
// undefined behavior. The pointer must have been loaded from the front
// during the passed pause.
unsafe fn try_clear_first(
&self,
expected: NonNull<Node<T>>,
pause: &Pause<OwnedAlloc<Node<T>>>,
) -> Result<NonNull<Node<T>>, RecvErr> {
let next = expected.as_ref().next.load(Acquire);
if next as usize & 1 == 1 {
// If the next is bit flagged, sender disconnected, no more messages
// ever.
Err(RecvErr::NoSender)
} else if next.is_null() {
// No bit flag means sender is still there but we have no message.
Err(RecvErr::NoMessage)
} else {
let ptr = expected.as_ptr();
// We are not oblied to succeed. This is just cleanup and some other
// thread might do it.
let next = match self
.inner
.front
.compare_exchange(ptr, next, Relaxed, Relaxed)
{
Ok(_) => {
// Only deleting nodes via incinerator due to ABA
// problem and use-after-frees.
pause.add_to_incin(OwnedAlloc::from_raw(expected));
next
},
Err(found) => found,
};
// Safe to by-pass the check since we only store non-null
// pointers on the front.
Ok(bypass_null(next))
}
}
}
impl<T> Clone for Receiver<T> {
fn clone(&self) -> Self {
Self { inner: self.inner.clone() }
}
}
impl<T> fmt::Debug for Receiver<T> {
fn fmt(&self, fmtr: &mut fmt::Formatter) -> fmt::Result {
write!(fmtr, "spmc::Receiver {} ptr: {:p} {}", '{', self.inner, '}')
}
}
unsafe impl<T> Send for Receiver<T> where T: Send {}
unsafe impl<T> Sync for Receiver<T> where T: Send {}
struct ReceiverInner<T> {
// never null
front: AtomicPtr<Node<T>>,
incin: SharedIncin<T>,
}
impl<T> Drop for ReceiverInner<T> {
fn drop(&mut self) {
let front = self.front.get_mut();
loop {
// This null-check-by-pass is safe because we never store null in
// the front.
let front_nnptr = unsafe { bypass_null(*front) };
// This is safe because we are the only receiver left and the list
// will always have at least one node, even in the drop. Of course,
// unless we are the last side to drop (then we do drop it all).
let res = unsafe {
// Let's try to mark the next (which means we disconnected). We
// might fail because either this is not the last node or the
// sender already disconnected and marked this pointer.
front_nnptr.as_ref().next.compare_exchange(
null_mut(),
(null_mut::<Node<T>>() as usize | 1) as *mut _,
AcqRel,
Acquire,
)
};
match res {
// If the succeeded, we are the first side to disconnect and we
// must keep at least one node in the queue.
Ok(_) => break,
Err(next) => {
// Ok, safe to deallocate the front now. We already loaded
// the next field and it is not null.
// Either the queue won't be empty or the
// sender disconnected.
unsafe { OwnedAlloc::from_raw(front_nnptr) };
// This means the sender disconnected we reached the end of
// the queue.
if next as usize & 1 == 1 {
break;
}
// Now let's keep going until the list is empty.
*front = next;
},
}
}
}
}
#[repr(align(/* at least */ 2))]
struct Node<T> {
message: Removable<T>,
// lower bit is 1 if the other side disconnected, 0 means nothing
next: AtomicPtr<Node<T>>,
}
make_shared_incin! {
{ "`spmc::Receiver`" }
pub SharedIncin<T> of OwnedAlloc<Node<T>>
}
#[cfg(test)]
mod test {
use channel::spmc;
use std::{
sync::{
atomic::{AtomicBool, Ordering::*},
Arc,
},
thread,
};
#[test]
fn correct_numbers() {
const THREADS: usize = 8;
const MSGS: usize = 512;
let mut done = Vec::with_capacity(MSGS);
for _ in 0 .. MSGS {
done.push(AtomicBool::new(false));
}
let done = Arc::<[AtomicBool]>::from(done);
let (mut sender, receiver) = spmc::create::<usize>();
let mut threads = Vec::with_capacity(THREADS);
for _ in 0 .. THREADS {
let done = done.clone();
let receiver = receiver.clone();
threads.push(thread::spawn(move || loop {
match receiver.recv() {
Ok(i) => assert!(!done[i].swap(true, AcqRel)),
Err(spmc::NoSender) => break,
Err(spmc::NoMessage) => (),
}
}))
}
for i in 0 .. MSGS {
sender.send(i).unwrap();
}
drop(sender);
for thread in threads {
thread.join().unwrap();
}
for status in done.iter() {
assert!(status.load(Relaxed));
}
}
}
| true
|
c1199f8a013d6d03d20d66e0a7fe5528ed6d434c
|
Rust
|
eeeeeta/inebriated-rs-edition
|
/src/rgen.rs
|
UTF-8
| 1,455
| 2.9375
| 3
|
[] |
no_license
|
extern crate rand;
use markov;
use rand::distributions::{Weighted, WeightedChoice, IndependentSample};
pub trait HasWeight {
fn getwt(&self) -> u32;
}
pub fn pick_from_vec<T>(vec: &Vec<T>) -> Option<&T> where T: HasWeight {
match vec.len() {
0 => None,
1 => Some(&vec[0]),
_ => {
let mut items: Vec<Weighted<usize>> = Vec::new();
for (i, ref k) in vec.iter().enumerate() {
items.push(Weighted {
weight: k.getwt(),
item: i
});
}
let wc = WeightedChoice::new(&mut items);
let mut rng = rand::thread_rng();
Some(&vec[wc.ind_sample(&mut rng)])
}
}
}
pub fn pick_from_str<'a, 'b>(str: &'a str, kvdb: &'b markov::KvdbType) -> Option<&'b markov::Key> {
println!("str {}", str);
if let Some(vec) = kvdb.get(str) {
println!("str {} vec {:?}", str, vec);
pick_from_vec(vec)
}
else {
None
}
}
pub fn weight_key(key: &Vec<markov::Key>, kvdb: &markov::KvdbType) -> u32 {
let mut weight = key.len();
let mut vec = key;
while let Some(k) = pick_from_vec(vec) {
if let Some(nvec) = kvdb.get(&k.str) {
if nvec[0].str == vec[0].str {
break;
}
weight += nvec.len();
vec = nvec;
}
else {
break;
}
}
weight as u32
}
| true
|
809505a854aa6072d49afb5cbd71525d64b89905
|
Rust
|
smartbrainisme/queen
|
/test/test_stream_ext.rs
|
UTF-8
| 7,247
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
use std::time::Duration;
use std::thread;
use std::sync::{Arc, Mutex};
use queen::{Queen, Node, Port};
use queen::nson::{msg, MessageId};
use queen::error::{Error, ErrorCode};
use queen::net::CryptoOptions;
use queen::crypto::Method;
use queen::dict::*;
use queen::stream::StreamExt;
use super::get_free_addr;
#[test]
fn stream() {
// start queen
let queen = Queen::new(MessageId::new(), (), None).unwrap();
let stream1 = queen.connect(msg!{}, None, None).unwrap();
let stream2 = queen.connect(msg!{}, None, None).unwrap();
// stream1 auth
let _ = stream1.send(&mut Some(msg!{
CHAN: AUTH
}));
thread::sleep(Duration::from_secs(1));
let recv = stream1.recv().unwrap();
assert!(recv.get_i32(OK).unwrap() == 0);
// stream ext
let stream_ext = StreamExt::new(stream2);
// ping
assert!(stream_ext.ping(msg!{}).is_ok());
// try attach
assert!(matches!(
stream_ext.attach("hello", None),
Err(Error::ErrorCode(ErrorCode::Unauthorized))
));
assert!(!stream_ext.authed());
// auth
assert!(stream_ext.auth(msg!{}).is_ok());
assert!(stream_ext.authed());
// try attach
assert!(stream_ext.attach("hello", None).is_ok());
// recv
let state = Arc::new(Mutex::new(false));
let state2 = state.clone();
stream_ext.recv(move |chan, message| {
if chan == "hello" && message.get_str("hello").unwrap() == "world" {
let mut state = state2.lock().unwrap();
*state = true;
}
});
// stream1 send
let _ = stream1.send(&mut Some(msg!{
CHAN: "hello",
"hello": "world",
ACK: "123"
}));
thread::sleep(Duration::from_secs(1));
let recv = stream1.recv().unwrap();
assert!(recv.get_i32(OK).unwrap() == 0);
// check state
let state2 = state.lock().unwrap();
assert!(*state2 == true);
// stream ext close
stream_ext.close();
thread::sleep(Duration::from_secs(1));
// stream1 send
let _ = stream1.send(&mut Some(msg!{
CHAN: "hello",
"hello": "world",
ACK: "123"
}));
thread::sleep(Duration::from_secs(1));
let recv = stream1.recv().unwrap();
assert!(ErrorCode::has_error(&recv) == Some(ErrorCode::NoConsumers));
}
#[test]
fn stream_over_port() {
// start node
let queen = Queen::new(MessageId::new(), (), None).unwrap();
let addr = get_free_addr();
let mut node = Node::new(
queen.clone(),
2,
vec![addr.parse().unwrap()]
).unwrap();
thread::spawn(move || {
node.run().unwrap();
});
// start stream
let stream1 = queen.connect(msg!{}, None, None).unwrap();
let _ = stream1.send(&mut Some(msg!{
CHAN: AUTH
}));
// start port
let port = Port::new().unwrap();
let stream2 = port.connect(addr, None, None).unwrap();
thread::sleep(Duration::from_secs(1));
// stream1 recv
let recv = stream1.recv().unwrap();
assert!(recv.get_i32(OK).unwrap() == 0);
// stream ext
let stream_ext = StreamExt::new(stream2);
// ping
assert!(stream_ext.ping(msg!{}).is_ok());
// try attach
assert!(matches!(
stream_ext.attach("hello", None),
Err(Error::ErrorCode(ErrorCode::Unauthorized))
));
assert!(!stream_ext.authed());
// auth
assert!(stream_ext.auth(msg!{}).is_ok());
assert!(stream_ext.authed());
// try attach
assert!(stream_ext.attach("hello", None).is_ok());
// recv
let state = Arc::new(Mutex::new(false));
let state2 = state.clone();
stream_ext.recv(move |chan, message| {
if chan == "hello" && message.get_str("hello").unwrap() == "world" {
let mut state = state2.lock().unwrap();
*state = true;
}
});
// stream1 send
let _ = stream1.send(&mut Some(msg!{
CHAN: "hello",
"hello": "world",
ACK: "123"
}));
thread::sleep(Duration::from_secs(1));
let recv = stream1.recv().unwrap();
assert!(recv.get_i32(OK).unwrap() == 0);
// check state
let state2 = state.lock().unwrap();
assert!(*state2 == true);
// stream ext close
stream_ext.close();
thread::sleep(Duration::from_secs(1));
// stream1 send
let _ = stream1.send(&mut Some(msg!{
CHAN: "hello",
"hello": "world",
ACK: "123"
}));
thread::sleep(Duration::from_secs(1));
let recv = stream1.recv().unwrap();
assert!(ErrorCode::has_error(&recv) == Some(ErrorCode::NoConsumers));
}
#[test]
fn stream_over_port_secure() {
// start node
let queen = Queen::new(MessageId::new(), (), None).unwrap();
let addr = get_free_addr();
let mut node = Node::new(
queen.clone(),
2,
vec![addr.parse().unwrap()]
).unwrap();
node.set_access_fn(|key|{
assert!(key == "12d3eaf5e9effffb14fb213e");
Some("99557df09590ad6043ceefd1".to_string())
});
thread::spawn(move || {
node.run().unwrap();
});
// start stream
let stream1 = queen.connect(msg!{}, None, None).unwrap();
let _ = stream1.send(&mut Some(msg!{
CHAN: AUTH
}));
// start port
let port = Port::new().unwrap();
let crypto_options = CryptoOptions {
method: Method::Aes128Gcm,
access: "12d3eaf5e9effffb14fb213e".to_string(),
secret: "99557df09590ad6043ceefd1".to_string()
};
let stream2 = port.connect(addr, Some(crypto_options), None).unwrap();
thread::sleep(Duration::from_secs(1));
// stream1 recv
let recv = stream1.recv().unwrap();
assert!(recv.get_i32(OK).unwrap() == 0);
// stream ext
let stream_ext = StreamExt::new(stream2);
// ping
assert!(stream_ext.ping(msg!{}).is_ok());
// try attach
assert!(matches!(
stream_ext.attach("hello", None),
Err(Error::ErrorCode(ErrorCode::Unauthorized))
));
assert!(!stream_ext.authed());
// auth
assert!(stream_ext.auth(msg!{}).is_ok());
assert!(stream_ext.authed());
// try attach
assert!(stream_ext.attach("hello", None).is_ok());
// recv
let state = Arc::new(Mutex::new(false));
let state2 = state.clone();
stream_ext.recv(move |chan, message| {
if chan == "hello" && message.get_str("hello").unwrap() == "world" {
let mut state = state2.lock().unwrap();
*state = true;
}
});
// stream1 send
let _ = stream1.send(&mut Some(msg!{
CHAN: "hello",
"hello": "world",
ACK: "123"
}));
thread::sleep(Duration::from_secs(1));
let recv = stream1.recv().unwrap();
assert!(recv.get_i32(OK).unwrap() == 0);
// check state
let state2 = state.lock().unwrap();
assert!(*state2 == true);
// stream ext close
stream_ext.close();
thread::sleep(Duration::from_secs(1));
// stream1 send
let _ = stream1.send(&mut Some(msg!{
CHAN: "hello",
"hello": "world",
ACK: "123"
}));
thread::sleep(Duration::from_secs(1));
let recv = stream1.recv().unwrap();
assert!(ErrorCode::has_error(&recv) == Some(ErrorCode::NoConsumers));
}
| true
|
ba6658fed022c030ef995ecb7e6bc1863b07e482
|
Rust
|
Kha/elan
|
/src/elan-dist/src/manifest.rs
|
UTF-8
| 1,217
| 3.09375
| 3
|
[
"Apache-2.0"
] |
permissive
|
//! Lean distribution v2 manifests.
//!
//! This manifest describes the distributable artifacts for a single
//! release of Lean. They are toml files, typically downloaded from
//! e.g. static.lean-lang.org/dist/channel-lean-nightly.toml. They
//! describe where to download, for all platforms, each component of
//! the a release, and their relationships to each other.
//!
//! Installers use this info to customize Lean installations.
//!
//! See tests/channel-lean-nightly-example.toml for an example.
use elan_utils::toml_utils::*;
use errors::*;
use toml;
#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct Component {
pub pkg: String,
}
impl Component {
pub fn from_toml(mut table: toml::value::Table, path: &str) -> Result<Self> {
Ok(Component {
pkg: get_string(&mut table, "pkg", path)?,
})
}
pub fn to_toml(self) -> toml::value::Table {
let mut result = toml::value::Table::new();
result.insert("pkg".to_owned(), toml::Value::String(self.pkg));
result
}
pub fn name(&self) -> String {
format!("{}", self.pkg)
}
pub fn description(&self) -> String {
format!("'{}'", self.pkg)
}
}
| true
|
982cd0ff814ceb9241fa7142661650068d344b2a
|
Rust
|
peter-fomin/rust-playground
|
/rna-transcription/src/lib.rs
|
UTF-8
| 1,636
| 3.375
| 3
|
[] |
no_license
|
#[derive(Debug, PartialEq)]
pub struct DNA;
#[derive(Debug, PartialEq)]
pub struct RNA;
#[derive(Debug, PartialEq)]
pub struct NucleicAcid {
sequence: Vec<char>,
acid: Acid,
}
#[derive(Debug, PartialEq)]
pub enum Acid {
DNA,
RNA,
}
impl DNA {
pub fn new(sequence: &str) -> Result<NucleicAcid, usize> {
NucleicAcid::new(sequence, Acid::DNA)
}
}
impl RNA {
pub fn new(sequence: &str) -> Result<NucleicAcid, usize> {
NucleicAcid::new(sequence, Acid::RNA)
}
}
impl Acid {
fn nucleotides(&self) -> &'static [char] {
// Arrays have to be in transcription order.
match self {
Self::DNA => &['A', 'C', 'T', 'G'],
// Transcribes: v v v v
Self::RNA => &['U', 'G', 'A', 'C'],
}
}
fn nucleotide_to_rna(nuc: &mut char) {
// Transcribes one nucleotide according to the order in nucleotides() fn.
*nuc = Acid::RNA.nucleotides()[Acid::DNA
.nucleotides()
.iter()
.position(|c| c == nuc)
.unwrap()];
}
}
impl NucleicAcid {
pub fn new(sequence: &str, acid: Acid) -> Result<Self, usize> {
match sequence
.chars()
.position(|c| !acid.nucleotides().contains(&c))
{
Some(position) => Err(position),
None => Ok(Self {
sequence: sequence.chars().collect(),
acid,
}),
}
}
pub fn into_rna(mut self) -> Self {
self.sequence.iter_mut().for_each(Acid::nucleotide_to_rna);
self.acid = Acid::RNA;
self
}
}
| true
|
87871a2d84e90ba38cd6a63d3d56227fa43cf215
|
Rust
|
leshow/exercism
|
/hackerrank/src/simple_text_editor.rs
|
UTF-8
| 1,851
| 3.15625
| 3
|
[] |
no_license
|
use crate::scanner::*;
use std::io::{self, BufWriter, Write};
#[derive(Clone, Debug)]
enum Op<T> {
Append { value: T },
Del { idx: usize },
Print { idx: usize },
Undo,
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut scan = Scanner::default();
let out = &mut BufWriter::new(io::stdout());
let len = scan.next::<usize>();
let ops = (0..len)
.map(|_| {
let op = scan.next::<usize>();
match op {
1 => {
let value = scan.next::<String>().into_bytes();
Op::Append { value }
}
2 => {
let idx = scan.next::<usize>();
Op::Del { idx }
}
3 => {
let idx = scan.next::<usize>();
Op::Print { idx }
}
4 => Op::Undo,
_ => panic!("unknown op"),
}
})
.collect::<Vec<_>>();
edit(ops, out);
Ok(())
}
fn edit<W>(ops: Vec<Op<Vec<u8>>>, out: &mut BufWriter<W>)
where
W: Write,
{
let mut s: Vec<u8> = Vec::new();
let mut stack: Vec<Vec<u8>> = Vec::new();
for op in ops {
match op {
Op::Append { value } => {
stack.push(s.clone());
s.extend(&value);
}
Op::Del { idx } => {
stack.push(s.clone());
(0..idx).for_each(|_| {
let _ = s.pop();
});
}
Op::Print { idx } => {
writeln!(out, "{}", s[idx - 1] as char).expect("failed to write");
}
Op::Undo => {
if let Some(last_s) = stack.pop() {
s = last_s;
}
}
}
}
}
| true
|
43e1e5487a4d000ae5a50eca737729b898f90cbc
|
Rust
|
sweisser/rust-serverless-example
|
/src/main.rs
|
UTF-8
| 1,856
| 2.953125
| 3
|
[] |
no_license
|
use lambda_runtime::{Context, error::HandlerError};
use lambda_http::{lambda, Request, IntoResponse, RequestExt};
use serde_derive::{Serialize, Deserialize};
use serde_json::json;
use rust_serverless_example::{ compute_holidays, Holidays };
use std::fmt;
fn main() {
lambda!(handler)
}
fn handler(
request: Request,
_ctx: Context
) -> Result<impl IntoResponse, HandlerError> {
match request.payload::<MyRequest>() {
Ok(req) => {
match req {
Some(req_ok) => {
// All parsing went okay.
let r = MyResponse {
version: String::from("1.0"),
holidays: compute_holidays(req_ok.year),
};
Ok(json!(r))
},
None => {
Err(HandlerError::new(MyError::new("Error deserializing the request. Maybe some fields missing?")))
}
}
},
Err(_e) => {
Err(HandlerError::new(MyError::new("Error parsing the request (must be POST with Content-Type: application/json).")))
}
}
}
#[derive(Debug, Deserialize, Default)]
struct MyRequest {
#[serde(default)]
year: i32,
}
#[derive(Serialize)]
struct MyResponse {
version: String,
holidays: Holidays,
}
#[derive(Serialize, Debug, Clone)]
struct MyError {
errormessage: String,
}
impl MyError {
pub fn new(msg: &str) -> MyError {
MyError {
errormessage: String::from(msg)
}
}
}
impl fmt::Display for MyError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.errormessage)
}
}
impl std::error::Error for MyError {}
impl lambda_runtime::error::LambdaErrorExt for MyError {
fn error_type(&self) -> &str {
"MyError"
}
}
| true
|
e3cf9be3fed198fdb82764bfc371b29cf176be0c
|
Rust
|
DougLau/pix
|
/src/rgb.rs
|
UTF-8
| 9,907
| 3.265625
| 3
|
[
"Apache-2.0",
"MIT"
] |
permissive
|
// rgb.rs RGB color model.
//
// Copyright (c) 2018-2022 Douglas P Lau
// Copyright (c) 2019-2020 Jeron Aldaron Lau
//
//! [RGB] color model and types.
//!
//! [rgb]: https://en.wikipedia.org/wiki/RGB_color_model
use crate::chan::{Ch16, Ch32, Ch8, Linear, Premultiplied, Srgb, Straight};
use crate::el::{Pix3, Pix4, PixRgba, Pixel};
use crate::ColorModel;
use std::ops::Range;
/// [RGB] additive [color model].
///
/// The components are *[red]*, *[green]*, *[blue]* and optional *[alpha]*.
///
/// [alpha]: ../el/trait.Pixel.html#method.alpha
/// [blue]: #method.blue
/// [color model]: ../trait.ColorModel.html
/// [green]: #method.green
/// [red]: #method.red
/// [rgb]: https://en.wikipedia.org/wiki/RGB_color_model
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Rgb {}
impl Rgb {
/// Get the *red* component.
///
/// # Example: RGB Red
/// ```
/// use pix::chan::Ch32;
/// use pix::rgb::{Rgb, Rgb32};
///
/// let p = Rgb32::new(0.25, 0.5, 1.0);
/// assert_eq!(Rgb::red(p), Ch32::new(0.25));
/// ```
pub fn red<P: Pixel>(p: P) -> P::Chan
where
P: Pixel<Model = Self>,
{
p.one()
}
/// Get a mutable reference to the *red* component.
///
/// # Example: Modify RGB Red
/// ```
/// use pix::chan::Ch32;
/// use pix::rgb::{Rgb, Rgb32};
///
/// let mut p = Rgb32::new(0.25, 0.5, 1.0);
/// *Rgb::red_mut(&mut p) = Ch32::new(0.75);
/// assert_eq!(Rgb::red(p), Ch32::new(0.75));
/// ```
pub fn red_mut<P: Pixel>(p: &mut P) -> &mut P::Chan
where
P: Pixel<Model = Self>,
{
p.one_mut()
}
/// Get the *green* component.
///
/// # Example: RGB Green
/// ```
/// use pix::chan::Ch16;
/// use pix::rgb::{Rgb, Rgb16};
///
/// let p = Rgb16::new(0x2000, 0x1234, 0x8000);
/// assert_eq!(Rgb::green(p), Ch16::new(0x1234));
/// ```
pub fn green<P: Pixel>(p: P) -> P::Chan
where
P: Pixel<Model = Self>,
{
p.two()
}
/// Get a mutable reference to the *green* component.
///
/// # Example: Modify RGB Green
/// ```
/// use pix::chan::Ch16;
/// use pix::rgb::{Rgb, Rgb16};
///
/// let mut p = Rgb16::new(0x2000, 0x1234, 0x8000);
/// *Rgb::green_mut(&mut p) = 0x4321.into();
/// assert_eq!(Rgb::green(p), Ch16::new(0x4321));
/// ```
pub fn green_mut<P: Pixel>(p: &mut P) -> &mut P::Chan
where
P: Pixel<Model = Self>,
{
p.two_mut()
}
/// Get the *blue* component.
///
/// # Example: RGB Blue
/// ```
/// use pix::chan::Ch8;
/// use pix::rgb::{Rgb, Rgb8};
///
/// let p = Rgb8::new(0x93, 0x80, 0xA0);
/// assert_eq!(Rgb::blue(p), Ch8::new(0xA0));
/// ```
pub fn blue<P: Pixel>(p: P) -> P::Chan
where
P: Pixel<Model = Self>,
{
p.three()
}
/// Get a mutable reference to the *blue* component.
///
/// # Example: Modify RGB Blue
/// ```
/// use pix::chan::Ch8;
/// use pix::rgb::{Rgb, Rgb8};
///
/// let mut p = Rgb8::new(0x88, 0x77, 0x66);
/// *Rgb::blue_mut(&mut p) = 0x55.into();
/// assert_eq!(Rgb::blue(p), Ch8::new(0x55));
/// ```
pub fn blue_mut<P: Pixel>(p: &mut P) -> &mut P::Chan
where
P: Pixel<Model = Self>,
{
p.three_mut()
}
/// Get channel-wise difference
pub fn difference<P: Pixel>(p: P, rhs: P) -> P
where
P: Pixel<Model = Self>,
{
let red = if Self::red(p) > Self::red(rhs) {
Self::red(p) - Self::red(rhs)
} else {
Self::red(rhs) - Self::red(p)
};
let green = if Self::green(p) > Self::green(rhs) {
Self::green(p) - Self::green(rhs)
} else {
Self::green(rhs) - Self::green(p)
};
let blue = if Self::blue(p) > Self::blue(rhs) {
Self::blue(p) - Self::blue(rhs)
} else {
Self::blue(rhs) - Self::blue(p)
};
let alpha = if Pixel::alpha(p) > Pixel::alpha(rhs) {
Pixel::alpha(p) - Pixel::alpha(rhs)
} else {
Pixel::alpha(rhs) - Pixel::alpha(p)
};
P::from_channels(&[red, green, blue, alpha])
}
/// Check if all `Channel`s are within threshold
pub fn within_threshold<P: Pixel>(p: P, rhs: P) -> bool
where
P: Pixel<Model = Self>,
{
Self::red(p) <= Self::red(rhs)
&& Self::green(p) <= Self::green(rhs)
&& Self::blue(p) <= Self::blue(rhs)
&& Pixel::alpha(p) <= Pixel::alpha(rhs)
}
}
impl ColorModel for Rgb {
const CIRCULAR: Range<usize> = 0..0;
const LINEAR: Range<usize> = 0..3;
const ALPHA: usize = 3;
/// Convert into *red*, *green*, *blue* and *alpha* components
fn into_rgba<P>(p: P) -> PixRgba<P>
where
P: Pixel<Model = Self>,
{
let red = Rgb::red(p);
let green = Rgb::green(p);
let blue = Rgb::blue(p);
PixRgba::<P>::new::<P::Chan>(red, green, blue, p.alpha())
}
/// Convert from *red*, *green*, *blue* and *alpha* components
fn from_rgba<P>(rgba: PixRgba<P>) -> P
where
P: Pixel<Model = Self>,
{
P::from_channels(rgba.channels())
}
}
/// [Rgb](struct.Rgb.html) 8-bit opaque (no *alpha* channel)
/// [linear](../chan/struct.Linear.html) gamma [pixel](../el/trait.Pixel.html)
/// format.
pub type Rgb8 = Pix3<Ch8, Rgb, Straight, Linear>;
/// [Rgb](struct.Rgb.html) 16-bit opaque (no *alpha* channel)
/// [linear](../chan/struct.Linear.html) gamma [pixel](../el/trait.Pixel.html)
/// format.
pub type Rgb16 = Pix3<Ch16, Rgb, Straight, Linear>;
/// [Rgb](struct.Rgb.html) 32-bit opaque (no *alpha* channel)
/// [linear](../chan/struct.Linear.html) gamma [pixel](../el/trait.Pixel.html)
/// format.
pub type Rgb32 = Pix3<Ch32, Rgb, Straight, Linear>;
/// [Rgb](struct.Rgb.html) 8-bit [straight](../chan/struct.Straight.html)
/// alpha [linear](../chan/struct.Linear.html) gamma
/// [pixel](../el/trait.Pixel.html) format.
pub type Rgba8 = Pix4<Ch8, Rgb, Straight, Linear>;
/// [Rgb](struct.Rgb.html) 16-bit [straight](../chan/struct.Straight.html)
/// alpha [linear](../chan/struct.Linear.html) gamma
/// [pixel](../el/trait.Pixel.html) format.
pub type Rgba16 = Pix4<Ch16, Rgb, Straight, Linear>;
/// [Rgb](struct.Rgb.html) 32-bit [straight](../chan/struct.Straight.html)
/// alpha [linear](../chan/struct.Linear.html) gamma
/// [pixel](../el/trait.Pixel.html) format.
pub type Rgba32 = Pix4<Ch32, Rgb, Straight, Linear>;
/// [Rgb](struct.Rgb.html) 8-bit
/// [premultiplied](../chan/struct.Premultiplied.html) alpha
/// [linear](../chan/struct.Linear.html) gamma [pixel](../el/trait.Pixel.html)
/// format.
pub type Rgba8p = Pix4<Ch8, Rgb, Premultiplied, Linear>;
/// [Rgb](struct.Rgb.html) 16-bit
/// [premultiplied](../chan/struct.Premultiplied.html) alpha
/// [linear](../chan/struct.Linear.html) gamma [pixel](../el/trait.Pixel.html)
/// format.
pub type Rgba16p = Pix4<Ch16, Rgb, Premultiplied, Linear>;
/// [Rgb](struct.Rgb.html) 32-bit
/// [premultiplied](../chan/struct.Premultiplied.html) alpha
/// [linear](../chan/struct.Linear.html) gamma [pixel](../el/trait.Pixel.html)
/// format.
pub type Rgba32p = Pix4<Ch32, Rgb, Premultiplied, Linear>;
/// [Rgb](struct.Rgb.html) 8-bit opaque (no *alpha* channel)
/// [sRGB](../chan/struct.Srgb.html) gamma [pixel](../el/trait.Pixel.html)
/// format.
pub type SRgb8 = Pix3<Ch8, Rgb, Straight, Srgb>;
/// [Rgb](struct.Rgb.html) 16-bit opaque (no *alpha* channel)
/// [sRGB](../chan/struct.Srgb.html) gamma [pixel](../el/trait.Pixel.html)
/// format.
pub type SRgb16 = Pix3<Ch16, Rgb, Straight, Srgb>;
/// [Rgb](struct.Rgb.html) 32-bit opaque (no *alpha* channel)
/// [sRGB](../chan/struct.Srgb.html) gamma [pixel](../el/trait.Pixel.html)
/// format.
pub type SRgb32 = Pix3<Ch32, Rgb, Straight, Srgb>;
/// [Rgb](struct.Rgb.html) 8-bit [straight](../chan/struct.Straight.html)
/// alpha [sRGB](../chan/struct.Srgb.html) gamma [pixel](../el/trait.Pixel.html)
/// format.
pub type SRgba8 = Pix4<Ch8, Rgb, Straight, Srgb>;
/// [Rgb](struct.Rgb.html) 16-bit [straight](../chan/struct.Straight.html)
/// alpha [sRGB](../chan/struct.Srgb.html) gamma [pixel](../el/trait.Pixel.html)
/// format.
pub type SRgba16 = Pix4<Ch16, Rgb, Straight, Srgb>;
/// [Rgb](struct.Rgb.html) 32-bit [straight](../chan/struct.Straight.html)
/// alpha [sRGB](../chan/struct.Srgb.html) gamma [pixel](../el/trait.Pixel.html)
/// format.
pub type SRgba32 = Pix4<Ch32, Rgb, Straight, Srgb>;
/// [Rgb](struct.Rgb.html) 8-bit
/// [premultiplied](../chan/struct.Premultiplied.html) alpha
/// [sRGB](../chan/struct.Srgb.html) gamma [pixel](../el/trait.Pixel.html)
/// format.
pub type SRgba8p = Pix4<Ch8, Rgb, Premultiplied, Srgb>;
/// [Rgb](struct.Rgb.html) 16-bit
/// [premultiplied](../chan/struct.Premultiplied.html) alpha
/// [sRGB](../chan/struct.Srgb.html) gamma [pixel](../el/trait.Pixel.html)
/// format.
pub type SRgba16p = Pix4<Ch16, Rgb, Premultiplied, Srgb>;
/// [Rgb](struct.Rgb.html) 32-bit
/// [premultiplied](../chan/struct.Premultiplied.html) alpha
/// [sRGB](../chan/struct.Srgb.html) gamma [pixel](../el/trait.Pixel.html)
/// format.
pub type SRgba32p = Pix4<Ch32, Rgb, Premultiplied, Srgb>;
#[cfg(test)]
mod tests {
use crate::el::Pixel;
use crate::ops::SrcOver;
use crate::rgb::*;
#[test]
fn rgba8_transparent() {
let mut dst = Rgba8p::new(0, 0, 0, 0);
let src = Rgba8p::new(20, 40, 80, 160);
dst.composite_channels(&src, SrcOver);
assert_eq!(dst, src);
dst.composite_channels(&Rgba8p::new(0, 0, 0, 0), SrcOver);
assert_eq!(dst, src);
dst = Rgba8p::new(0xFF, 0xFF, 0xFF, 0x00);
dst.composite_channels(&Rgba8p::new(0, 0, 0, 0), SrcOver);
assert_eq!(dst, Rgba8p::new(0xFF, 0xFF, 0xFF, 0x00));
}
}
| true
|
2666d2c25a49b971cfde52335fa57432ec049eda
|
Rust
|
Azure/azure-sdk-for-rust
|
/services/mgmt/maps/src/package_preview_2020_02/models.rs
|
UTF-8
| 22,791
| 2.703125
| 3
|
[
"LicenseRef-scancode-generic-cla",
"MIT",
"LGPL-2.1-or-later"
] |
permissive
|
#![allow(non_camel_case_types)]
#![allow(unused_imports)]
use serde::de::{value, Deserializer, IntoDeserializer};
use serde::{Deserialize, Serialize, Serializer};
use std::str::FromStr;
#[doc = "An Azure resource which represents Maps Creator product and provides ability to manage private location data."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Creator {
#[serde(flatten)]
pub tracked_resource: TrackedResource,
#[doc = "Creator resource properties"]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<CreatorProperties>,
}
impl Creator {
pub fn new(tracked_resource: TrackedResource) -> Self {
Self {
tracked_resource,
properties: None,
}
}
}
#[doc = "Parameters used to create a new Maps Creator resource."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CreatorCreateParameters {
#[doc = "The location of the resource."]
pub location: String,
#[doc = "Gets or sets a list of key value pairs that describe the resource. These tags can be used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can be provided for a resource. Each tag must have a key no greater than 128 characters and value no greater than 256 characters."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
}
impl CreatorCreateParameters {
pub fn new(location: String) -> Self {
Self { location, tags: None }
}
}
#[doc = "A list of Creator resources."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct CreatorList {
#[doc = "a Creator account."]
#[serde(
default,
deserialize_with = "azure_core::util::deserialize_null_as_default",
skip_serializing_if = "Vec::is_empty"
)]
pub value: Vec<Creator>,
}
impl azure_core::Continuable for CreatorList {
type Continuation = String;
fn continuation(&self) -> Option<Self::Continuation> {
None
}
}
impl CreatorList {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "Creator resource properties"]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct CreatorProperties {
#[doc = "The state of the resource provisioning, terminal states: Succeeded, Failed, Canceled"]
#[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")]
pub provisioning_state: Option<String>,
}
impl CreatorProperties {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "Parameters used to update an existing Creator resource."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct CreatorUpdateParameters {
#[doc = "Gets or sets a list of key value pairs that describe the resource. These tags can be used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can be provided for a resource. Each tag must have a key no greater than 128 characters and value no greater than 256 characters."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
}
impl CreatorUpdateParameters {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "The resource management error additional info."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct ErrorAdditionalInfo {
#[doc = "The additional info type."]
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
#[doc = "The additional info."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub info: Option<serde_json::Value>,
}
impl ErrorAdditionalInfo {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "The error detail."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct ErrorDetail {
#[doc = "The error code."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub code: Option<String>,
#[doc = "The error message."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
#[doc = "The error target."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub target: Option<String>,
#[doc = "The error details."]
#[serde(
default,
deserialize_with = "azure_core::util::deserialize_null_as_default",
skip_serializing_if = "Vec::is_empty"
)]
pub details: Vec<ErrorDetail>,
#[doc = "The error additional info."]
#[serde(
rename = "additionalInfo",
default,
deserialize_with = "azure_core::util::deserialize_null_as_default",
skip_serializing_if = "Vec::is_empty"
)]
pub additional_info: Vec<ErrorAdditionalInfo>,
}
impl ErrorDetail {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "Common error response for all Azure Resource Manager APIs to return error details for failed operations. (This also follows the OData error response format.)."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct ErrorResponse {
#[doc = "The error detail."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error: Option<ErrorDetail>,
}
impl azure_core::Continuable for ErrorResponse {
type Continuation = String;
fn continuation(&self) -> Option<Self::Continuation> {
None
}
}
impl ErrorResponse {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "An Azure resource which represents access to a suite of Maps REST APIs."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MapsAccount {
#[serde(flatten)]
pub tracked_resource: TrackedResource,
#[doc = "The SKU of the Maps Account."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sku: Option<Sku>,
#[doc = "Metadata pertaining to creation and last modification of the resource."]
#[serde(rename = "systemData", default, skip_serializing_if = "Option::is_none")]
pub system_data: Option<SystemData>,
#[doc = "Additional Map account properties"]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<MapsAccountProperties>,
}
impl MapsAccount {
pub fn new(tracked_resource: TrackedResource) -> Self {
Self {
tracked_resource,
sku: None,
system_data: None,
properties: None,
}
}
}
#[doc = "Parameters used to create a new Maps Account."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MapsAccountCreateParameters {
#[doc = "The location of the resource."]
pub location: String,
#[doc = "Gets or sets a list of key value pairs that describe the resource. These tags can be used in viewing and grouping this resource (across resource groups). Each tag must have a key no greater than 128 characters and value no greater than 256 characters."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
#[doc = "The SKU of the Maps Account."]
pub sku: Sku,
}
impl MapsAccountCreateParameters {
pub fn new(location: String, sku: Sku) -> Self {
Self { location, tags: None, sku }
}
}
#[doc = "The set of keys which can be used to access the Maps REST APIs. Two keys are provided for key rotation without interruption."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct MapsAccountKeys {
#[doc = "The full Azure resource identifier of the Maps Account."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[doc = "The primary key for accessing the Maps REST APIs."]
#[serde(rename = "primaryKey", default, skip_serializing_if = "Option::is_none")]
pub primary_key: Option<String>,
#[doc = "The secondary key for accessing the Maps REST APIs."]
#[serde(rename = "secondaryKey", default, skip_serializing_if = "Option::is_none")]
pub secondary_key: Option<String>,
}
impl MapsAccountKeys {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "Additional Map account properties"]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct MapsAccountProperties {
#[doc = "A unique identifier for the maps account"]
#[serde(rename = "x-ms-client-id", default, skip_serializing_if = "Option::is_none")]
pub x_ms_client_id: Option<String>,
}
impl MapsAccountProperties {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "Parameters used to update an existing Maps Account."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct MapsAccountUpdateParameters {
#[doc = "Gets or sets a list of key value pairs that describe the resource. These tags can be used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can be provided for a resource. Each tag must have a key no greater than 128 characters and value no greater than 256 characters."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
#[doc = "The SKU of the Maps Account."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sku: Option<Sku>,
}
impl MapsAccountUpdateParameters {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "A list of Maps Accounts."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct MapsAccounts {
#[doc = "a Maps Account."]
#[serde(
default,
deserialize_with = "azure_core::util::deserialize_null_as_default",
skip_serializing_if = "Vec::is_empty"
)]
pub value: Vec<MapsAccount>,
}
impl azure_core::Continuable for MapsAccounts {
type Continuation = String;
fn continuation(&self) -> Option<Self::Continuation> {
None
}
}
impl MapsAccounts {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "Whether the operation refers to the primary or secondary key."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MapsKeySpecification {
#[doc = "Whether the operation refers to the primary or secondary key."]
#[serde(rename = "keyType")]
pub key_type: maps_key_specification::KeyType,
}
impl MapsKeySpecification {
pub fn new(key_type: maps_key_specification::KeyType) -> Self {
Self { key_type }
}
}
pub mod maps_key_specification {
use super::*;
#[doc = "Whether the operation refers to the primary or secondary key."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(remote = "KeyType")]
pub enum KeyType {
#[serde(rename = "primary")]
Primary,
#[serde(rename = "secondary")]
Secondary,
#[serde(skip_deserializing)]
UnknownValue(String),
}
impl FromStr for KeyType {
type Err = value::Error;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Self::deserialize(s.into_deserializer())
}
}
impl<'de> Deserialize<'de> for KeyType {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
let deserialized = Self::from_str(&s).unwrap_or(Self::UnknownValue(s));
Ok(deserialized)
}
}
impl Serialize for KeyType {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
match self {
Self::Primary => serializer.serialize_unit_variant("KeyType", 0u32, "primary"),
Self::Secondary => serializer.serialize_unit_variant("KeyType", 1u32, "secondary"),
Self::UnknownValue(s) => serializer.serialize_str(s.as_str()),
}
}
}
}
#[doc = "The set of operations available for Maps."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct MapsOperations {
#[doc = "An operation available for Maps."]
#[serde(
default,
deserialize_with = "azure_core::util::deserialize_null_as_default",
skip_serializing_if = "Vec::is_empty"
)]
pub value: Vec<serde_json::Value>,
}
impl azure_core::Continuable for MapsOperations {
type Continuation = String;
fn continuation(&self) -> Option<Self::Continuation> {
None
}
}
impl MapsOperations {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "An Azure resource which represents which will provision the ability to create private location data."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PrivateAtlas {
#[serde(flatten)]
pub tracked_resource: TrackedResource,
#[doc = "Private Atlas resource properties"]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<PrivateAtlasProperties>,
}
impl PrivateAtlas {
pub fn new(tracked_resource: TrackedResource) -> Self {
Self {
tracked_resource,
properties: None,
}
}
}
#[doc = "Parameters used to create a new Private Atlas resource."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PrivateAtlasCreateParameters {
#[doc = "The location of the resource."]
pub location: String,
#[doc = "Gets or sets a list of key value pairs that describe the resource. These tags can be used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can be provided for a resource. Each tag must have a key no greater than 128 characters and value no greater than 256 characters."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
}
impl PrivateAtlasCreateParameters {
pub fn new(location: String) -> Self {
Self { location, tags: None }
}
}
#[doc = "A list of Private Atlas resources."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct PrivateAtlasList {
#[doc = "a Private Atlas."]
#[serde(
default,
deserialize_with = "azure_core::util::deserialize_null_as_default",
skip_serializing_if = "Vec::is_empty"
)]
pub value: Vec<PrivateAtlas>,
}
impl azure_core::Continuable for PrivateAtlasList {
type Continuation = String;
fn continuation(&self) -> Option<Self::Continuation> {
None
}
}
impl PrivateAtlasList {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "Private Atlas resource properties"]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct PrivateAtlasProperties {
#[doc = "The state of the resource provisioning, terminal states: Succeeded, Failed, Canceled"]
#[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")]
pub provisioning_state: Option<String>,
}
impl PrivateAtlasProperties {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "Parameters used to update an existing Private Atlas resource."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct PrivateAtlasUpdateParameters {
#[doc = "Gets or sets a list of key value pairs that describe the resource. These tags can be used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can be provided for a resource. Each tag must have a key no greater than 128 characters and value no greater than 256 characters."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
}
impl PrivateAtlasUpdateParameters {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "Common fields that are returned in the response for all Azure Resource Manager resources"]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct Resource {
#[doc = "Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}"]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[doc = "The name of the resource"]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[doc = "The type of the resource. E.g. \"Microsoft.Compute/virtualMachines\" or \"Microsoft.Storage/storageAccounts\""]
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
}
impl Resource {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "The SKU of the Maps Account."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Sku {
#[doc = "The name of the SKU, in standard format (such as S0)."]
pub name: String,
#[doc = "Gets the sku tier. This is based on the SKU name."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tier: Option<String>,
}
impl Sku {
pub fn new(name: String) -> Self {
Self { name, tier: None }
}
}
#[doc = "The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' and a 'location'"]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TrackedResource {
#[serde(flatten)]
pub resource: Resource,
#[doc = "Resource tags."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
#[doc = "The geo-location where the resource lives"]
pub location: String,
}
impl TrackedResource {
pub fn new(location: String) -> Self {
Self {
resource: Resource::default(),
tags: None,
location,
}
}
}
#[doc = "Metadata pertaining to creation and last modification of the resource."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct SystemData {
#[doc = "The identity that created the resource."]
#[serde(rename = "createdBy", default, skip_serializing_if = "Option::is_none")]
pub created_by: Option<String>,
#[doc = "The type of identity that created the resource."]
#[serde(rename = "createdByType", default, skip_serializing_if = "Option::is_none")]
pub created_by_type: Option<system_data::CreatedByType>,
#[doc = "The timestamp of resource creation (UTC)."]
#[serde(rename = "createdAt", default, with = "azure_core::date::rfc3339::option")]
pub created_at: Option<time::OffsetDateTime>,
#[doc = "The identity that last modified the resource."]
#[serde(rename = "lastModifiedBy", default, skip_serializing_if = "Option::is_none")]
pub last_modified_by: Option<String>,
#[doc = "The type of identity that last modified the resource."]
#[serde(rename = "lastModifiedByType", default, skip_serializing_if = "Option::is_none")]
pub last_modified_by_type: Option<system_data::LastModifiedByType>,
#[doc = "The timestamp of resource last modification (UTC)"]
#[serde(rename = "lastModifiedAt", default, with = "azure_core::date::rfc3339::option")]
pub last_modified_at: Option<time::OffsetDateTime>,
}
impl SystemData {
pub fn new() -> Self {
Self::default()
}
}
pub mod system_data {
use super::*;
#[doc = "The type of identity that created the resource."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(remote = "CreatedByType")]
pub enum CreatedByType {
User,
Application,
ManagedIdentity,
Key,
#[serde(skip_deserializing)]
UnknownValue(String),
}
impl FromStr for CreatedByType {
type Err = value::Error;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Self::deserialize(s.into_deserializer())
}
}
impl<'de> Deserialize<'de> for CreatedByType {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
let deserialized = Self::from_str(&s).unwrap_or(Self::UnknownValue(s));
Ok(deserialized)
}
}
impl Serialize for CreatedByType {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
match self {
Self::User => serializer.serialize_unit_variant("CreatedByType", 0u32, "User"),
Self::Application => serializer.serialize_unit_variant("CreatedByType", 1u32, "Application"),
Self::ManagedIdentity => serializer.serialize_unit_variant("CreatedByType", 2u32, "ManagedIdentity"),
Self::Key => serializer.serialize_unit_variant("CreatedByType", 3u32, "Key"),
Self::UnknownValue(s) => serializer.serialize_str(s.as_str()),
}
}
}
#[doc = "The type of identity that last modified the resource."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(remote = "LastModifiedByType")]
pub enum LastModifiedByType {
User,
Application,
ManagedIdentity,
Key,
#[serde(skip_deserializing)]
UnknownValue(String),
}
impl FromStr for LastModifiedByType {
type Err = value::Error;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Self::deserialize(s.into_deserializer())
}
}
impl<'de> Deserialize<'de> for LastModifiedByType {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
let deserialized = Self::from_str(&s).unwrap_or(Self::UnknownValue(s));
Ok(deserialized)
}
}
impl Serialize for LastModifiedByType {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
match self {
Self::User => serializer.serialize_unit_variant("LastModifiedByType", 0u32, "User"),
Self::Application => serializer.serialize_unit_variant("LastModifiedByType", 1u32, "Application"),
Self::ManagedIdentity => serializer.serialize_unit_variant("LastModifiedByType", 2u32, "ManagedIdentity"),
Self::Key => serializer.serialize_unit_variant("LastModifiedByType", 3u32, "Key"),
Self::UnknownValue(s) => serializer.serialize_str(s.as_str()),
}
}
}
}
| true
|
f676b371980e88e3d9aec1259071369df32ce70b
|
Rust
|
seanpianka/leetcode-rust
|
/src/data_structure/heap/top_k_frequent_elements.rs
|
UTF-8
| 3,269
| 3.71875
| 4
|
[] |
no_license
|
//! https://leetcode.com/problems/top-k-frequent-elements/
//! 解题思路类似: <https://leetcode.com/problems/kth-largest-element-in-a-stream/>
/// return [num for num, _ in collections.Counter(nums).most_common(k)]
fn top_k_frequent_elements(nums: Vec<i32>, k: i32) -> Vec<i32> {
let k = k as usize;
let n = nums.len();
let mut counter = std::collections::HashMap::<i32, i32>::with_capacity(n);
for &num in &nums {
*counter.entry(num).or_default() += 1;
}
// 小根堆: (-出现次数, 数字),所以堆顶会是出现次数最低的数字,随时可以被别人挤掉
let mut heap = std::collections::BinaryHeap::<(i32, i32)>::with_capacity(k);
for (&num, &cnt) in &counter {
if heap.len() == k {
if -cnt < heap.peek().unwrap().0 {
heap.pop();
heap.push((-cnt, num));
}
} else {
heap.push((-cnt, num));
}
}
heap.into_iter().rev().map(|(_, num)| num).collect()
}
/// https://leetcode.com/problems/top-k-frequent-words/
fn top_k_frequent_words_sorting_solution(words: Vec<String>, k: i32) -> Vec<String> {
let mut counter = std::collections::HashMap::<String, i32>::new();
for word in words {
*counter.entry(word).or_default() += 1;
}
let mut a = counter.into_iter().collect::<Vec<_>>();
a.sort_unstable_by(|(word_a, freq_a), (word_b, freq_b)| {
freq_b.cmp(freq_a).then(word_a.cmp(word_b))
});
a.into_iter()
.take(k as usize)
.map(|(word, _freq)| word)
.collect()
}
/// [wrong answer!]fast than sort, sort has extra overhead on array elements swap O(n), but heap swap overhead is O(k)
fn top_k_frequent_words_heap_solution(words: Vec<String>, k: i32) -> Vec<String> {
let mut counter = std::collections::BTreeMap::<String, i32>::new();
for word in words {
*counter.entry(word).or_default() += 1;
}
let k = k as usize;
let mut min_heap = std::collections::BinaryHeap::with_capacity(k + 1);
for (word, freq) in counter {
// python3 heap pushpop
// word is sort by letter desc
min_heap.push((-freq, word));
if min_heap.len() > k {
min_heap.pop();
}
}
// min_heap is sort by freq asc and letter desc, need to reverse it
min_heap
.into_iter()
.rev()
.map(|(_freq, word)| word)
.collect()
}
#[test]
fn test_top_k_frequent_words() {
let test_cases = vec![
(
vec_string!["i", "love", "leetcode", "i", "love", "coding"],
2,
vec_string!["i", "love"],
),
(
vec_string!["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"],
4,
vec_string!["the", "is", "sunny", "day"],
),
];
for (words, k, top_k_frequent) in test_cases {
// since HashMap into_iter is unordered, my heap solution sometimes pass test_cases sometimes not pass, if I change to BTreeMap it would 100% not pass
//assert_eq!(top_k_frequent_words_heap_solution(words.clone(), k), top_k_frequent);
assert_eq!(
top_k_frequent_words_sorting_solution(words, k),
top_k_frequent
);
}
}
| true
|
d2da768a039c09303f9c87bb8659be9fc78f6cd1
|
Rust
|
amadeusine/blisp
|
/src/coq.rs
|
UTF-8
| 8,089
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
use super::semantics as S;
use alloc::collections::LinkedList;
use alloc::format;
use alloc::string::{String, ToString};
pub(crate) fn to_coq_type(
expr: &S::TypeExpr,
depth: usize,
targs: &mut LinkedList<String>,
) -> String {
match expr {
S::TypeExpr::TEBool(_) => "bool".to_string(),
S::TypeExpr::TEInt(_) => "Z".to_string(),
S::TypeExpr::TEString(_) => "string".to_string(),
S::TypeExpr::TEChar(_) => "ascii".to_string(),
S::TypeExpr::TEID(e) => {
if let Some(c) = e.id.chars().next() {
if ('a'..='z').contains(&c) {
let mut flag = false;
for s in targs.iter() {
if *s == e.id {
flag = true;
}
}
if !flag {
targs.push_back(e.id.clone());
}
}
}
e.id.clone()
}
S::TypeExpr::TETuple(e) => {
if e.ty.is_empty() {
return "unit".to_string();
}
let mut i = 0;
let mut s = "".to_string();
for t in e.ty.iter() {
i += 1;
if i == e.ty.len() {
s = format!("{}{}", s, to_coq_type(t, depth + 1, targs));
} else {
s = format!("{}{} * ", s, to_coq_type(t, depth + 1, targs));
}
}
if depth > 0 {
format!("({})", s)
} else {
s
}
}
S::TypeExpr::TEList(e) => {
if depth == 0 {
format!("list {}", to_coq_type(&e.ty, depth + 1, targs))
} else {
format!("(list {})", to_coq_type(&e.ty, depth + 1, targs))
}
}
S::TypeExpr::TEData(e) => {
if e.type_args.is_empty() {
e.id.id.clone()
} else {
let mut args = "".to_string();
for arg in e.type_args.iter() {
args = format!("{}{}", args, to_coq_type(arg, depth + 1, targs));
}
if depth == 0 {
format!("{} {}", e.id.id, args)
} else {
format!("({} {})", e.id.id, args)
}
}
}
S::TypeExpr::TEFun(e) => {
let mut s = "".to_string();
for (i, arg) in e.args.iter().enumerate() {
if i == 0 {
s = to_coq_type(arg, depth + 1, targs);
} else {
s = format!("{} -> {}", s, to_coq_type(arg, depth + 1, targs));
}
}
if depth > 0 {
format!("({})", s)
} else {
s
}
}
}
}
pub(crate) fn import() -> &'static str {
"Require Import ZArith."
}
pub(crate) fn to_coq_data(expr: &S::DataType) -> String {
let mut mem = "".to_string();
let mut i = 0;
for d in expr.members.iter() {
i += 1;
if i == expr.members.len() {
mem = format!("{}{}.\n", mem, to_coq_data_mem(d));
} else {
mem = format!("{}{}\n", mem, to_coq_data_mem(d));
}
}
format!("Inductive {}\n{}", to_coq_data_def(&expr.name), mem)
}
fn to_coq_data_def(expr: &S::DataTypeName) -> String {
let mut args = "(".to_string();
let mut i = 0;
for t in expr.type_args.iter() {
i += 1;
if expr.type_args.len() == i {
args = format!("{}{}: Type)", args, t.id);
} else {
args = format!("{}{} ", args, t.id);
}
}
if !expr.type_args.is_empty() {
format!("{} {}: Type :=", expr.id.id, args)
} else {
format!("{}: Type :=", expr.id.id)
}
}
fn to_coq_data_mem(expr: &S::DataTypeMem) -> String {
let mut mem = "".to_string();
for (i, t) in expr.types.iter().enumerate() {
let mut targs = LinkedList::new();
if expr.types.len() == i + 1 {
mem = format!("{}(x{}: {})", mem, i, to_coq_type(t, 0, &mut targs));
} else {
mem = format!("{}(x{}: {}) ", mem, i, to_coq_type(t, 0, &mut targs));
}
}
if !expr.types.is_empty() {
format!("| {} {}", expr.id.id, mem)
} else {
format!("| {}", expr.id.id)
}
}
fn to_args_type(args: &LinkedList<String>, ty: &str) -> String {
let mut s = "(".to_string();
let mut i = 0;
for a in args {
i += 1;
if i == args.len() {
s = format!("{}{}: {})", s, a, ty);
} else {
s = format!("{}{} ", s, a);
}
}
s
}
pub(crate) fn to_coq_func(expr: &S::Defun) -> String {
let head;
if is_recursive(expr) {
head = format!("Fixpoint {}", expr.id.id);
} else {
head = format!("Definition {}", expr.id.id);
}
let fun_type = if let S::TypeExpr::TEFun(e) = &expr.fun_type {
e
} else {
return "".to_string();
};
// transpile arguments
// arguments whose types are same are aggregated
let mut args = "".to_string();
let mut targs = LinkedList::new();
let mut args_list = LinkedList::new();
let mut prev = "".to_string();
for (arg, t) in expr.args.iter().zip(fun_type.args.iter()) {
let ta = to_coq_type(t, 0, &mut targs);
if prev.is_empty() {
prev = ta.clone();
}
if prev != ta {
let s = to_args_type(&args_list, &prev);
args = format!("{} {}", args, s);
args_list.clear();
args_list.push_back(arg.id.clone());
prev = ta;
} else {
args_list.push_back(arg.id.clone());
}
}
let s = to_args_type(&args_list, &prev);
args = format!("{} {}", args, s);
// transpile return type
let ret = to_coq_type(&fun_type.ret, 0, &mut targs);
// if there is no type argument, then return
if targs.is_empty() {
return format!("{}{}: {} :=\n", head, args, ret);
}
// transpile type arguments
let mut s_targs = "{".to_string();
let mut i = 0;
for targ in &targs {
i += 1;
if i == targs.len() {
s_targs = format!("{}{}", s_targs, targ);
} else {
s_targs = format!("{}{} ", s_targs, targ);
}
}
s_targs = format!("{}: Type}}", s_targs);
format!("{} {}{}: {} :=\n", head, s_targs, args, ret)
}
fn is_recursive(expr: &S::Defun) -> bool {
is_recursive_expr(&expr.expr, &expr.id.id)
}
fn is_recursive_expr(expr: &S::LangExpr, id: &str) -> bool {
match expr {
S::LangExpr::IfExpr(e) => {
is_recursive_expr(&e.cond_expr, id)
|| is_recursive_expr(&e.then_expr, id)
|| is_recursive_expr(&e.else_expr, id)
}
S::LangExpr::LetExpr(e) => is_recursive_expr(&e.expr, id),
S::LangExpr::LitStr(_) => false,
S::LangExpr::LitChar(_) => false,
S::LangExpr::LitNum(_) => false,
S::LangExpr::LitBool(_) => false,
S::LangExpr::IDExpr(e) => e.id == *id,
S::LangExpr::DataExpr(e) => is_recursive_exprs(&e.exprs, id),
S::LangExpr::MatchExpr(e) => {
if is_recursive_expr(&e.expr, id) {
return true;
}
for c in e.cases.iter() {
if is_recursive_expr(&c.expr, id) {
return true;
}
}
false
}
S::LangExpr::ApplyExpr(e) => is_recursive_exprs(&e.exprs, id),
S::LangExpr::ListExpr(e) => is_recursive_exprs(&e.exprs, id),
S::LangExpr::TupleExpr(e) => is_recursive_exprs(&e.exprs, id),
S::LangExpr::LambdaExpr(e) => is_recursive_expr(&e.expr, id),
}
}
fn is_recursive_exprs(exprs: &[S::LangExpr], id: &str) -> bool {
for e in exprs.iter() {
if is_recursive_expr(e, id) {
return true;
}
}
false
}
| true
|
514a368505dc32e15b0f8f1cadf7cf87068d585c
|
Rust
|
gba-rs/web-frontend
|
/src/components/registers.rs
|
UTF-8
| 6,067
| 2.96875
| 3
|
[
"Apache-2.0",
"MIT"
] |
permissive
|
use yew::prelude::*;
use yew::{html, Component, ComponentLink, InputData, KeyboardEvent, Html, ShouldRender};
use gba_emulator::gba::GBA;
use std::rc::Rc;
use std::cell::RefCell;
use log::{info};
pub struct Registers {
props: RegistersProp,
updated_reg_hex: String,
updated_reg_dec: String,
update_reg_num: u8,
link: ComponentLink<Self>
}
#[derive(Properties, Clone)]
pub struct RegistersProp {
pub gba: Rc<RefCell<GBA>>,
pub hex: bool
}
pub enum RegUpdateType {
Hex,
Dec
}
pub enum Msg {
StartUpdate(String, RegUpdateType),
UpdateReg(String, u8, RegUpdateType),
FinishUpdate(RegUpdateType),
Nope
}
impl Component for Registers {
type Message = Msg;
type Properties = RegistersProp;
fn create(props: Self::Properties, link: ComponentLink<Self>) -> Self {
Registers {
props: props,
updated_reg_dec: "".to_string(),
updated_reg_hex: "".to_string(),
update_reg_num: 0,
link: link
}
}
fn update(&mut self, msg: Self::Message) -> ShouldRender {
match msg {
Msg::StartUpdate(init_string, update_type) => {
match update_type {
RegUpdateType::Dec => {
self.updated_reg_dec = init_string;
},
RegUpdateType::Hex => {
self.updated_reg_hex = init_string;
}
}
},
Msg::UpdateReg(update_string, reg_num, update_type) => {
self.update_reg_num = reg_num;
match update_type {
RegUpdateType::Hex => {
self.updated_reg_hex = update_string;
},
RegUpdateType::Dec => {
self.updated_reg_dec = update_string;
}
}
},
Msg::FinishUpdate(update_type) => {
match update_type {
RegUpdateType::Hex => {
self.updated_reg_hex.retain(|c| !c.is_whitespace());
let result = u32::from_str_radix(&self.updated_reg_hex, 16);
match result {
Ok(val) => {
self.props.gba.borrow_mut().cpu.set_register(self.update_reg_num, val)
},
Err(_) => {
info!("Error updating r{}: {}", self.update_reg_num, self.updated_reg_hex);
}
}
},
RegUpdateType::Dec => {
self.updated_reg_dec.retain(|c| !c.is_whitespace());
let result = u32::from_str_radix(&self.updated_reg_dec, 10);
match result {
Ok(val) => {
self.props.gba.borrow_mut().cpu.set_register(self.update_reg_num, val)
},
Err(_) => {
info!("Error updating r{}: {}", self.update_reg_num, self.updated_reg_dec);
}
}
}
}
},
Msg::Nope => {}
}
true
}
fn change(&mut self, props: Self::Properties) -> ShouldRender {
self.props = props;
true
}
fn view(&self) -> Html {
html! {
<div>
<h4>{"Registers"}</h4>
<table class="table register-table">
<thead>
<tr>
<th scope="col">{"Reg"}</th>
<th scope="col">{"Val Hex"}</th>
<th scope="col">{"Val Dec"}</th>
</tr>
</thead>
<tbody>
{for (0..16).map(|val|{
let reg_val = self.props.gba.borrow().cpu.get_register_unsafe(val);
let reg_num = val;
html! {
<tr>
<td class="text-left">{format!("r{}", val)}</td>
<td class="text-right">
<input class="hex-edit hex-edit-word" type="text" value={format!("{:08X}", reg_val)}
onclick=self.link.callback(move |_|{ Msg::StartUpdate(format!("{:08X}", reg_val), RegUpdateType::Hex) })
oninput=self.link.callback(move |e: InputData|{ Msg::UpdateReg(e.value, reg_num, RegUpdateType::Hex) })
onkeypress=self.link.callback(|e: KeyboardEvent|{ if e.key() == "Enter" { Msg::FinishUpdate(RegUpdateType::Hex) } else { Msg::Nope } })
/>
</td>
<td class="text-right">
<input class="hex-edit hex-edit-word" type="text" value={format!("{}", reg_val)}
onclick=self.link.callback(move |_|{ Msg::StartUpdate(format!("{}", reg_val), RegUpdateType::Dec) })
oninput=self.link.callback(move |e: InputData|{ Msg::UpdateReg(e.value, reg_num, RegUpdateType::Dec) })
onkeypress=self.link.callback(|e: KeyboardEvent|{ if e.key() == "Enter" { Msg::FinishUpdate(RegUpdateType::Dec) } else { Msg::Nope } })
/>
</td>
</tr>
}
})}
</tbody>
</table>
</div>
}
}
}
| true
|
217f02c11f3f712ce4160d6dc4802ecd82a46668
|
Rust
|
gskapka/etheroff
|
/src/interactive_cli_lib/get_eth_gas_price.rs
|
UTF-8
| 675
| 2.90625
| 3
|
[] |
no_license
|
use crate::{
interactive_cli_lib::{state::InteractiveCliState, utils::get_user_input},
lib::types::Result,
};
pub fn get_eth_gas_price_from_user(state: InteractiveCliState) -> Result<InteractiveCliState> {
println!("❍ Please enter the gas price for the transaction (in GWEI):");
get_user_input().and_then(|user_input| match user_input.parse::<f64>() {
Ok(amount) => {
println!("✔ Gas price: {} GWei", &amount);
state.add_eth_gas_price_gwei(amount)
},
Err(_) => {
println!("✘ Could not parse '{}' to an amount!", user_input);
get_eth_gas_price_from_user(state)
},
})
}
| true
|
39a0d833928d5a0ec0e689b46f8565ae7f629873
|
Rust
|
rstropek/rust-samples
|
/memory-management/040-Rc/src/main.rs
|
UTF-8
| 720
| 3.453125
| 3
|
[] |
no_license
|
use std::rc::Rc;
#[derive(Debug)]
struct MyPrecious {
ring: i32,
}
impl Drop for MyPrecious {
fn drop(&mut self) {
println!("Dropping {:?}", self);
}
}
fn main() {
let mine = Box::new(MyPrecious{ ring: 21 });
let also_mine = mine;
//println!("{:?}", mine); // Does not work
println!("{:?}", also_mine.ring);
let mine = Rc::new(MyPrecious{ ring: 42 });
{
let also_mine = Clone::clone(&mine);
println!("{:?} {:p}", mine.ring, mine.as_ref());
println!("{:?} {:p}", also_mine.ring, also_mine.as_ref());
println!("Ref count inside: {:?}", Rc::strong_count(&also_mine));
}
println!("Ref count outside: {:?}", Rc::strong_count(&mine));
}
| true
|
d7411140ec10bd5a35dc0e496708a909342ff8b2
|
Rust
|
marlon-bain/aoc2019
|
/day1/src/main.rs
|
UTF-8
| 756
| 3.328125
| 3
|
[] |
no_license
|
use aoc::utils::get_ints;
fn get_fuel(mass: i32) -> i32 {
let tentative = ((mass / 3) as i32) - 2;
if tentative < 0 {
return 0;
}
tentative
}
fn main() {
let values = get_ints("input.txt");
// Part 1
{
let mut result = 0;
for value in values.clone() {
result += get_fuel(value);
}
println!("{}", result);
}
// Part 2
{
let mut result = 0;
for value in values.clone() {
let mut load = value;
let mut fuel = get_fuel(load);
while (fuel > 0) {
result += fuel;
load = fuel;
fuel = get_fuel(load);
}
}
println!("{}", result);
}
}
| true
|
8895a9982139e1b8ba83d574a317f4df6d207965
|
Rust
|
jaffa4/siko-1
|
/crates/siko_interpreter/src/std_ops.rs
|
UTF-8
| 1,343
| 2.59375
| 3
|
[
"MIT"
] |
permissive
|
use crate::environment::Environment;
use crate::extern_function::ExternFunction;
use crate::interpreter::Interpreter;
use crate::value::Value;
use siko_ir::expr::ExprId;
use siko_ir::function::NamedFunctionKind;
use siko_ir::types::Type;
pub struct And {}
impl ExternFunction for And {
fn call(
&self,
environment: &mut Environment,
_: Option<ExprId>,
_: &NamedFunctionKind,
_: Type,
) -> Value {
let l = environment.get_arg_by_index(0).core.as_bool();
let r = environment.get_arg_by_index(1).core.as_bool();
return Interpreter::get_bool_value(l && r);
}
}
pub struct Or {}
impl ExternFunction for Or {
fn call(
&self,
environment: &mut Environment,
_: Option<ExprId>,
_: &NamedFunctionKind,
_: Type,
) -> Value {
let l = environment.get_arg_by_index(0).core.as_bool();
if l {
return Interpreter::get_bool_value(l);
} else {
let r = environment.get_arg_by_index(1).core.as_bool();
return Interpreter::get_bool_value(r);
}
}
}
pub fn register_extern_functions(interpreter: &mut Interpreter) {
interpreter.add_extern_function("Std.Ops", "opAnd", Box::new(And {}));
interpreter.add_extern_function("Std.Ops", "opOr", Box::new(Or {}));
}
| true
|
362c38ff8a53c41faf85ff85ee328cf5ad1fb7ea
|
Rust
|
hubris-lang/hubris
|
/src/hubris/core/name.rs
|
UTF-8
| 5,701
| 3.03125
| 3
|
[
"MIT"
] |
permissive
|
use super::super::ast::{Span, HasSpan};
use std::fmt::{self, Display, Formatter};
use std::hash::{Hash, Hasher};
use super::Term;
use super::BindingMode;
use super::super::pretty::*;
#[derive(Clone, Debug, Eq)]
pub enum Name {
DeBruijn {
index: usize,
span: Span,
repr: String,
},
Local {
number: usize,
repr: String,
ty: Box<Term>,
binding_info: BindingMode,
},
Qual {
span: Span,
components: Vec<String>,
},
Meta {
number: usize,
ty: Box<Term>,
},
}
impl Name {
pub fn from_str(s: &str) -> Name {
Name::Qual {
span: Span::dummy(),
components: vec![s.to_owned()],
}
}
pub fn to_term(&self) -> Term {
Term::Var { name: self.clone() }
}
pub fn is_placeholder(&self) -> bool {
use self::Name::*;
match self {
&DeBruijn { ref repr, .. } |
&Local { ref repr, .. } if repr == "" || repr == "_" => true,
_ => false,
}
}
pub fn is_meta(&self) -> bool {
use self::Name::*;
match self {
&Meta { .. } => true,
_ => false,
}
}
pub fn is_local(&self) -> bool {
use self::Name::*;
match self {
&Local { .. } => true,
_ => false,
}
}
pub fn is_qual(&self) -> bool {
use self::Name::*;
match self {
&Qual { .. } => true,
_ => false,
}
}
pub fn qualified(components: Vec<String>) -> Name {
Name::Qual {
span: Span::dummy(),
components: components,
}
}
pub fn in_scope(&self, component: String) -> Option<Name> {
match self {
&Name::Qual { span, ref components } => {
let mut components = components.clone();
components.push(component);
Some(Name::Qual {
span: span,
components: components,
})
}
_ => None,
}
}
pub fn is_implicit(&self) -> bool {
match self {
&Name::Local { binding_info: BindingMode::Implicit, .. } => true,
_ => false,
}
}
pub fn with_repr(mut self, new_repr: String) -> Name {
use self::Name::*;
match &mut self {
&mut DeBruijn { ref mut repr, .. } =>
*repr = new_repr,
&mut Qual { .. } =>
panic!("error"),
&mut Local { ref mut repr, .. } =>
*repr = new_repr,
&mut Meta { .. } =>
panic!("error"),
}
self
}
}
impl PartialEq for Name {
fn eq(&self, other: &Name) -> bool {
use self::Name::*;
match (self, other) {
(&DeBruijn { index: ref index1, .. },
&DeBruijn { index: ref index2, .. }) => index1 == index2,
(&Qual { components: ref components1, .. },
&Qual { components: ref components2, .. }) => components1 == components2,
(&Local { number: ref n1, .. },
&Local { number: ref n2, .. }) =>
n1 == n2,
(&Meta { number: number1, ..}, &Meta { number: number2, .. }) =>
number1 == number2,
_ => false
}
}
}
impl Hash for Name {
fn hash<H>(&self, state: &mut H)
where H: Hasher
{
use self::Name::*;
match self {
&DeBruijn { ref index, .. } => {
0.hash(state);
index.hash(state);
}
&Qual { ref components, .. } => {
1.hash(state);
components.hash(state);
}
&Meta { ref number, .. } => {
2.hash(state);
number.hash(state);
}
&Local { ref number, .. } => {
3.hash(state);
number.hash(state);
}
}
}
}
impl Pretty for Name {
fn pretty(&self) -> Doc {
use self::Name::*;
match self {
&DeBruijn { ref repr, ref index, .. } => repr.pretty(), // Doc::text(format!("{}", index)),
&Qual { ref components, .. } => {
if components.len() == 1 {
components[0].pretty()
} else {
seperate(components.iter().map(|x| x.pretty())
.collect::<Vec<Doc>>().as_slice(),
&Doc::text("."))
}
}
&Meta { number, .. } => Doc::text(format!("?{}", number)),
&Local { ref repr, ref number, .. } => {
// try!(write!(formatter, "{}(local {} : {})", repr, number, ty))
repr.pretty() + parens(Doc::text(format!("{}", number)))
}
}
}
}
impl Display for Name {
fn fmt(&self, formatter: &mut Formatter) -> Result<(), fmt::Error> {
format(self, formatter)
}
}
impl HasSpan for Name {
fn get_span(&self) -> Span {
use self::Name::*;
match self {
&Qual { span, .. } => span,
&DeBruijn { span, .. } => span,
&Meta { .. } => Span::dummy(),
&Local { .. } => Span::dummy(),
}
}
fn set_span(&mut self, sp: Span) {
use self::Name::*;
match self {
&mut DeBruijn { ref mut span, .. } => *span = sp,
&mut Qual { ref mut span, ..} => *span = sp,
&mut Meta { .. } => {}
&mut Local { .. } => {}
}
}
}
| true
|
47c6ae5b203297d8bf25d781d14b3941b7bf2239
|
Rust
|
zoniony/sdz
|
/src/corpus/inputs.rs
|
UTF-8
| 531
| 2.9375
| 3
|
[] |
no_license
|
use std::{
fs::File,
io::{Read},
path::Path
};
use crate::corpus::Inputs;
#[derive(Debug)]
pub struct BytesInput {
pub bytes: Vec<u8>,
}
impl Inputs for BytesInput {
fn read_file<P>(path: P) -> Self
where
P: AsRef<Path>,
{
let mut file = File::open(path).unwrap();
let mut bytes: Vec<u8> = vec![];
file.read_to_end(&mut bytes).unwrap();
BytesInput::new(bytes)
}
}
impl BytesInput {
pub fn new(bytes: Vec<u8>) -> Self {
Self {bytes}
}
}
| true
|
71af673b38833bd8c8d6905738bde836bb811a34
|
Rust
|
jorgeja/advent_of_code_2020
|
/src/day_14/mod.rs
|
UTF-8
| 2,537
| 3.515625
| 4
|
[] |
no_license
|
use std::collections::HashMap;
fn parse_input(input: &str) -> usize {
let mut memory = HashMap::new();
let mut mask = (0, 0);
for line in input.lines() {
if let Some(index) = line.find("mask = ") {
mask = parse_mask(&line[index+7..]);
} else if line.starts_with("mem") {
let (address, new_value) = parse_value(line);
//eprintln!("[{}] = {:#036b}", address, new_value);
let mut value = new_value | mask.1;
//eprintln!("VAL {:#036b}", new_value);
//eprintln!("OR {:#036b}", mask.1);
//eprintln!("= {:#036b}", value);
value &= mask.0;
//eprintln!("AND {:#036b}", mask.0);
//eprintln!("[{}] {:#036b} = {}", address, value, value);
let _ = memory.insert(address, value);
}
}
//eprintln!("{:?}", memory);
memory.values().fold(0, |acc, v| acc + *v)
}
fn parse_value(input: &str) -> (usize, usize) {
let s: Vec<&str> = input.split(" = ").collect();
let address = s[0].strip_prefix("mem[").unwrap().strip_suffix("]").unwrap().parse::<usize>().unwrap();
let value = s[1].parse::<usize>().unwrap();
(address, value)
}
fn parse_mask(input: &str) -> (usize, usize){
let string_and_mask = input.chars().map(|c| {
match c {
'X' => '1',
'1' => '1',
_ => '0',
}
}).collect::<String>();
let string_or_mask = input.chars().map(|c| {
match c {
'1' => '1',
_ => '0',
}
}).collect::<String>();
//eprintln!("raw mask len: {} => {}", input.len(), input);
//eprintln!("and mask len: {} => {}", string_and_mask.len(), string_and_mask);
//eprintln!("and or len: {} => {}", string_or_mask.len(), string_or_mask);
let and_mask = usize::from_str_radix(string_and_mask.as_str(), 2).unwrap();
let or_mask = usize::from_str_radix(string_or_mask.as_str(), 2).unwrap();
//eprintln!("AND_MASK: {:#036b}", and_mask);
//eprintln!("OR_MASK: {:#036b}", or_mask);
(and_mask, or_mask)
}
#[cfg(test)]
mod tests {
use super::parse_input;
#[test]
fn part1_example() {
let input = include_str!("example_part1.txt");
let result = parse_input(input);
eprintln!("Sum: {}", result);
}
#[test]
fn part1() {
let input = include_str!("input_part1.txt");
let result = parse_input(input);
eprintln!("Sum: {}", result);
}
}
| true
|
5a49e9babaae012dfa9f758fb8d4065f191340e7
|
Rust
|
scotow/nustify
|
/examples/image.rs
|
UTF-8
| 549
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
use std::env::args;
use std::error::Error;
use nustify::notification::Builder;
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Box<dyn Error>> {
let args = args().skip(1).collect::<Vec<_>>();
let key = args.get(0).ok_or("invalid ifttt key")?;
let image = args.get(1).unwrap_or(&"https://i.imgur.com/SFmiPRo.png".to_owned()).clone();
let notification = Builder::new("A nice image".to_owned())
.image_url(image)
.build();
nustify::send(¬ification, "nustify", &key).await?;
Ok(())
}
| true
|
abe0aa3cc8e733c5e72e2ac2696dca3d50c089f9
|
Rust
|
mneumann/graph-neighbor-matching
|
/src/lib.rs
|
UTF-8
| 1,100
| 2.578125
| 3
|
[
"MIT"
] |
permissive
|
//! A graph similarity score using neighbor matching according to [this paper][1].
//!
//! [1]: http://arxiv.org/abs/1009.5290 "2010, Mladen Nikolic, Measuring Similarity
//! of Graph Nodes by Neighbor Matching"
//!
//! TODO: Introduce EdgeWeight trait to abstract edge weight similarity.
pub mod graph;
mod graph_traits;
mod node_color_matching;
mod score_norm;
mod similarity_matrix;
use closed01::Closed01;
pub use {graph_traits::*, node_color_matching::*, score_norm::*, similarity_matrix::*};
impl NodeColorWeight for f32 {
fn node_color_weight(&self) -> f32 {
*self
}
}
pub fn similarity_max_degree<T: Graph>(a: &T, b: &T, num_iters: usize, eps: f32) -> Closed01<f32> {
let mut s = SimilarityMatrix::new(a, b, IgnoreNodeColors);
s.iterate(num_iters, eps);
s.score_optimal_sum_norm(None, ScoreNorm::MaxDegree)
}
pub fn similarity_min_degree<T: Graph>(a: &T, b: &T, num_iters: usize, eps: f32) -> Closed01<f32> {
let mut s = SimilarityMatrix::new(a, b, IgnoreNodeColors);
s.iterate(num_iters, eps);
s.score_optimal_sum_norm(None, ScoreNorm::MinDegree)
}
| true
|
80f28a8ef10c0ee4086e0db03b3bd77c52ad1bf6
|
Rust
|
IThawk/rust-project
|
/rust-master/src/test/ui/span/recursive-type-field.rs
|
UTF-8
| 305
| 2.65625
| 3
|
[
"MIT",
"LicenseRef-scancode-other-permissive",
"Apache-2.0",
"BSD-3-Clause",
"BSD-2-Clause",
"NCSA"
] |
permissive
|
use std::rc::Rc;
struct Foo<'a> { //~ ERROR recursive type
bar: Bar<'a>,
b: Rc<Bar<'a>>,
}
struct Bar<'a> { //~ ERROR recursive type
y: (Foo<'a>, Foo<'a>),
z: Option<Bar<'a>>,
a: &'a Foo<'a>,
c: &'a [Bar<'a>],
d: [Bar<'a>; 1],
e: Foo<'a>,
x: Bar<'a>,
}
fn main() {}
| true
|
ae5519f20685837d80871500de315a9e5090b7c9
|
Rust
|
rushmorem/domain
|
/src/bits/net/udp.rs
|
UTF-8
| 7,589
| 2.78125
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
//! Sending and receiving via UDP.
use std::{io, mem};
use std::collections::{HashMap, VecDeque};
use std::net::{IpAddr, SocketAddr};
use futures::Async;
use futures::stream::Stream;
use tokio_core::reactor;
use tokio_core::net::UdpSocket;
use ::bits::{ComposeMode, MessageBuf};
use super::Flow;
use super::mpsc::{Receiver, Sender, channel};
//------------ UdpServer -----------------------------------------------------
pub struct UdpServer {
sock: UdpSocket,
flows: HashMap<SocketAddr, Sender<MessageBuf>>,
pending: VecDeque<(Sender<MessageBuf>, UdpServerFlow)>,
write_sender: Sender<(Vec<u8>, SocketAddr)>,
write_queue: Receiver<(Vec<u8>, SocketAddr)>,
write_item: Option<(Vec<u8>, SocketAddr)>,
read_buf: Vec<u8>,
read_size: usize,
write_size: usize,
}
impl UdpServer {
pub fn new(sock: UdpSocket, read_size: usize, write_size: usize) -> Self {
let (tx, rx) = channel();
UdpServer {
sock: sock,
flows: HashMap::new(),
pending: VecDeque::new(),
write_sender: tx,
write_queue: rx,
write_item: None,
read_buf: vec![0; read_size],
read_size: read_size,
write_size: write_size
}
}
pub fn bind(addr: &SocketAddr, handle: &reactor::Handle, read_size: usize,
write_size: usize) -> io::Result<Self> {
UdpSocket::bind(addr, handle).map(|sock| {
UdpServer::new(sock, read_size, write_size)
})
}
}
impl Stream for UdpServer {
type Item = UdpServerFlow;
type Error = io::Error;
fn poll(&mut self) -> io::Result<Async<Option<UdpServerFlow>>> {
try!(self.poll_write());
try!(self.poll_read());
if let Some((tx, flow)) = self.pending.pop_front() {
self.flows.insert(flow.peer, tx);
Ok(Async::Ready(Some(flow)))
}
else {
Ok(Async::NotReady)
}
}
}
impl UdpServer {
fn poll_write(&mut self) -> io::Result<Async<()>> {
loop {
if let Some((ref mut item, ref addr)) = self.write_item {
try_nb!(self.sock.send_to(item, addr));
}
match self.write_queue.poll() {
Ok(Async::Ready(Some(item))) => {
self.write_item = Some(item)
}
Ok(Async::NotReady) => {
self.write_item = None;
return Ok(Async::NotReady)
}
_ => unreachable!()
}
}
}
fn poll_read(&mut self) -> io::Result<Async<()>> {
loop {
let (size, peer) = try_nb!(self.sock.recv_from(&mut self.read_buf));
let mut data = mem::replace(&mut self.read_buf,
vec![0; self.read_size]);
data.truncate(size);
if let Ok(data) = MessageBuf::from_vec(data) {
if let Err(data) = self.dispatch(data, peer) {
self.new_flow(data, peer);
}
}
}
}
fn dispatch(&mut self, data: MessageBuf, peer: SocketAddr)
-> Result<(), MessageBuf> {
let data = if let Some(sender) = self.flows.get(&peer) {
match sender.send(data) {
Ok(()) => return Ok(()),
Err(data) => data
}
}
else {
return Err(data)
};
self.flows.remove(&peer);
Err(data)
}
fn new_flow(&mut self, data: MessageBuf, peer: SocketAddr) {
let (flow, tx) = UdpServerFlow::new(peer, self.write_sender.clone(),
self.write_size);
tx.send(data).unwrap();
self.pending.push_back((tx, flow));
}
}
//------------ UdpServerFlow -------------------------------------------------
pub struct UdpServerFlow {
peer: SocketAddr,
write: Sender<(Vec<u8>, SocketAddr)>,
write_size: usize,
recv: Receiver<MessageBuf>,
}
impl UdpServerFlow {
fn new(peer: SocketAddr, write: Sender<(Vec<u8>, SocketAddr)>,
write_size: usize)
-> (Self, Sender<MessageBuf>) {
let (tx, rx) = channel();
(UdpServerFlow{peer: peer, write: write, write_size: write_size, recv: rx},
tx)
}
}
impl Flow for UdpServerFlow {
fn compose_mode(&self) -> ComposeMode {
ComposeMode::Limited(self.write_size)
}
fn send(&mut self, msg: Vec<u8>) -> io::Result<()> {
self.write.send((msg, self.peer)).map_err(|_| {
io::Error::new(io::ErrorKind::ConnectionAborted,
"socket closed")
})
}
fn flush(&mut self) -> io::Result<Async<()>> {
Ok(Async::Ready(()))
}
fn recv(&mut self) -> io::Result<Async<Option<MessageBuf>>> {
self.recv.poll().map_err(|_| unreachable!())
}
}
//------------ UdpClientFlow -------------------------------------------------
pub struct UdpClientFlow {
sock: UdpSocket,
peer: SocketAddr,
write: VecDeque<Vec<u8>>,
read_buf: Vec<u8>,
read_size: usize,
write_size: usize,
}
impl UdpClientFlow {
fn new(sock: UdpSocket, peer: SocketAddr, read_size: usize,
write_size: usize) -> Self {
UdpClientFlow {
sock: sock, peer: peer,
write: VecDeque::new(),
read_buf: vec![0; read_size],
read_size: read_size, write_size: write_size
}
}
pub fn bind_and_connect(local: &SocketAddr, peer: &SocketAddr,
handle: &reactor::Handle, read_size: usize,
write_size: usize) -> io::Result<Self> {
UdpSocket::bind(&local, handle).map(|sock| {
UdpClientFlow::new(sock, *peer, read_size, write_size)
})
}
pub fn connect(peer: &SocketAddr, handle: &reactor::Handle,
read_size: usize, write_size: usize) -> io::Result<Self> {
let local = match *peer {
SocketAddr::V4(_)
=> SocketAddr::new(IpAddr::V4(0.into()), 0),
SocketAddr::V6(_)
=> SocketAddr::new(IpAddr::V6([0;16].into()), 0)
};
UdpClientFlow::bind_and_connect(&local, peer, handle, read_size,
write_size)
}
}
impl Flow for UdpClientFlow {
fn compose_mode(&self) -> ComposeMode {
ComposeMode::Limited(self.write_size)
}
fn send(&mut self, msg: Vec<u8>) -> io::Result<()> {
self.write.push_back(msg);
Ok(())
}
fn flush(&mut self) -> io::Result<Async<()>> {
loop {
match self.write.front() {
Some(msg) => {
try_nb!(self.sock.send_to(&msg, &self.peer));
}
None => return Ok(Async::Ready(()))
}
self.write.pop_front();
}
}
fn recv(&mut self) -> io::Result<Async<Option<MessageBuf>>> {
loop {
let (size, peer) = try_nb!(self.sock.recv_from(&mut self.read_buf));
if peer != self.peer {
// Quietly drop messages from the wrong peer.
continue
}
let mut data = mem::replace(&mut self.read_buf,
vec![0; self.read_size]);
data.truncate(size);
if let Ok(msg) = MessageBuf::from_vec(data) {
return Ok(Async::Ready(Some(msg)))
}
// ... and drop short messages, too.
}
}
}
| true
|
3b246d6ad950edd96365cbfb243c6d9e93a8ae85
|
Rust
|
LgnMs/my-leetcode-rust
|
/dynamic_programming/max_profit.rs
|
UTF-8
| 595
| 3.265625
| 3
|
[
"MIT"
] |
permissive
|
/*
* @lc app=leetcode.cn id=1 lang=rust
*
* [121] 买卖股票的最佳时机
* https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/
* - [动态规划]
*/
pub fn max_profit(prices: Vec<i32>) -> i32 {
let mut min = prices[0];
let mut max_sum = 0;
for x in prices {
if x < min {
min = x;
} else if x - min > max_sum {
max_sum = x - min;
}
}
max_sum
}
#[cfg(test)]
mod tests {
use crate::max_profit::max_profit;
#[test]
fn it_work_1() {
assert_eq!(max_profit(vec![2, 4, 1]), 2);
}
}
| true
|
7e659950469db94988ab539be6744acde8d646fa
|
Rust
|
DioneJM/minigrep
|
/src/lib.rs
|
UTF-8
| 2,255
| 3.53125
| 4
|
[] |
no_license
|
use std::fs;
use std::path::Path;
use std::error::Error;
pub struct Arguments<'a> {
query: &'a String,
filename: &'a String,
case_sensitive: bool
}
impl<'a> Arguments<'a> {
pub fn new(args: &Vec<String>) -> Result<Arguments, &str> {
if args.len() < 3 {
return Err("Invalid arguments - You must supply a search query and filename");
}
let query: &String = &args[1];
let filename: &String = &args[2];
let mut flag_one: &String = &String::from("");
if args.len() > 3 {
flag_one = &args[3];
}
let disable_case_sensitive = match flag_one.as_str() {
"--ignore-case" => true,
_ => false
};
Ok(Arguments {
query,
filename,
case_sensitive: !disable_case_sensitive
})
}
}
pub fn parse_arguments(arguments: Arguments) -> Result<(), Box<dyn Error>> {
let contents = fs::read_to_string(Path::new(arguments.filename))?;
let search_results = match arguments.case_sensitive {
true => search(arguments.query, &contents),
false => search_insensitive(arguments.query, &contents)
};
for line in search_results {
println!("{}", line);
}
Ok(())
}
pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
contents.lines()
.filter(|line| line.contains(query))
.map(|line| line.trim())
.collect()
}
pub fn search_insensitive<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
contents.lines()
.filter(|line| line.to_lowercase().contains(query.to_lowercase().as_str()))
.map(|line| line.trim())
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn case_sensitive() {
let query = "duct";
let contents = "\
Rust:
safe, fast, productive.
Pick three.
Duct tape.";
assert_eq!(vec!["safe, fast, productive."], search(query, contents));
}
#[test]
fn case_insensitive() {
let query = "rUsT";
let contents = "\
Rust:
safe, fast, productive.
Pick three.
Trust me.";
assert_eq!(
vec!["Rust:", "Trust me."],
search_insensitive(query, contents)
);
}
}
| true
|
d275cbcb6968f76f39f86037ca247b11548bb04e
|
Rust
|
hatoo/rukako
|
/rukako-shader/src/camera.rs
|
UTF-8
| 1,966
| 2.859375
| 3
|
[
"MIT"
] |
permissive
|
// use rand::Rng;
use spirv_std::glam::Vec3;
#[allow(unused_imports)]
use spirv_std::num_traits::Float;
use crate::math::random_in_unit_disk;
use crate::rand::DefaultRng;
use crate::ray::Ray;
#[derive(Copy, Clone)]
pub struct Camera {
origin: Vec3,
lower_left_corner: Vec3,
horizontal: Vec3,
vertical: Vec3,
u: Vec3,
v: Vec3,
// w: Vec3,
lens_radius: f32,
time0: f32,
time1: f32,
}
impl Camera {
#[allow(clippy::too_many_arguments)]
pub fn new(
look_from: Vec3,
look_at: Vec3,
vup: Vec3,
vfov: f32,
aspect_ratio: f32,
aperture: f32,
focus_dist: f32,
time0: f32,
time1: f32,
) -> Self {
let theta = vfov;
let h = (theta / 2.0).tan();
let viewport_height = 2.0 * h;
let viewport_width = aspect_ratio * viewport_height;
let w = (look_from - look_at).normalize();
let u = vup.cross(w).normalize();
let v = w.cross(u);
let origin = look_from;
let horizontal = focus_dist * viewport_width * u;
let vertical = focus_dist * viewport_height * v;
let lower_left_corner = origin - horizontal / 2.0 - vertical / 2.0 - focus_dist * w;
Self {
origin,
lower_left_corner,
horizontal,
vertical,
u,
v,
// w,
lens_radius: aperture / 2.0,
time0,
time1,
}
}
pub fn get_ray(&self, s: f32, t: f32, rng: &mut DefaultRng) -> Ray {
let rd = self.lens_radius * random_in_unit_disk(rng);
let offset = self.u * rd.x + self.v * rd.y;
Ray {
origin: self.origin + offset,
direction: (self.lower_left_corner + s * self.horizontal + t * self.vertical
- self.origin
- offset),
time: rng.next_f32_range(self.time0, self.time1),
}
}
}
| true
|
53524d00de92ddacf385fbe9e17599a898c28d73
|
Rust
|
Junzki/shadowsocks-rust
|
/src/relay/loadbalancing/server/ping.rs
|
UTF-8
| 5,842
| 2.671875
| 3
|
[
"MIT"
] |
permissive
|
use std::io;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};
use crate::{
config::ServerConfig, context::SharedContext, relay::loadbalancing::server::LoadBalancer, relay::socks5::Address,
relay::tcprelay::client::ServerClient,
};
use futures::{Future, Stream};
use log::{debug, error};
use tokio;
use tokio::timer::{Interval, Timeout};
struct Server {
config: Arc<ServerConfig>,
elapsed: AtomicU64,
available: AtomicBool,
}
impl Server {
fn new(config: ServerConfig) -> Server {
Server {
config: Arc::new(config),
elapsed: AtomicU64::new(0),
available: AtomicBool::new(true),
}
}
}
#[derive(Clone)]
pub struct PingBalancer {
servers: Vec<Arc<Server>>,
}
impl PingBalancer {
pub fn new(context: SharedContext) -> PingBalancer {
let config = context.config();
if config.server.is_empty() {
panic!("no servers");
}
let check_required = config.server.len() > 1;
let mut servers = Vec::new();
for svr in &config.server {
let sc = Arc::new(Server::new(svr.clone()));
servers.push(sc.clone());
if !check_required {
continue;
}
let addr = Address::DomainNameAddress("www.example.com".to_owned(), 80);
let context = context.clone();
tokio::spawn(
// Check every 10 seconds
Interval::new(Instant::now() + Duration::from_secs(1), Duration::from_secs(10))
.for_each(move |_| {
let sc = sc.clone();
let fut1 = PingBalancer::check_delay(sc.clone(), context.clone(), addr.clone());
let fut2 = PingBalancer::check_delay(sc.clone(), context.clone(), addr.clone());
let fut3 = PingBalancer::check_delay(sc.clone(), context.clone(), addr.clone());
fut1.join3(fut2, fut3).then(move |res| {
match res {
Ok((d1, d2, d3)) => {
sc.available.store(true, Ordering::Release);
sc.elapsed.store((d1 + d2 + d3) / 3, Ordering::Release);
}
Err(..) => {
sc.available.store(false, Ordering::Release);
}
}
Ok(())
})
})
.map_err(|_| ()),
);
}
PingBalancer { servers }
}
fn check_delay(
sc: Arc<Server>,
context: SharedContext,
addr: Address,
) -> impl Future<Item = u64, Error = io::Error> {
let start = Instant::now();
let fut = ServerClient::connect(context, addr, sc.config.clone());
Timeout::new(fut, Duration::from_secs(5)).then(move |res| {
let elapsed = Instant::now() - start;
let elapsed = elapsed.as_secs() * 1000 + u64::from(elapsed.subsec_millis()); // Converted to ms
match res {
Ok(..) => {
// Connected ... record its time
debug!(
"checked remote server {} connected with {} ms",
sc.config.addr(),
elapsed
);
Ok(elapsed)
}
Err(err) => {
match err.into_inner() {
Some(err) => {
error!("failed to check server {}, error: {}", sc.config.addr(), err);
// NOTE: connection / handshake error, server is down
Err(err)
}
None => {
// Timeout
error!("checked remote server {} connect timeout", sc.config.addr());
// NOTE: timeout is still available, but server is too slow
Ok(elapsed)
}
}
}
}
})
}
}
impl LoadBalancer for PingBalancer {
fn pick_server(&mut self) -> Arc<ServerConfig> {
if self.servers.is_empty() {
panic!("No server");
}
// Choose the best one
let mut choosen_svr = &self.servers[0];
let mut found_one = false;
for svr in &self.servers {
if svr.available.load(Ordering::Acquire)
&& (!choosen_svr.available.load(Ordering::Acquire)
|| svr.elapsed.load(Ordering::Acquire) < choosen_svr.elapsed.load(Ordering::Acquire))
{
found_one = true;
choosen_svr = svr;
}
}
if !found_one && !choosen_svr.available.load(Ordering::Acquire) {
// Just choose one available
for svr in &self.servers {
if svr.available.load(Ordering::Acquire) {
choosen_svr = svr;
}
}
debug!(
"cannot find any available servers, picked {} delay {} ms",
choosen_svr.config.addr(),
choosen_svr.elapsed.load(Ordering::Acquire)
);
} else {
debug!(
"choosen the best server {} delay {} ms",
choosen_svr.config.addr(),
choosen_svr.elapsed.load(Ordering::Acquire)
);
}
choosen_svr.config.clone()
}
fn total(&self) -> usize {
self.servers.len()
}
}
| true
|
18c5c392f4b1fa1a8e0cb5e2da0ca4acd66485a2
|
Rust
|
YuichiroSato/banner-of-life
|
/src/mold.rs
|
UTF-8
| 6,923
| 3.078125
| 3
|
[
"MIT"
] |
permissive
|
use cells::*;
use fonts::*;
pub struct Mold {
pub font_size: usize,
pub target: Cells,
}
impl Mold {
pub fn new(font: Font, font_size: usize) -> Self {
let mold_scale = font_size as f64 / font.val.len() as f64;
let mut cells = Cells::new(font_size, font_size);
cells.allocate(Cells::from_font(font), 0, 0, mold_scale);
Mold {
font_size: font_size,
target: cells,
}
}
pub fn from_char(c: char, font_size: usize) -> Self {
match c {
'A' => Mold::new(FONT_A, font_size),
'B' => Mold::new(FONT_B, font_size),
'C' => Mold::new(FONT_C, font_size),
'D' => Mold::new(FONT_D, font_size),
'E' => Mold::new(FONT_E, font_size),
'F' => Mold::new(FONT_F, font_size),
'G' => Mold::new(FONT_G, font_size),
'H' => Mold::new(FONT_H, font_size),
'I' => Mold::new(FONT_I, font_size),
'J' => Mold::new(FONT_J, font_size),
'K' => Mold::new(FONT_K, font_size),
'L' => Mold::new(FONT_L, font_size),
'N' => Mold::new(FONT_N, font_size),
'M' => Mold::new(FONT_M, font_size),
'O' => Mold::new(FONT_O, font_size),
'P' => Mold::new(FONT_P, font_size),
'Q' => Mold::new(FONT_Q, font_size),
'R' => Mold::new(FONT_R, font_size),
'S' => Mold::new(FONT_S, font_size),
'T' => Mold::new(FONT_T, font_size),
'U' => Mold::new(FONT_U, font_size),
'V' => Mold::new(FONT_V, font_size),
'W' => Mold::new(FONT_W, font_size),
'X' => Mold::new(FONT_X, font_size),
'Y' => Mold::new(FONT_Y, font_size),
'Z' => Mold::new(FONT_Z, font_size),
'a' => Mold::new(FONT_CASE_A, font_size),
'b' => Mold::new(FONT_CASE_B, font_size),
'c' => Mold::new(FONT_CASE_C, font_size),
'd' => Mold::new(FONT_CASE_D, font_size),
'e' => Mold::new(FONT_CASE_E, font_size),
'f' => Mold::new(FONT_CASE_F, font_size),
'g' => Mold::new(FONT_CASE_G, font_size),
'h' => Mold::new(FONT_CASE_H, font_size),
'i' => Mold::new(FONT_CASE_I, font_size),
'j' => Mold::new(FONT_CASE_J, font_size),
'k' => Mold::new(FONT_CASE_K, font_size),
'l' => Mold::new(FONT_CASE_L, font_size),
'n' => Mold::new(FONT_CASE_N, font_size),
'm' => Mold::new(FONT_CASE_M, font_size),
'o' => Mold::new(FONT_CASE_O, font_size),
'p' => Mold::new(FONT_CASE_P, font_size),
'q' => Mold::new(FONT_CASE_Q, font_size),
'r' => Mold::new(FONT_CASE_R, font_size),
's' => Mold::new(FONT_CASE_S, font_size),
't' => Mold::new(FONT_CASE_T, font_size),
'u' => Mold::new(FONT_CASE_U, font_size),
'v' => Mold::new(FONT_CASE_V, font_size),
'w' => Mold::new(FONT_CASE_W, font_size),
'x' => Mold::new(FONT_CASE_X, font_size),
'y' => Mold::new(FONT_CASE_Y, font_size),
'z' => Mold::new(FONT_CASE_Z, font_size),
'1' => Mold::new(FONT_1, font_size),
'2' => Mold::new(FONT_2, font_size),
'3' => Mold::new(FONT_3, font_size),
'4' => Mold::new(FONT_4, font_size),
'5' => Mold::new(FONT_5, font_size),
'6' => Mold::new(FONT_6, font_size),
'7' => Mold::new(FONT_7, font_size),
'8' => Mold::new(FONT_8, font_size),
'9' => Mold::new(FONT_9, font_size),
'0' => Mold::new(FONT_0, font_size),
_ => Mold::new(FONT_EMPTY, font_size),
}
}
pub fn intersect(&self, cells: &Cells) -> u64 {
let mut count = 0;
for x in 0..self.target.size_x {
for y in 0..self.target.size_y {
if self.target.is_alive(x, y) && cells.is_alive(x, y) {
count += 1;
}
}
}
count
}
pub fn difference(&self, cells: &Cells) -> u64 {
let mut count = 0;
for x in 0..self.target.size_x {
for y in 0..self.target.size_y {
if !self.target.is_alive(x, y) && cells.is_alive(x, y) {
count += 1;
}
}
}
count
}
}
#[test]
fn test_intersect() {
let test_font = Font {
val : &[
&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
&[0, 0, 0, 0, 1, 1, 1, 1, 0, 0],
&[0, 0, 0, 0, 1, 1, 1, 1, 0, 0],
&[0, 0, 1, 1, 0, 0, 0, 0, 0, 0],
&[0, 0, 1, 1, 0, 0, 0, 0, 0, 0],
&[0, 0, 1, 1, 0, 0, 0, 0, 0, 0],
&[0, 0, 1, 1, 0, 0, 0, 0, 0, 0],
&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
]
};
let test_font2 = Font {
val : &[
&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
&[0, 0, 1, 0, 0, 0, 0, 0, 0, 0],
&[0, 0, 1, 0, 1, 0, 0, 0, 0, 0],
&[0, 0, 1, 0, 1, 0, 0, 0, 0, 0],
&[0, 0, 1, 0, 1, 0, 0, 0, 0, 0],
&[0, 0, 1, 0, 1, 0, 0, 0, 0, 0],
&[0, 0, 1, 0, 1, 0, 0, 0, 0, 0],
&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
]
};
let mold = Mold::new(test_font, 20);
let mut cells = Cells::new(20, 20);
cells.allocate(Cells::from_font(test_font2), 0, 0, 2.0);
assert_eq!(20, mold.intersect(&cells));
}
#[test]
fn test_difference() {
let test_font = Font {
val : &[
&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
&[0, 0, 0, 0, 1, 1, 1, 1, 0, 0],
&[0, 0, 0, 0, 1, 1, 1, 1, 0, 0],
&[0, 0, 1, 1, 0, 0, 0, 0, 0, 0],
&[0, 0, 1, 1, 0, 0, 0, 0, 0, 0],
&[0, 0, 1, 1, 0, 0, 0, 0, 0, 0],
&[0, 0, 1, 1, 0, 0, 0, 0, 0, 0],
&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
]
};
let test_font2 = Font {
val : &[
&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
&[0, 0, 1, 0, 1, 0, 0, 0, 0, 0],
&[0, 0, 1, 0, 1, 0, 0, 0, 0, 0],
&[0, 0, 1, 0, 1, 0, 0, 0, 0, 0],
&[0, 0, 1, 0, 1, 0, 0, 0, 0, 0],
&[0, 0, 1, 0, 1, 0, 0, 0, 0, 0],
&[0, 0, 1, 0, 1, 0, 0, 0, 0, 0],
&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
]
};
let mold = Mold::new(test_font, 20);
let mut cells = Cells::new(20, 20);
cells.allocate(Cells::from_font(test_font2), 0, 0, 2.0);
assert_eq!(24, mold.difference(&cells));
}
| true
|
19bdea239e39e906186270d3e26e99d6af954deb
|
Rust
|
cyb0124/OCRemote
|
/server/RustImpl/src/item.rs
|
UTF-8
| 3,797
| 2.84375
| 3
|
[] |
no_license
|
use super::lua_value::{table_remove, Table, Value};
use flexstr::LocalStr;
use std::{cmp::min, convert::TryInto, rc::Rc};
#[derive(PartialEq, Eq, Hash)]
pub struct Item {
pub label: LocalStr,
pub name: LocalStr,
pub damage: i16,
pub max_damage: i16,
pub max_size: i32,
pub has_tag: bool,
pub others: Table,
}
impl Item {
pub fn serialize(&self) -> Value {
let mut result = self.others.clone();
result.insert("label".into(), self.label.clone().into());
result.insert("name".into(), self.name.clone().into());
result.insert("damage".into(), self.damage.into());
result.insert("maxDamage".into(), self.max_damage.into());
result.insert("maxSize".into(), self.max_size.into());
result.insert("hasTag".into(), self.has_tag.into());
result.into()
}
}
pub fn jammer() -> Rc<Item> {
thread_local!(static ITEM: Rc<Item> = Rc::new(Item {
label: <_>::default(),
name: <_>::default(),
damage: 0,
max_damage: 0,
max_size: 1,
has_tag: false,
others: Table::new()
}));
ITEM.with(|item| item.clone())
}
#[derive(Clone)]
pub struct ItemStack {
pub item: Rc<Item>,
pub size: i32,
}
impl ItemStack {
pub fn parse(value: Value) -> Result<Self, LocalStr> {
let mut table: Table = value.try_into()?;
let size = table_remove(&mut table, "size")?;
let label = table_remove(&mut table, "label")?;
let name = table_remove(&mut table, "name")?;
let damage = table_remove(&mut table, "damage")?;
let max_damage = table_remove(&mut table, "maxDamage")?;
let max_size = table_remove(&mut table, "maxSize")?;
let has_tag = table_remove(&mut table, "hasTag")?;
Ok(ItemStack {
item: Rc::new(Item { label, name, damage, max_damage, max_size, has_tag, others: table }),
size,
})
}
}
pub struct InsertPlan {
pub n_inserted: i32,
pub insertions: Vec<(usize, i32)>,
}
pub fn insert_into_inventory(inventory: &mut Vec<Option<ItemStack>>, item: &Rc<Item>, to_insert: i32) -> InsertPlan {
let mut result = InsertPlan { n_inserted: 0, insertions: Vec::new() };
let mut remaining = min(to_insert, item.max_size);
let mut first_empty_slot = None;
for (slot, stack) in inventory.iter_mut().enumerate() {
if remaining <= 0 {
return result;
}
if let Some(stack) = stack {
if stack.item == *item {
let to_insert = min(remaining, item.max_size - stack.size);
if to_insert > 0 {
stack.size += to_insert;
result.n_inserted += to_insert;
result.insertions.push((slot, to_insert));
remaining -= to_insert
}
}
} else if first_empty_slot.is_none() {
first_empty_slot = Some(slot)
}
}
if remaining > 0 {
if let Some(slot) = first_empty_slot {
inventory[slot] = Some(ItemStack { item: item.clone(), size: remaining });
result.n_inserted += remaining;
result.insertions.push((slot, remaining))
}
}
result
}
#[derive(Clone)]
pub enum Filter {
Label(LocalStr),
Name(LocalStr),
Both { label: LocalStr, name: LocalStr },
Custom { desc: LocalStr, func: Rc<dyn Fn(&Item) -> bool> },
}
impl Filter {
pub fn apply(&self, item: &Item) -> bool {
match self {
Filter::Label(label) => item.label == *label,
Filter::Name(name) => item.name == *name,
Filter::Both { label, name } => item.label == *label && item.name == *name,
Filter::Custom { func, .. } => func(item),
}
}
}
| true
|
ee3b66d3939b7d516edc1adfa2b998975fe8d0b4
|
Rust
|
jiegec/pinyin
|
/src/bin/train.rs
|
UTF-8
| 4,126
| 2.75
| 3
|
[] |
no_license
|
extern crate structopt;
use encoding_rs::GBK;
use pinyin;
use serde::Deserialize;
use std::collections::{BTreeMap, BTreeSet};
use std::fs::File;
use std::io::Read;
use std::path::PathBuf;
use structopt::StructOpt;
#[derive(Debug, Deserialize)]
pub struct News {
html: String,
time: String,
title: String,
url: String,
}
#[derive(StructOpt, Debug)]
#[structopt(name = "train")]
struct Opt {
/// pinyin mapping file
#[structopt(name = "pinyin", parse(from_os_str))]
pinyin: PathBuf,
/// data files
#[structopt(name = "files", parse(from_os_str))]
files: Vec<PathBuf>,
}
fn main() {
let opt = Opt::from_args();
// insert pinyin mapping
let mut all_char: BTreeSet<char> = BTreeSet::new();
let mut pinyin_data = Vec::new();
File::open(opt.pinyin)
.expect("pinyin")
.read_to_end(&mut pinyin_data)
.expect("read pinyin");
let pinyin = GBK.decode(&pinyin_data).0;
let mut model1: pinyin::Model<pinyin::Match1> = pinyin::Model::empty();
let mut model2: pinyin::Model<pinyin::Match2> = pinyin::Model::empty();
let mut model3: pinyin::Model<pinyin::Match3> = pinyin::Model::empty();
for line in pinyin.split(|ch| ch == '\r' || ch == '\n') {
if line.is_empty() {
continue;
}
let mut words = line.split(|ch| ch == ' ');
let pinyin = String::from(words.next().unwrap());
let chinese: Vec<char> = words.map(|s| s.chars().next().unwrap()).collect();
for ch in chinese.iter() {
all_char.insert(*ch);
}
model1.mapping.insert(pinyin.clone(), chinese.clone());
model2.mapping.insert(pinyin.clone(), chinese.clone());
model3.mapping.insert(pinyin.clone(), chinese.clone());
}
// collect probabilities
let mut count1: BTreeMap<pinyin::Match1Prefix, u32> = BTreeMap::new();
let mut occur1: BTreeMap<pinyin::Match1, u32> = BTreeMap::new();
let mut count2: BTreeMap<pinyin::Match2Prefix, u32> = BTreeMap::new();
let mut occur2: BTreeMap<pinyin::Match2, u32> = BTreeMap::new();
let mut count3: BTreeMap<pinyin::Match3Prefix, u32> = BTreeMap::new();
let mut occur3: BTreeMap<pinyin::Match3, u32> = BTreeMap::new();
for file in opt.files {
println!("Processing file {:?}", file);
let mut data = Vec::new();
File::open(file)
.expect("open")
.read_to_end(&mut data)
.expect("read");
let content = GBK.decode(&data).0;
for line in content.split(|ch| ch == '\r' || ch == '\n') {
if line.is_empty() {
continue;
}
let news: News = serde_json::from_str(line).expect("parsing");
let match1_iter = pinyin::Match1::iter(&news.html, &all_char);
for match1 in match1_iter {
*count1.entry(match1.get_prefix()).or_insert(0) += 1;
*occur1.entry(match1).or_insert(0) += 1;
}
let match2_iter = pinyin::Match2::iter(&news.html, &all_char);
for match2 in match2_iter {
*count2.entry(match2.get_prefix()).or_insert(0) += 1;
*occur2.entry(match2).or_insert(0) += 1;
}
let match3_iter = pinyin::Match3::iter(&news.html, &all_char);
for match3 in match3_iter {
*count3.entry(match3.get_prefix()).or_insert(0) += 1;
*occur3.entry(match3).or_insert(0) += 1;
}
}
}
for (match1, o) in &occur1 {
let prob = (*o as f64) / (*count1.get(&match1.get_prefix()).expect("found") as f64);
model1.prob.insert(*match1, prob);
}
for (match2, o) in &occur2 {
let prob = (*o as f64) / (*count2.get(&match2.get_prefix()).expect("found") as f64);
model2.prob.insert(*match2, prob);
}
for (match3, o) in &occur3 {
let prob = (*o as f64) / (*count3.get(&match3.get_prefix()).expect("found") as f64);
model3.prob.insert(*match3, prob);
}
println!("Saving...");
model1.save();
model2.save();
model3.save();
}
| true
|
76cbef304813c0f5c482c2ce919a76297de8126f
|
Rust
|
StevenMeng5898/zCore
|
/zircon-object/src/signal/futex.rs
|
UTF-8
| 4,190
| 2.890625
| 3
|
[
"MIT"
] |
permissive
|
use super::*;
use crate::object::*;
use alloc::collections::VecDeque;
use alloc::sync::Arc;
use core::future::Future;
use core::pin::Pin;
use core::sync::atomic::*;
use core::task::{Context, Poll, Waker};
use spin::Mutex;
/// A primitive for creating userspace synchronization tools.
///
/// ## SYNOPSIS
/// A **futex** is a Fast Userspace muTEX. It is a low level
/// synchronization primitive which is a building block for higher level
/// APIs such as `pthread_mutex_t` and `pthread_cond_t`.
/// Futexes are designed to not enter the kernel or allocate kernel
/// resources in the uncontested case.
pub struct Futex {
base: KObjectBase,
value: &'static AtomicI32,
inner: Mutex<FutexInner>,
}
impl_kobject!(Futex);
#[derive(Default)]
struct FutexInner {
waiter_queue: VecDeque<Waker>,
wake_num: usize,
}
impl Futex {
/// Create a new Futex.
pub fn new(value: &'static AtomicI32) -> Arc<Self> {
Arc::new(Futex {
base: KObjectBase::default(),
value,
inner: Mutex::new(FutexInner::default()),
})
}
/// Wait on a futex asynchronously.
///
/// This atomically verifies that `value_ptr` still contains the value `current_value`
/// and sleeps until the futex is made available by a call to [`wake`].
///
/// # SPURIOUS WAKEUPS
///
/// This implementation currently does not generate spurious wakeups.
///
/// [`wake`]: Futex::wake
pub fn wait_async(self: &Arc<Self>, current_value: i32) -> impl Future<Output = ZxResult<()>> {
struct FutexFuture {
futex: Arc<Futex>,
current_value: i32,
num: Option<usize>,
}
impl Future for FutexFuture {
type Output = ZxResult<()>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let mut inner = self.futex.inner.lock();
// if waiting, check wake num
if let Some(num) = self.num {
return if inner.wake_num > num {
Poll::Ready(Ok(()))
} else {
Poll::Pending
};
}
// first call, check value
let value = self.futex.value.load(Ordering::SeqCst);
if value != self.current_value {
return Poll::Ready(Err(ZxError::BAD_STATE));
}
// push to wait queue
let wait_num = inner.wake_num + inner.waiter_queue.len();
inner.waiter_queue.push_back(cx.waker().clone());
drop(inner);
self.num = Some(wait_num);
Poll::Pending
}
}
FutexFuture {
futex: self.clone(),
current_value,
num: None,
}
}
/// Wake some number of threads waiting on a futex.
///
/// It wakes at most `wake_count` of the waiters that are waiting on this futex.
/// Return the number of waiters that were woken up.
pub fn wake(&self, wake_count: usize) -> usize {
let mut inner = self.inner.lock();
for i in 0..wake_count {
if let Some(waker) = inner.waiter_queue.pop_front() {
waker.wake();
inner.wake_num += 1;
} else {
return i + 1;
}
}
wake_count
}
}
#[cfg(test)]
mod tests {
use super::*;
#[async_std::test]
async fn wait_async() {
static VALUE: AtomicI32 = AtomicI32::new(1);
let futex = Futex::new(&VALUE);
// inconsistent value should fail.
assert_eq!(futex.wait_async(0).await, Err(ZxError::BAD_STATE));
// spawn a new task to wake me up.
{
let futex = futex.clone();
async_std::task::spawn(async move {
VALUE.store(2, Ordering::SeqCst);
let count = futex.wake(1);
assert_eq!(count, 1);
});
}
// wait for wake.
futex.wait_async(1).await.unwrap();
assert_eq!(VALUE.load(Ordering::SeqCst), 2);
}
}
| true
|
50958c3e4ee708e254d48502a8e0be8986f57e5e
|
Rust
|
JRud52/Shape_Grammar_Parser
|
/src/parser.rs
|
UTF-8
| 578
| 3.46875
| 3
|
[] |
no_license
|
use lexer::Lexer;
use lexer::Token;
use lexer::Ident;
pub struct Parser {
lexer: Lexer,
}
impl Parser {
pub fn new(buffer: String) -> Parser {
let lexer = Lexer::new(buffer);
Parser {lexer: lexer}
}
pub fn parse(&mut self){
// loop through the buffer until all the tokens have been consumed
loop {
let token = match self.lexer.next(){
None => { println!("End of file"); break; },
Some(value) => value,
};
println!("{}", token.identifier );
}
}
}
| true
|
6ffea15c30b2445d837668f9ab3cae8a44be421d
|
Rust
|
cptroot/CS11C-to-Rust
|
/triangle_game.rs
|
UTF-8
| 2,601
| 3.3125
| 3
|
[] |
no_license
|
use std::io::println;
use triangle_routines::triangle_print;
mod triangle_routines;
static NUM_PEGS:int = 15;
static NUM_MOVES:int = 36;
static moves:[[int, ..3], ..NUM_MOVES] = [
[0, 1, 3],
[0, 2, 5],
[1, 3, 6],
[1, 4, 8],
[2, 4, 7],
[2, 5, 9],
[3, 1, 0],
[3, 4, 5],
[3, 6, 10],
[3, 7, 12],
[4, 7, 11],
[4, 8, 13],
[5, 2, 0],
[5, 4, 3],
[5, 8, 12],
[5, 9, 14],
[6, 3, 1],
[6, 7, 8],
[7, 4, 2],
[7, 8, 9],
[8, 4, 1],
[8, 7, 6],
[9, 5, 2],
[9, 8, 7],
[10, 6, 3],
[10, 11, 12],
[11, 7, 4],
[11, 12, 13],
[12, 7, 3],
[12, 8, 5],
[12, 11, 10],
[12, 13, 14],
[13, 8, 4],
[13, 12, 11],
[14, 9, 5],
[14, 13, 12]
];
fn main() {
let mut board = [false, ..NUM_PEGS];
/* Parse the input, assuming valid input */
triangle_routines::triangle_input(board);
/* Solve the board */
let result = solve(board);
/* If no solution, say so */
if result == false {
println("There are no solutions to the initial position given.");
}
}
/* Return the number of pegs on the board. */
fn num_pegs(board:&[bool]) -> int {
let mut sum = 0;
for peg in board.iter() { sum += *peg as int; }
return sum;
}
/* Return 1 if the move is valid on this board, otherwise return 0. */
fn valid_move(board:&[bool], move:&[int]) -> bool {
return board[move[0]] && board[move[1]] && (!board[move[2]]);
}
/* Make this move on this board. */
fn make_move(board:&mut [bool], move:&[int]) {
board[move[0]] = false;
board[move[1]] = false;
board[move[2]] = true;
}
/* Unmake this move on this board. */
fn unmake_move(board:&mut [bool], move:&[int]) {
board[move[0]] = true;
board[move[1]] = true;
board[move[2]] = false;
}
/*
* Solve the game starting from this board. Return 1 if the game can
* be solved; otherwise return 0. Do not permanently alter the board passed
* in. Once a solution is found, print the boards making up the solution in
* reverse order.
*/
fn solve(board:&mut [bool]) -> bool {
/* Check if the board is already solved. If it is, print it. */
if num_pegs(board) == 1 {
triangle_print(board);
return true;
}
/* For each move we could make, make it,
* and then try to solve the resulting board.
*/
for i in range(0, NUM_MOVES) {
if !valid_move(board, moves[i]) { continue; }
make_move(board, moves[i]);
/* If we find a solution, print the board and return true. */
if solve(board) {
unmake_move(board, moves[i]);
triangle_print(board);
return true;
}
unmake_move(board, moves[i]);
}
/* Return false */
return false;
}
| true
|
4a743810093d55654d437b127a00846e92f52c54
|
Rust
|
jiegec/decaf-rs-pa
|
/typeck/src/scope_stack.rs
|
UTF-8
| 3,304
| 3.046875
| 3
|
[] |
no_license
|
use std::iter;
use common::Loc;
use syntax::{ScopeOwner, Symbol, ClassDef, Program};
use std::collections::HashMap;
pub(crate) struct ScopeStack<'a> {
// `global` must be ScopeOwner::Global, but we will not depend on this, so just define it as ScopeOwner
global: ScopeOwner<'a>,
// ignore symbols whose loc >= item.1
// for local var def
stack: Vec<(ScopeOwner<'a>, Option<Loc>)>,
}
impl<'a> ScopeStack<'a> {
pub fn new(p: &'a Program<'a>) -> Self {
Self { global: ScopeOwner::Global(p), stack: vec![] }
}
pub fn lookup(&self, name: &'a str) -> Option<(Symbol<'a>, ScopeOwner<'a>)> {
self.stack.iter().rev().chain(iter::once(&(self.global, None)))
.filter_map(|&(owner, _loc)| owner.scope().get(name).map(|&sym| (sym, owner)))
.next()
}
// do lookup, but will ignore those local symbols whose loc >= item.1
// returns (symbol, across_lambda)
pub fn lookup_var_sel(&self, name: &'a str, loc: Loc) -> (Option<Symbol<'a>>, bool) {
let mut across_lambda = false;
for (owner, def_loc) in self.stack.iter().rev().chain(iter::once(&(self.global, None))) {
if let Some(sym) = owner.scope().get(name).cloned() {
if owner.is_local() && sym.loc() >= loc {
continue;
}
if let Some(def) = def_loc {
if def <= &sym.loc() {
continue;
}
}
if owner.is_class() {
// can write class variable, however
across_lambda = false;
}
return (Some(sym), across_lambda);
}
if owner.is_lambda() {
across_lambda = true;
}
}
(None, across_lambda)
}
pub fn declare(&mut self, sym: Symbol<'a>) {
self.cur_owner().scope_mut().insert(sym.name(), sym);
}
// if `owner` is ScopeOwner::Class, then will recursively open all its ancestors
pub fn open(&mut self, owner: ScopeOwner<'a>) {
if let ScopeOwner::Class(c) = owner {
if let Some(p) = c.parent_ref.get() {
self.open(ScopeOwner::Class(p));
}
}
self.stack.push((owner, None));
}
// the global scope is not affected
pub fn close(&mut self) {
let (owner, _loc) = self.stack.pop().unwrap();
if let ScopeOwner::Class(_) = owner {
self.stack.clear();
}
}
pub fn cur_owner(&self) -> ScopeOwner<'a> {
*self.stack.last().map(|t| &t.0).unwrap_or(&self.global)
}
pub fn lookup_class(&self, name: &'a str) -> Option<&'a ClassDef<'a>> {
self.global.scope().get(name).map(|class| match class {
Symbol::Class(c) => *c,
_ => unreachable!("Global scope should only contain classes."),
})
}
// Return a map of (function_name, abstract_)
pub fn collect_member_fun(&self) -> HashMap<&'a str, bool> {
let mut res = HashMap::new();
for (owner, _loc) in self.stack.iter() {
for (_, symbol) in owner.scope().iter() {
if let Symbol::Func(func) = symbol {
if !func.static_ {
res.insert(func.name, func.abstract_);
}
}
}
}
res
}
pub fn enter_var_def(&mut self, loc: Loc) {
if let Some((_owner, def_loc)) = self.stack.last_mut() {
*def_loc = Some(loc);
}
}
pub fn end_var_def(&mut self) {
if let Some((_owner, def_loc)) = self.stack.last_mut() {
*def_loc = None;
}
}
}
| true
|
437fa7b852ee1c87a38a1f4df0ecab2e63056a42
|
Rust
|
imbolc/perseus
|
/packages/perseus-cli/src/cmd.rs
|
UTF-8
| 3,771
| 3.390625
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
use crate::errors::*;
use console::Emoji;
use indicatif::{ProgressBar, ProgressStyle};
use std::io::Write;
use std::path::Path;
use std::process::Command;
// Some useful emojis
pub static SUCCESS: Emoji<'_, '_> = Emoji("✅", "success!");
pub static FAILURE: Emoji<'_, '_> = Emoji("❌", "failed!");
/// Runs the given command conveniently, returning the exit code. Notably, this parses the given command by separating it on spaces.
/// Returns the command's output and the exit code.
pub fn run_cmd(
cmd: String,
dir: &Path,
pre_dump: impl Fn(),
) -> Result<(String, String, i32), ExecutionError> {
// We run the command in a shell so that NPM/Yarn binaries can be recognized (see #5)
#[cfg(unix)]
let shell_exec = "sh";
#[cfg(windows)]
let shell_exec = "powershell";
#[cfg(unix)]
let shell_param = "-c";
#[cfg(windows)]
let shell_param = "-command";
// This will NOT pipe output/errors to the console
let output = Command::new(shell_exec)
.args([shell_param, &cmd])
.current_dir(dir)
.output()
.map_err(|err| ExecutionError::CmdExecFailed { cmd, source: err })?;
let exit_code = match output.status.code() {
Some(exit_code) => exit_code, // If we have an exit code, use it
None if output.status.success() => 0, // If we don't, but we know the command succeeded, return 0 (success code)
None => 1, // If we don't know an exit code but we know that the command failed, return 1 (general error code)
};
// Print `stderr` only if there's something therein and the exit code is non-zero
if !output.stderr.is_empty() && exit_code != 0 {
pre_dump();
std::io::stderr().write_all(&output.stderr).unwrap();
}
Ok((
String::from_utf8_lossy(&output.stdout).to_string(),
String::from_utf8_lossy(&output.stderr).to_string(),
exit_code,
))
}
/// Creates a new spinner.
pub fn cfg_spinner(spinner: ProgressBar, message: &str) -> ProgressBar {
spinner.set_style(ProgressStyle::default_spinner().tick_chars("⠁⠂⠄⡀⢀⠠⠐⠈ "));
spinner.set_message(format!("{}...", &message));
// Tick the spinner every 50 milliseconds
spinner.enable_steady_tick(50);
spinner
}
/// Instructs the given spinner to show success.
pub fn succeed_spinner(spinner: &ProgressBar, message: &str) {
spinner.finish_with_message(format!("{}...{}", message, SUCCESS));
}
/// Instructs the given spinner to show failure.
pub fn fail_spinner(spinner: &ProgressBar, message: &str) {
spinner.finish_with_message(format!("{}...{}", message, FAILURE));
}
/// Runs a series of commands. Returns the last command's output and an appropriate exit code (0 if everything worked, otherwise th
/// exit code of the first one that failed). This also takes a `Spinner` to use and control.
pub fn run_stage(
cmds: Vec<&str>,
target: &Path,
spinner: &ProgressBar,
message: &str,
) -> Result<(String, String, i32), ExecutionError> {
let mut last_output = (String::new(), String::new());
// Run the commands
for cmd in cmds {
// We make sure all commands run in the target directory ('.perseus/' itself)
let (stdout, stderr, exit_code) = run_cmd(cmd.to_string(), target, || {
// This stage has failed
fail_spinner(spinner, message);
})?;
last_output = (stdout, stderr);
// If we have a non-zero exit code, we should NOT continue (stderr has been written to the console already)
if exit_code != 0 {
return Ok((last_output.0, last_output.1, 1));
}
}
// Everything has worked for this stage
succeed_spinner(spinner, message);
Ok((last_output.0, last_output.1, 0))
}
| true
|
b5ea9e187e8010eeef29cd93e46276d54e8aec4f
|
Rust
|
green-s/skim
|
/src/reader.rs
|
UTF-8
| 7,917
| 3.09375
| 3
|
[
"MIT"
] |
permissive
|
///! Reader is used for reading items from datasource (e.g. stdin or command output)
///!
///! After reading in a line, reader will save an item into the pool(items)
use crate::field::FieldRange;
use crate::item::Item;
use crate::options::SkimOptions;
use crate::spinlock::SpinLock;
use regex::Regex;
use std::collections::HashMap;
use std::env;
use std::error::Error;
use std::io::{BufRead, BufReader};
use std::process::{Child, Command, Stdio};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, RwLock};
use std::thread;
use std::thread::JoinHandle;
use std::time::Duration;
const DELIMITER_STR: &str = r"[\t\n ]+";
pub struct ReaderControl {
stopped: Arc<AtomicBool>,
thread_reader: JoinHandle<()>,
items: Arc<SpinLock<Vec<Arc<Item>>>>,
}
impl ReaderControl {
pub fn kill(self) {
self.stopped.store(true, Ordering::SeqCst);
let _ = self.thread_reader.join();
}
pub fn take(&self) -> Vec<Arc<Item>> {
let mut items = self.items.lock();
let mut ret = Vec::with_capacity(items.len());
ret.append(&mut items);
ret
}
pub fn is_done(&self) -> bool {
let items = self.items.lock();
self.stopped.load(Ordering::Relaxed) && items.is_empty()
}
}
pub struct Reader {
option: Arc<ReaderOption>,
source_file: Option<Box<dyn BufRead + Send>>,
}
impl Reader {
pub fn with_options(options: &SkimOptions) -> Self {
Self {
option: Arc::new(ReaderOption::with_options(&options)),
source_file: None,
}
}
pub fn source(mut self, source_file: Option<Box<dyn BufRead + Send>>) -> Self {
self.source_file = source_file;
self
}
pub fn run(&mut self, cmd: &str) -> ReaderControl {
let stopped = Arc::new(AtomicBool::new(false));
let stopped_clone = stopped.clone();
stopped.store(false, Ordering::SeqCst);
let items = Arc::new(SpinLock::new(Vec::new()));
let items_clone = items.clone();
let option_clone = self.option.clone();
let source_file = self.source_file.take();
let cmd = cmd.to_string();
// start the new command
let thread_reader = thread::spawn(move || {
reader(&cmd, stopped_clone, items_clone, option_clone, source_file);
});
ReaderControl {
stopped,
thread_reader,
items,
}
}
}
struct ReaderOption {
pub use_ansi_color: bool,
pub default_arg: String,
pub transform_fields: Vec<FieldRange>,
pub matching_fields: Vec<FieldRange>,
pub delimiter: Regex,
pub replace_str: String,
pub line_ending: u8,
}
impl ReaderOption {
pub fn new() -> Self {
ReaderOption {
use_ansi_color: false,
default_arg: String::new(),
transform_fields: Vec::new(),
matching_fields: Vec::new(),
delimiter: Regex::new(DELIMITER_STR).unwrap(),
replace_str: "{}".to_string(),
line_ending: b'\n',
}
}
pub fn with_options(options: &SkimOptions) -> Self {
let mut reader_option = Self::new();
reader_option.parse_options(&options);
reader_option
}
fn parse_options(&mut self, options: &SkimOptions) {
if options.ansi {
self.use_ansi_color = true;
}
if let Some(delimiter) = options.delimiter {
self.delimiter = Regex::new(delimiter).unwrap_or_else(|_| Regex::new(DELIMITER_STR).unwrap());
}
if let Some(transform_fields) = options.with_nth {
self.transform_fields = transform_fields
.split(',')
.filter_map(|string| FieldRange::from_str(string))
.collect();
}
if let Some(matching_fields) = options.nth {
self.matching_fields = matching_fields
.split(',')
.filter_map(|string| FieldRange::from_str(string))
.collect();
}
if options.read0 {
self.line_ending = b'\0';
}
}
}
type CommandOutput = (Option<Child>, Box<dyn BufRead + Send>);
fn get_command_output(cmd: &str) -> Result<CommandOutput, Box<dyn Error>> {
let shell = env::var("SHELL").unwrap_or_else(|_| "sh".to_string());
let mut command = Command::new(shell)
.arg("-c")
.arg(cmd)
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()?;
let stdout = command
.stdout
.take()
.ok_or_else(|| "command output: unwrap failed".to_owned())?;
Ok((Some(command), Box::new(BufReader::new(stdout))))
}
// Consider that you invoke a command with different arguments several times
// If you select some items each time, how will skim remeber it?
// => Well, we'll give each invokation a number, i.e. RUN_NUM
// What if you invoke the same command and same arguments twice?
// => We use NUM_MAP to specify the same run number.
lazy_static! {
static ref RUN_NUM: RwLock<usize> = RwLock::new(0);
static ref NUM_MAP: RwLock<HashMap<String, usize>> = RwLock::new(HashMap::new());
}
fn reader(
cmd: &str,
stopped: Arc<AtomicBool>,
items: Arc<SpinLock<Vec<Arc<Item>>>>,
option: Arc<ReaderOption>,
source_file: Option<Box<dyn BufRead + Send>>,
) {
let (command, mut source) = source_file
.map(|f| (None, f))
.unwrap_or_else(|| get_command_output(cmd).expect("command not found"));
let command_stopped = Arc::new(AtomicBool::new(false));
let stopped_clone = stopped.clone();
let command_stopped_clone = command_stopped.clone();
thread::spawn(move || {
// kill command if it is got
while command.is_some() && !stopped_clone.load(Ordering::Relaxed) {
thread::sleep(Duration::from_millis(5));
}
// clean up resources
if let Some(mut x) = command {
let _ = x.kill();
let _ = x.wait();
}
command_stopped_clone.store(true, Ordering::Relaxed);
});
let opt = option;
// set the proper run number
let run_num = { *RUN_NUM.read().expect("reader: failed to lock RUN_NUM") };
let run_num = *NUM_MAP
.write()
.expect("reader: failed to lock NUM_MAP")
.entry(cmd.to_string())
.or_insert_with(|| {
*(RUN_NUM.write().expect("reader: failed to lock RUN_NUM for write")) = run_num + 1;
run_num + 1
});
let mut index = 0;
let mut buffer = Vec::with_capacity(100);
loop {
buffer.clear();
// start reading
match source.read_until(opt.line_ending, &mut buffer) {
Ok(n) => {
if n == 0 {
break;
}
if buffer.ends_with(&[b'\r', b'\n']) {
buffer.pop();
buffer.pop();
} else if buffer.ends_with(&[b'\n']) || buffer.ends_with(&[b'\0']) {
buffer.pop();
}
let item = Item::new(
String::from_utf8_lossy(&buffer),
opt.use_ansi_color,
&opt.transform_fields,
&opt.matching_fields,
&opt.delimiter,
(run_num, index),
);
{
// save item into pool
let mut vec = items.lock();
vec.push(Arc::new(item));
index += 1;
}
if stopped.load(Ordering::SeqCst) {
break;
}
}
Err(_err) => {} // String not UTF8 or other error, skip.
}
}
stopped.store(true, Ordering::Relaxed);
while !command_stopped.load(Ordering::Relaxed) {
thread::sleep(Duration::from_millis(5));
}
}
| true
|
edcb19c31eea0b027c430d1571f74172d8af1263
|
Rust
|
palantir/conjure-rust
|
/conjure-object/src/bearer_token/mod.rs
|
UTF-8
| 5,722
| 2.78125
| 3
|
[
"Apache-2.0"
] |
permissive
|
// Copyright 2018 Palantir Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! The Conjure `bearertoken` type.
use serde::de::{self, Deserialize, Deserializer, Unexpected};
use serde::ser::{Serialize, Serializer};
use std::borrow::Borrow;
use std::error::Error;
use std::fmt;
use std::str::FromStr;
#[cfg(test)]
mod test;
// A lookup table mapping valid characters to themselves and invalid characters to 0. We don't actually care what
// nonzero value valid characters map to, but it's easier to read this way. There's a test making sure that the mapping
// is consistent.
#[rustfmt::skip]
static VALID_CHARS: [u8; 256] = [
// 0 1 2 3 4 5 6 7 8 9
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // x
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 1x
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 2x
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 3x
0, 0, 0, b'+', 0, b'-', b'.', b'/', b'0', b'1', // 4x
b'2', b'3', b'4', b'5', b'6', b'7', b'8', b'9', 0, 0, // 5x
0, 0, 0, 0, 0, b'A', b'B', b'C', b'D', b'E', // 6x
b'F', b'G', b'H', b'I', b'J', b'K', b'L', b'M', b'N', b'O', // 7x
b'P', b'Q', b'R', b'S', b'T', b'U', b'V', b'W', b'X', b'Y', // 8x
b'Z', 0, 0, 0, 0, b'_', 0, b'a', b'b', b'c', // 9x
b'd', b'e', b'f', b'g', b'h', b'i', b'j', b'k', b'l', b'm', // 10x
b'n', b'o', b'p', b'q', b'r', b's', b't', b'u', b'v', b'w', // 11x
b'x', b'y', b'z', 0, 0, 0, b'~', 0, 0, 0, // 12x
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 13x
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 14x
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 15x
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16x
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 17x
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 18x
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 19x
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 20x
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 21x
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 22x
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 23x
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 24x
0, 0, 0, 0, 0, 0, // 25x
];
/// An authentication bearer token.
///
/// Bearer tokens are strings which match the regular expression `^[A-Za-z0-9\-\._~\+/]+=*$`.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct BearerToken(String);
impl BearerToken {
/// Creates a bearer token from a string, validating that it is in the correct format.
///
/// This function behaves identically to `BearerToken`'s `FromStr` implementation.
#[inline]
pub fn new(s: &str) -> Result<BearerToken, ParseError> {
s.parse()
}
/// Returns the string representation of the bearer token.
#[inline]
pub fn as_str(&self) -> &str {
&self.0
}
/// Consumes the bearer token, returning its owned string representation.
#[inline]
pub fn into_string(self) -> String {
self.0
}
}
impl AsRef<str> for BearerToken {
#[inline]
fn as_ref(&self) -> &str {
&self.0
}
}
impl Borrow<str> for BearerToken {
#[inline]
fn borrow(&self) -> &str {
&self.0
}
}
impl fmt::Debug for BearerToken {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.debug_tuple("BearerToken").field(&"REDACTED").finish()
}
}
impl FromStr for BearerToken {
type Err = ParseError;
fn from_str(s: &str) -> Result<BearerToken, ParseError> {
if !is_valid(s) {
return Err(ParseError(()));
}
Ok(BearerToken(s.to_string()))
}
}
impl Serialize for BearerToken {
fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
self.0.serialize(s)
}
}
impl<'de> Deserialize<'de> for BearerToken {
fn deserialize<D>(d: D) -> Result<BearerToken, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(d)?;
if is_valid(&s) {
Ok(BearerToken(s))
} else {
Err(de::Error::invalid_value(
Unexpected::Str(&s),
&"a bearer token",
))
}
}
}
fn is_valid(s: &str) -> bool {
let stripped = s.trim_end_matches('=');
if stripped.is_empty() || !stripped.as_bytes().iter().cloned().all(valid_char) {
return false;
}
true
}
// implementing this via a lookup table rather than a match is ~25% faster.
fn valid_char(b: u8) -> bool {
VALID_CHARS[b as usize] != 0
}
/// An error parsing a string into a `BearerToken`.
#[derive(Debug)]
pub struct ParseError(());
impl fmt::Display for ParseError {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.write_str("invalid bearer token")
}
}
impl Error for ParseError {}
| true
|
64922898e2698e1954014a01a22cbee96af481ad
|
Rust
|
alanhoff/rust-v8-experiments
|
/src/core/communication.rs
|
UTF-8
| 1,121
| 2.578125
| 3
|
[
"ISC"
] |
permissive
|
use crate::runtime::Runtime;
use std::{future::Future, pin::Pin};
use tokio::sync::mpsc;
use std::{cell::RefCell, rc::Rc};
pub type SyncMessage = Box<dyn FnOnce(&Runtime)>;
pub type AsyncMessage = Box<dyn FnOnce(&Runtime) -> Pin<Box<dyn Future<Output = ()>>>>;
pub struct Channel {
pub tx: mpsc::UnboundedSender<AsyncMessage>,
pub rx: Rc<RefCell<mpsc::UnboundedReceiver<AsyncMessage>>>,
}
impl Default for Channel {
fn default() -> Self {
Self::new()
}
}
impl Channel {
pub fn new() -> Self {
let (tx, rx) = mpsc::unbounded_channel();
Self { tx, rx: Rc::new(RefCell::new(rx)) }
}
pub fn sync_sender(&self) -> Box<dyn Fn(SyncMessage)> {
let tx = self.tx.clone();
Box::new(move |func| {
let _ = tx.send(Box::new(move |runtime| {
func(runtime);
Box::pin(async {})
})).is_ok();
})
}
pub fn sender(&self) -> Box<dyn Fn(AsyncMessage)> {
let tx = self.tx.clone();
Box::new(move |func| {
let _ = tx.send(Box::new(move |runtime| {
func(runtime)
})).is_ok();
})
}
}
| true
|
0d73219a8b572df6557cb4e0140efc564bc74ab6
|
Rust
|
sugyan/leetcode
|
/problems/0946-validate-stack-sequences/lib.rs
|
UTF-8
| 958
| 3.578125
| 4
|
[] |
no_license
|
pub struct Solution;
impl Solution {
pub fn validate_stack_sequences(pushed: Vec<i32>, popped: Vec<i32>) -> bool {
let mut stack = Vec::with_capacity(pushed.len());
let mut iter = popped.iter().peekable();
for n in &pushed {
stack.push(n);
while !stack.is_empty() && stack.last() == iter.peek() {
stack.pop();
iter.next();
}
}
stack.is_empty()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[allow(clippy::bool_assert_comparison)]
#[test]
fn example_1() {
assert_eq!(
true,
Solution::validate_stack_sequences(vec![1, 2, 3, 4, 5], vec![4, 5, 3, 2, 1])
);
}
#[allow(clippy::bool_assert_comparison)]
#[test]
fn example_2() {
assert_eq!(
false,
Solution::validate_stack_sequences(vec![1, 2, 3, 4, 5], vec![4, 3, 5, 1, 2])
);
}
}
| true
|
0a85ffe7d89c46f022dcae1ade88f1d0424da55b
|
Rust
|
nerdalert/rust-examples
|
/json/src/main.rs
|
UTF-8
| 1,307
| 3.109375
| 3
|
[
"WTFPL"
] |
permissive
|
#[macro_use] // required for the use of the json! macro on line #26
extern crate serde_json;
use serde_json::Value;
fn extract(json: &Value, path: String, extracted: &mut Vec<(String, String)>) {
match json {
Value::String(s) => extracted.push((path, s.clone())),
Value::Null => extracted.push((path, "null".to_string())),
Value::Number(n) => extracted.push((path, n.to_string())),
Value::Bool(b) => extracted.push((path, b.to_string())),
Value::Object(m) => {
for (k, v) in m {
extract(v, format!("{}/{}", path, k), extracted);
}
}
Value::Array(a) => {
for (i, v) in a.iter().enumerate() {
extract(v, format!("{}[{}]", path, i), extracted);
}
}
}
}
fn main() {
let test = json! {
{
"things": {
"pet": {
"cat": "muffy",
"dog": "fido"
},
"servers": {
"srv1": "192.168.100.10",
"srv2": "10.100.10.50"
}
}
}
};
let mut parsed_json = Vec::new();
let root = "".to_string();
extract(&test, root, &mut parsed_json);
println!("{:?}", parsed_json);
}
| true
|
bd5d796deb3e5d1081cb08b0859df15c6c41c4a7
|
Rust
|
ecc521/experiments
|
/char_counter.rs
|
UTF-8
| 251
| 3.34375
| 3
|
[] |
no_license
|
use std::io;
fn main() {
println!("Please input some text");
let mut text = String::new();
io::stdin().read_line(&mut text)
.expect("Error reading line");
println!("You input {}", text);
println!("That is {} characters", text.len())
}
| true
|
69fec51d504f256861a7409700a3571933c5b28d
|
Rust
|
krisprice/playground
|
/aggip/src/main.rs
|
UTF-8
| 709
| 2.8125
| 3
|
[] |
no_license
|
// Created external crate and moved all types and methods there.
extern crate ipnet;
use ipnet::IpNet;
fn main() {
let strings = vec![
"10.0.0.0/24", "10.0.1.0/24", "10.0.1.1/24", "10.0.1.2/24",
"10.0.2.0/24",
"10.1.0.0/24", "10.1.1.0/24",
"192.168.0.0/24", "192.168.1.0/24", "192.168.2.0/24", "192.168.3.0/24",
"fd00::/32", "fd00:1::/32",
];
let nets: Vec<IpNet> = strings.iter().filter_map(|p| p.parse().ok()).collect();
println!("\nInput IP prefix list:");
for n in &nets {
println!("{}", n);
}
println!("\nAggregated IP prefixes:");
for n in IpNet::aggregate(&nets) {
println!("{}", n);
}
}
| true
|
4d8bb77bb0b300cb8f83c7ae8c2fbcceb67fa7d1
|
Rust
|
cassandraoconnell/rustdown
|
/src/document/matchers/selection.rs
|
UTF-8
| 2,469
| 3.5
| 4
|
[] |
no_license
|
use super::utils::matcher::{LeftoverString, MatchedString, Matcher, RejectedString};
pub struct SelectionMatcher {
selection: Vec<String>,
}
impl Matcher for SelectionMatcher {
fn try_match(&self, input: String) -> Result<(MatchedString, LeftoverString), RejectedString> {
let mut unconsumed = String::new();
if let Some(matched_selection) = self.selection.iter().find(|selection| {
let mut consumed = String::new();
let mut to_match = input.chars();
for selection_character in selection.chars() {
if let Some(character_to_match) = to_match.next() {
consumed.push(character_to_match);
if character_to_match == selection_character {
continue;
}
break;
}
}
if consumed == **selection {
unconsumed = to_match.collect();
return true;
}
false
}) {
return Ok((String::from(matched_selection), unconsumed));
}
Err(input)
}
}
impl From<Vec<String>> for SelectionMatcher {
fn from(selection: Vec<String>) -> Self {
SelectionMatcher { selection }
}
}
#[cfg(test)]
mod tests {
use super::{Matcher, SelectionMatcher};
#[test]
fn it_accepts_matched_and_returns_leftover() {
let a_or_b_matcher = SelectionMatcher::from(vec![String::from('a'), String::from('b')]);
assert_eq!(
a_or_b_matcher.try_match(String::from('a')),
Ok((String::from('a'), String::new()))
);
assert_eq!(
a_or_b_matcher.try_match(String::from('b')),
Ok((String::from('b'), String::new()))
);
assert_eq!(
a_or_b_matcher.try_match(String::from("abc")),
Ok((String::from('a'), String::from("bc")))
);
assert_eq!(
a_or_b_matcher.try_match(String::from("bc")),
Ok((String::from('b'), String::from('c')))
);
}
#[test]
fn it_rejects_mismatched_and_returns_original() {
let a_or_b_matcher = SelectionMatcher::from(vec![String::from('a'), String::from('b')]);
assert_eq!(
a_or_b_matcher.try_match(String::from('c')),
Err(String::from('c'))
);
assert_eq!(a_or_b_matcher.try_match(String::new()), Err(String::new()));
}
}
| true
|
bf3739d66c5bf48e2722519142e66bfe9416a8bc
|
Rust
|
LordAro/AdventOfCode
|
/2016/src/bin/day12.rs
|
UTF-8
| 2,504
| 3.21875
| 3
|
[] |
no_license
|
use std::collections::HashMap;
use std::env;
use std::fs::File;
use std::io::{BufRead, BufReader};
fn parse_reg(word: &str) -> Option<char> {
word.chars().next()
}
fn run_prog(registers: &mut HashMap<char, i32>, prog: &Vec<Vec<&str>>) {
let mut pc = 0;
while pc < prog.len() {
let ins = &prog[pc];
match ins[0] {
"cpy" => {
let reg = parse_reg(ins[2]).unwrap();
if let Ok(val) = ins[1].parse() {
registers.insert(reg, val);
} else {
let val = *registers.get(&parse_reg(ins[1]).unwrap()).unwrap();
registers.insert(reg, val);
}
}
"inc" | "dec" => {
let reg = parse_reg(ins[1]).unwrap();
*registers.get_mut(®).unwrap() += if ins[0] == "inc" { 1 } else { -1 };
}
"jnz" => {
let val: i32 = ins[2].parse().unwrap();
if let Ok(reg) = ins[1].parse::<i32>() {
if reg != 0 {
pc = (pc as i32 + (val - 1)) as usize; // -1 because of increment at end of loop
}
} else {
let reg = parse_reg(ins[1]).unwrap();
if *registers.get(®).unwrap() != 0 {
pc = (pc as i32 + (val - 1)) as usize; // -1 because of increment at end of loop
}
}
}
_ => panic!("Unrecognised instruction: {}", ins[0]),
}
pc += 1;
}
}
fn main() {
if env::args().len() != 2 {
panic!("Incorrect number of arguments provided\n");
}
let input: Vec<_> = BufReader::new(File::open(env::args().nth(1).unwrap()).unwrap())
.lines()
.map(|l| l.unwrap())
.collect();
let prog: Vec<Vec<_>> = input
.iter()
.map(|l| l.split_whitespace().collect())
.collect();
let mut registers: HashMap<char, i32> = HashMap::new();
registers.insert('a', 0);
registers.insert('b', 0);
registers.insert('c', 0);
registers.insert('d', 0);
run_prog(&mut registers, &prog);
println!("Value of register a: {}", *registers.get(&'a').unwrap());
registers.insert('a', 0);
registers.insert('b', 0);
registers.insert('c', 1);
registers.insert('d', 0);
run_prog(&mut registers, &prog);
println!("Value of register a: {}", *registers.get(&'a').unwrap());
}
| true
|
23c6848048de2cfe1522ee919353532a98f5e894
|
Rust
|
t3m8ch/another-todolist
|
/src/models.rs
|
UTF-8
| 816
| 3.265625
| 3
|
[
"MIT"
] |
permissive
|
use std::collections::HashMap;
use crate::errors::DeleteTodoError;
#[derive(Debug)]
pub struct Todo {
pub title: String,
pub body: String
}
pub struct TodoStore {
todos: HashMap<u32, Todo>
}
impl TodoStore {
pub fn new() -> TodoStore {
TodoStore { todos: HashMap::new() }
}
pub fn add(&mut self, todo: Todo) {
let id = match self.todos.keys().max() {
Some(n) => n.clone() + 1,
None => 0
};
self.todos.insert(id, todo);
}
pub fn delete(&mut self, id: u32) -> Result<Todo, DeleteTodoError> {
match self.todos.remove(&id) {
Some(todo) => Ok(todo),
None => Err(DeleteTodoError::IdNotFound)
}
}
pub fn get_all(&self) -> &HashMap<u32, Todo> {
&self.todos
}
}
| true
|
c1ee946158b78c4265e1f727ed869f3c33bcd0cb
|
Rust
|
icodinglife/ouch
|
/tests/compress_and_decompress.rs
|
UTF-8
| 8,281
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
mod utils;
use std::{
env,
io::prelude::*,
path::{Path, PathBuf},
time::Duration,
};
use fs_err as fs;
use ouch::{commands::run, Opts, QuestionPolicy, Subcommand};
use rand::{rngs::SmallRng, RngCore, SeedableRng};
use tempfile::NamedTempFile;
use utils::*;
#[test]
/// Makes sure that the files ouch produces are what they claim to be, checking their
/// types through MIME sniffing.
fn sanity_check_through_mime() {
// Somehow this test causes test failures when run in parallel with test_each_format
// This is a temporary hack that should allow the tests to pass while this bug isn't solved.
std::thread::sleep(Duration::from_secs(2));
let temp_dir = tempfile::tempdir().expect("to build a temporary directory");
let mut test_file = NamedTempFile::new_in(temp_dir.path()).expect("to be able to build a temporary file");
let bytes = generate_random_file_content(&mut SmallRng::from_entropy());
test_file.write_all(&bytes).expect("to successfully write bytes to the file");
let formats = [
"tar", "zip", "tar.gz", "tgz", "tbz", "tbz2", "txz", "tlz", "tlzma", "tzst", "tar.bz", "tar.bz2", "tar.lzma",
"tar.xz", "tar.zst",
];
let expected_mimes = [
"application/x-tar",
"application/zip",
"application/gzip",
"application/gzip",
"application/x-bzip2",
"application/x-bzip2",
"application/x-xz",
"application/x-xz",
"application/x-xz",
"application/zstd",
"application/x-bzip2",
"application/x-bzip2",
"application/x-xz",
"application/x-xz",
"application/zstd",
];
assert_eq!(formats.len(), expected_mimes.len());
for (format, expected_mime) in formats.iter().zip(expected_mimes.iter()) {
let temp_dir_path = temp_dir.path();
let paths_to_compress = &[test_file.path().into()];
let compressed_file_path = compress_files(temp_dir_path, paths_to_compress, format);
let sniffed =
infer::get_from_path(compressed_file_path).expect("the file to be read").expect("the MIME to be found");
assert_eq!(&sniffed.mime_type(), expected_mime);
}
}
#[test]
/// Tests each format that supports multiple files with random input.
/// TODO: test the remaining formats.
fn test_each_format() {
test_compressing_and_decompressing_archive("tar");
test_compressing_and_decompressing_archive("tar.gz");
test_compressing_and_decompressing_archive("tar.bz");
test_compressing_and_decompressing_archive("tar.bz2");
test_compressing_and_decompressing_archive("tar.xz");
test_compressing_and_decompressing_archive("tar.lz");
test_compressing_and_decompressing_archive("tar.lz4");
test_compressing_and_decompressing_archive("tar.lzma");
test_compressing_and_decompressing_archive("tar.zst");
test_compressing_and_decompressing_archive("tgz");
test_compressing_and_decompressing_archive("tbz");
test_compressing_and_decompressing_archive("tbz2");
test_compressing_and_decompressing_archive("txz");
test_compressing_and_decompressing_archive("tlz4");
test_compressing_and_decompressing_archive("tlz");
test_compressing_and_decompressing_archive("tlzma");
test_compressing_and_decompressing_archive("tzst");
test_compressing_and_decompressing_archive("zip");
test_compressing_and_decompressing_archive("zip.gz");
test_compressing_and_decompressing_archive("zip.bz");
test_compressing_and_decompressing_archive("zip.bz2");
test_compressing_and_decompressing_archive("zip.xz");
test_compressing_and_decompressing_archive("zip.lz");
test_compressing_and_decompressing_archive("zip.lzma");
// Why not
test_compressing_and_decompressing_archive(
"tar.gz.gz.gz.gz.gz.gz.gz.gz.zst.gz.gz.gz.gz.gz.gz.gz.gz.gz.gz.lz.lz.lz.lz.lz.lz.lz.lz.lz.lz.bz.bz.bz.bz.bz.bz.bz",
);
}
type FileContent = Vec<u8>;
/// Compress and decompresses random files to archive formats, checks if contents match
fn test_compressing_and_decompressing_archive(format: &str) {
// System temporary directory depends on the platform, for linux it's /tmp
let system_tmp = env::temp_dir();
// Create a temporary testing folder that will be deleted on scope drop
let testing_dir =
tempfile::Builder::new().prefix("ouch-testing").tempdir_in(system_tmp).expect("Could not create testing_dir");
let testing_dir_path = testing_dir.path();
// Quantity of compressed files vary from 1 to 10
let mut rng = SmallRng::from_entropy();
let quantity_of_files = rng.next_u32() % 10 + 1;
let contents_of_files: Vec<FileContent> =
(0..quantity_of_files).map(|_| generate_random_file_content(&mut rng)).collect();
// Create them
let mut file_paths = create_files(testing_dir_path, &contents_of_files);
// Compress them
let compressed_archive_path = compress_files(testing_dir_path, &file_paths, format);
// Decompress them
let mut extracted_paths = extract_files(&compressed_archive_path);
// // DEBUG UTIL:
// // Uncomment line below to freeze the code and see compressed and extracted files in
// // the temporary directory before their auto-destruction.
// std::thread::sleep(std::time::Duration::from_secs(1_000_000));
file_paths.sort();
extracted_paths.sort();
assert_correct_paths(&file_paths, &extracted_paths, format);
compare_file_contents(&extracted_paths, &contents_of_files, format);
}
/// Crate file contents from 1024 up to 8192 random bytes
fn generate_random_file_content(rng: &mut impl RngCore) -> FileContent {
let quantity = 1024 + rng.next_u32() % (8192 - 1024);
let mut vec = vec![0; quantity as usize];
rng.fill_bytes(&mut vec);
vec
}
/// Create files using the indexes as file names (eg. 0, 1, 2 and 3)
///
/// Return the path to each one.
fn create_files(at: &Path, contents: &[FileContent]) -> Vec<PathBuf> {
contents
.iter()
.enumerate()
.map(|(i, content)| {
let path = at.join(i.to_string());
let mut file = fs::File::create(&path).expect("Could not create dummy test file");
file.write_all(content).expect("Could not write to dummy test file");
path
})
.collect()
}
fn extract_files(archive_path: &Path) -> Vec<PathBuf> {
// We will extract in the same folder as the archive
// If the archive is at:
// /tmp/ouch-testing-tar.Rbq4DusBrtF8/archive.tar
// Then the extraction_output_folder will be:
// /tmp/ouch-testing-tar.Rbq4DusBrtF8/extraction_results/
let mut extraction_output_folder = archive_path.to_path_buf();
// Remove the name of the extracted archive
assert!(extraction_output_folder.pop());
// Add the suffix "results"
extraction_output_folder.push("extraction_results");
let command = Opts {
yes: false,
no: false,
cmd: Subcommand::Decompress {
files: vec![archive_path.to_owned()],
output_dir: Some(extraction_output_folder.clone()),
},
};
run(command, QuestionPolicy::Ask).expect("Failed to extract");
fs::read_dir(extraction_output_folder).unwrap().map(Result::unwrap).map(|entry| entry.path()).collect()
}
fn assert_correct_paths(original: &[PathBuf], extracted: &[PathBuf], format: &str) {
assert_eq!(
original.len(),
extracted.len(),
"Number of compressed files does not match number of decompressed when testing archive format '{:?}'.",
format
);
for (original, extracted) in original.iter().zip(extracted) {
assert_eq!(original.file_name(), extracted.file_name(), "");
}
}
fn compare_file_contents(extracted: &[PathBuf], contents: &[FileContent], format: &str) {
extracted.iter().zip(contents).for_each(|(extracted_path, expected_content)| {
let actual_content = fs::read(extracted_path).unwrap();
assert_eq!(
expected_content,
actual_content.as_slice(),
"Contents of file with path '{:?}' does not match after compression and decompression while testing archive format '{:?}.'",
extracted_path.canonicalize().unwrap(),
format
);
});
}
| true
|
77e5ff61cfd80c2fff6b3b47e7d1976e29625251
|
Rust
|
cnruby/learn-rust-by-crates
|
/hello-borrowing/bin-local-hello/examples/usage/main.rs
|
UTF-8
| 2,168
| 2.75
| 3
|
[] |
no_license
|
// cargo run --example usage
// >> Nothing
// cargo run --example usage -- u8_type
// cargo run --example usage -- str_type
// cargo run --example usage -- references_simple
// cargo run --example usage -- ref_and
// cargo run --example usage -- string_len_count
// cargo run --example usage -- closure
// cargo run --example usage -- raw_pointer_str
// cargo run --example usage -- raw_pointer_string
// cargo run --example usage -- raw_pointer
// cargo run --example usage -- clone_array
// cargo run --example usage -- kw_fn_u8_ref
// cargo run --example usage -- kw_fn_u8
// cargo run --example usage -- string_mut_new
// cargo run --example usage -- vec_mut_new
// cargo run --example usage -- convert_string_str
// cargo run --example usage -- prettytable
use std::env::args;
use hello_borrowing::immut::*;
use hello_borrowing::mutable::*;
use hello_borrowing::other::*;
fn main() {
match args().nth(1) {
Some(ref x) => {
println!("Enter mod_name: {}", x);
match x.as_str() {
"u8_type" => type_ref::use_u8_type(),
"str_type" => type_ref::use_str_type(),
"references_simple" => type_ref::use_references_simple(),
"ref_and" => type_ref::use_ref_and(),
"string_len_count" => len_count::use_string_len_count(),
"closure" => closure::use_closure(),
"raw_pointer_str" => raw_pointer::use_raw_pointer_str(),
"raw_pointer_string" => raw_pointer::use_raw_pointer_string(),
"raw_pointer" => raw_pointer::use_raw_pointer(),
"clone_array" => clone::use_clone_array(),
"kw_fn_u8_ref" => kw_fn::use_kw_fn_u8_ref(),
"kw_fn_u8" => kw_fn::use_kw_fn_u8(),
"string_mut_new" => mut_new::use_string_mut_new(),
"vec_mut_new" => mut_new::use_vec_mut_new(),
"convert_string_str" => string_str::use_convert_string_str(),
"prettytable" => crate_tools::use_prettytable(),
_ => println!("No mod_name"),
};
},
None => println!("Nothing")
}
}
| true
|
4911c7625a3977e5f4e026dab0905c7022e4e807
|
Rust
|
mkos11/rserver
|
/src/main.rs
|
UTF-8
| 1,487
| 3.390625
| 3
|
[
"MIT"
] |
permissive
|
mod lib;
use std::env;
fn main() {
/*
let us declare default local server host and sever port
that will be used in case not all commandline args are passed .
*/
let (mut server_host, mut server_port) = ("127.0.0.1", 80);
// let us add logic to get local server host and sever port from command line.
// RServer will run at the input server host and server port.
let args = env::args().collect::<Vec<String>>(); // args is a Vector of String
// let us check command line argument length , it should be 3 as 1st argument is the command used to invoke the program
if args.len() < 3 {
println!("Error - Not enough arguments supplied.\nPlease specify local server host and port as command-line arguments.");
println!("Using default host '{}' and port '{}'.", server_host, server_port);
} else {
// First assign the server host
server_host = &args[1];
// Second assign the
server_port = match args[2].trim().parse() {
Ok(num) => num,
Err(_) => { // handle error and continue the program
println!("Error - Pass port as number.");
println!("Using default port '{}'", server_port);
// return default port value
server_port
}
};
}
// println!("server_host: {}", server_host);
// println!("server_port: {}", server_port);
lib::start_server(server_host, server_port);
}
| true
|
075e5835ae94d0bf7d808074519d01b819522284
|
Rust
|
lar-rs/can
|
/src/config.rs
|
UTF-8
| 1,011
| 2.703125
| 3
|
[] |
no_license
|
use serde::{Deserialize, Serialize};
use std::io;
use std::fs::File;
use std::fs;
use std::io::prelude::*;
// use std::prelude::*;
use std::path::Path;
use toml;
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct Index {
pub addr: u32,
}
/// Configuration
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct Config {
pub iface: String,
pub bautrate: u32,
}
impl Default for Config {
fn default() -> Config {
Config {
iface:"vcan".to_owned(),
bautrate: 125000,
}
}
}
/// read config
pub fn read(path: &Path) -> io::Result<Config> {
let toml_str = fs::read_to_string(path)?;
if let Ok(conf) = toml::from_str(&toml_str) {
Ok(conf)
}else {
Ok(Config::default())
}
}
pub fn write(config: Config,path:&Path) ->io::Result<()> {
let toml_str = toml::to_string(&config).unwrap();
let mut file = File::create(path)?;
file.write_all(toml_str.as_bytes())?;
file.sync_all()?;
Ok(())
}
| true
|
628a12b59958093682cf7706288477efb8e1e465
|
Rust
|
wdhg/game-boy
|
/src/cpu/instr/instr.rs
|
UTF-8
| 1,953
| 2.90625
| 3
|
[
"MIT"
] |
permissive
|
use crate::cpu::instr::operand::{Op16, Op8};
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Instr {
NOP, // no operation
DAA, // decimal adjust register A
CPL, // complement register A (flip all bits)
CCF, // complement carry flag
SCF, // set carry flag
HALT, // power down CPU until an interrupt occurs
STOP, // halt CPU and LCD display until button pressed
DI, // disables interrupts
EI, // enables interrupts
LD(Op8, Op8), // load instruction
LD16(Op16, Op16), // 16 bit load instruction
LDH(Op8, Op8), // half* load instruction (*half of 16 bit reg)
PUSH(Op16), // bit push instruction
POP(Op16), // 16 bit pop instruction
ADD(Op8, Op8), // add instruction
ADD16(Op16, Op16), // 16 bit add instruction
ADC(Op8, Op8), // add with carry instruction
SUB(Op8), // sub instruction
SBC(Op8), // sub with carry instruction
AND(Op8), // and instruction
OR(Op8), // or instruction
XOR(Op8), // xor instruction
CP(Op8), // compare instruction
INC(Op8), // increment instruction
INC16(Op16), // 16 bit increment instruction
DEC(Op8), // decrement instruction
DEC16(Op16), // 16 bit decrement instruction
RLC(Op8), // rotate left with carry
RL(Op8), // rotate left
RRC(Op8), // rotate right with carry
RR(Op8), // rotate right
SLA(Op8), // shift left into carry (LSB = 0)
SRA(Op8), // shift right into carry (MSB constant)
SRL(Op8), // shift left into carry (MSB = 0)
BIT(u8, Op8), // test bit in register
SET(u8, Op8), // set bit in register
RES(u8, Op8), // reset bit in register
}
| true
|
c6f63627bfef7ead5a4703c4fd5ef710c31841c8
|
Rust
|
Im-Oab/One-Man-ggj21
|
/src/gameplay/enemy_types/crawling_pop_corn.rs
|
UTF-8
| 4,864
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
use std::collections::HashMap;
use std::time::Duration;
use rand::prelude::*;
use tetra::graphics::{self, Color, GeometryBuilder, Mesh, Rectangle, ShapeStyle};
use tetra::math::Vec2;
use tetra::Context;
use crate::image_assets::ImageAssets;
use crate::sprite::AnimationMultiTextures;
use crate::gameplay::enemy_manager::{Enemy, EnemyType};
use crate::gameplay::player::Player;
pub struct CrawlingPopCornEnemyType {}
impl CrawlingPopCornEnemyType {
pub fn new(image_assets: &ImageAssets) -> CrawlingPopCornEnemyType {
CrawlingPopCornEnemyType {}
}
fn apply_gravity(&self, enemy: &mut Enemy, offset: f32) {
enemy.position.y += crate::GRAVITY * offset;
enemy.position.y = enemy.position.y.min(0.0);
}
fn on_the_ground(&self, enemy: &mut Enemy) -> bool {
enemy.position.y >= -10.0
}
fn random_weapon_tick(&self, enemy: &mut Enemy) {
enemy.weapon_tick = 800 + random::<u128>() % 800;
}
fn update_rotation(&self, enemy: &mut Enemy, player_position: Vec2<f32>) {
if enemy.position.x < player_position.x {
enemy.rotation = 0.05;
} else {
enemy.rotation = 0.45;
}
}
}
impl EnemyType for CrawlingPopCornEnemyType {
fn enemy_type_id(&self) -> i32 {
2
}
fn init(&mut self, enemy: &mut Enemy, image_assets: &ImageAssets) {
enemy.enemy_type = self.enemy_type_id();
enemy.radius = 20.0;
enemy.active = true;
enemy.health = 40;
enemy.life_time = 1000;
enemy.sprite.scale = Vec2::new(2.0, 2.0);
enemy.rotation = match enemy.extra.get("rotation") {
Some(v) => v.parse::<f32>().unwrap_or(0.0),
None => 0.0,
};
self.random_weapon_tick(enemy);
match image_assets.get_animation_object("enemy-crawler-air") {
Some(animation) => {
enemy.sprite.play(&animation);
}
None => {
enemy.active = false;
}
}
}
fn update(&self, enemy: &mut Enemy, player: Option<&Player>, image_assets: &ImageAssets) {
if enemy.state == 0 {
let speed = 4.0;
if enemy.weapon_tick <= 500 {
self.apply_gravity(enemy, 0.5 * (1.0 - (enemy.weapon_tick as f32 / 500.0)));
} else {
enemy.position.y -= (enemy.rotation * 360.0).to_radians().sin() * speed;
}
if self.on_the_ground(enemy) {
enemy.state = 1;
enemy.weapon_tick = 1500;
self.update_rotation(enemy, player.unwrap().get_hit_point_position());
match image_assets.get_animation_object("enemy-crawler-idle") {
Some(animation) => {
enemy.sprite.play(&animation);
}
None => {
enemy.active = false;
}
}
}
enemy.position.x += (enemy.rotation * 360.0).to_radians().cos() * speed;
} else {
let speed = 3.0;
enemy.position.x += (enemy.rotation * 360.0).to_radians().cos()
* (speed * (enemy.weapon_tick as f32 / 1500.0));
if enemy.weapon_tick == 0 {
enemy.weapon_tick = 1500;
self.update_rotation(enemy, player.unwrap().get_hit_point_position());
}
}
match enemy.weapon_tick.checked_sub(crate::ONE_FRAME.as_millis()) {
Some(v) => enemy.weapon_tick = v,
None => enemy.weapon_tick = 0,
};
if enemy.rotation > 0.25 && enemy.rotation < 0.75 {
enemy.sprite.flip_x(true);
} else {
enemy.sprite.flip_x(false);
}
}
fn draw(&self, ctx: &mut Context, image_assets: &ImageAssets, enemy: &mut Enemy) {
enemy.sprite.draw(
ctx,
enemy.position + Vec2::new(0.0, -8.0),
0.0,
image_assets,
);
}
fn die(&self, enemy: &mut Enemy) {
{
let mut play_sound_nodes = crate::PLAY_SOUND_NODES.lock().unwrap();
play_sound_nodes.insert(String::from("crawl_explode"), (String::from("./resources/sfx/crawl_explode.mp3"), 0.8 ) );
}
}
/// 0: not hit, 1: hit weakpoint, -1: hit shield. (No damage)
fn hit_check(&self, enemy: &Enemy, position: &Vec2<f32>, radius: f32) -> i32 {
let distance = crate::gameplay::utils::distance_sqr(
enemy.position.x as i128,
enemy.position.y as i128,
position.x as i128,
position.y as i128,
);
let total_radius = (enemy.radius + radius) as i128;
if distance <= total_radius * total_radius {
return 1;
}
0
}
}
| true
|
5df7c43b3744f375dab11a20389fd4f3384c0baf
|
Rust
|
lanocci/algorithm-and-data-struscture-in-rust
|
/computational_geometry/geometric_element/src/circle.rs
|
UTF-8
| 3,071
| 3.359375
| 3
|
[] |
no_license
|
use std::fmt::Debug;
use num_traits::{Float, Zero, cast::FromPrimitive};
use crate::point::{Point, Vector};
use crate::segment::Line;
#[derive(Clone, Debug)]
pub struct Circle<T> where T: Float + FromPrimitive + Zero {
center: Point<T>,
radius: T,
}
impl<T> Circle<T> where T: Float + FromPrimitive + Zero + Debug {
pub fn new(x: T, y: T, r: T) -> Self {
Circle {
center: Point::new(x, y),
radius: r,
}
}
pub fn polar(&self, radian: T) -> Vector<T> {
Vector::new(radian.cos() * self.radius, radian.sin() * self.radius)
}
pub fn line_intersect(&self, line: &Line<T>) -> bool {
line.distance_from_point(&self.center) < self.radius
}
/// ```
/// use geometric_element::point::Point;
/// use geometric_element::segment::Line;
/// use geometric_element::circle::Circle;
///
/// let c = Circle::new(2.0, 1.0, 1.0);
/// let l = Line::new(Point::new(0.0, 1.0), Point::new(4.0, 1.0));
/// assert_eq!(c.line_cross_points(&l), Ok((Point{x: 1.0, y: 1.0}, Point{x: 3.0, y:1.0})));
/// ```
pub fn line_cross_points(&self, line: &Line<T>) -> Result<(Point<T>, Point<T>), String> {
if self.line_intersect(&line) {
let pr = line.projection(&self.center);
let e = line.base_vector() / line.base_vector().abs();
let base = (self.radius.clone().powi(2) + (pr.clone() - self.center.clone()).norm()).sqrt();
Ok((pr.clone() - e.clone() * base.clone(), pr.clone() + e.clone() * base.clone()))
} else {
Err("line doesn't intersects the circle".to_string())
}
}
pub fn intersect(&self, other: &Self) -> bool {
self.center.distance(&other.center) <= self.radius + other.radius
}
/// ```
/// use geometric_element::point::Point;
/// use geometric_element::circle::Circle;
/// use num_traits::identities::Zero;
/// let c1 = Circle::new(0.0, 0.0, 2.0);
/// let c2 = Circle::new(2.0, 0.0, 2.0);
/// if let Ok((point1, point2)) = c1.cross_points(&c2){
/// assert!(point1.x - 1.0 < 0.000001 && point1.x - 1.0 > -0.00000001);
/// assert!(point1.y - (-1.7320508) < 0.000001 && point1.y - (-1.7320508) > -0.000001);
/// assert!(point2.x - 1.0 < 0.000001 && point2.x - 1.0 > -0.00000001);
/// assert!(point2.y - 1.7320508 < 0.000001 && point2.y - 1.7320508 > -0.00000001);
/// } else {
/// panic!();
/// }
/// ```
pub fn cross_points(&self, other: &Self) -> Result<(Point<T>, Point<T>), String> {
if self.intersect(&other) {
let d = self.center.distance(&other.center);
let a = ((self.radius.powi(2) + d.powi(2) - other.radius.powi(2)) / (T::from_i8(2).unwrap() * self.radius * d)).acos();
let t = (other.center.clone() - self.center.clone()).declination();
Ok((self.center.clone() + self.polar(t - a), self.center.clone() + self.polar(t + a)))
} else {
Err("no intersection".to_string())
}
}
}
| true
|
9ff6e00bb5004cb85b0782dfc7c51702c2714367
|
Rust
|
RalfJung/miri
|
/test-cargo-miri/subcrate/main.rs
|
UTF-8
| 656
| 2.8125
| 3
|
[
"Apache-2.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
use std::env;
use std::path::PathBuf;
fn main() {
println!("subcrate running");
// CWD should be workspace root, i.e., one level up from crate root.
// We have to normalize slashes, as the env var might be set for a different target's conventions.
let env_dir = env::current_dir().unwrap();
let env_dir = env_dir.to_string_lossy().replace("\\", "/");
let crate_dir = env::var_os("CARGO_MANIFEST_DIR").unwrap();
let crate_dir = crate_dir.to_string_lossy().replace("\\", "/");
let crate_dir = PathBuf::from(crate_dir);
let crate_dir = crate_dir.parent().unwrap().to_string_lossy();
assert_eq!(env_dir, crate_dir);
}
| true
|
78cbaa0d7fa510dda30758c21157930fdcc427bf
|
Rust
|
wooster0/blockpaint
|
/src/util.rs
|
UTF-8
| 6,460
| 3.28125
| 3
|
[
"MIT"
] |
permissive
|
use crate::{palette, terminal::SIZE};
use std::{convert::TryFrom, fmt, ops};
#[derive(Clone, Debug, Copy, PartialEq)]
pub struct Point {
pub x: SIZE,
pub y: SIZE,
}
impl Default for Point {
fn default() -> Self {
Self {
x: Default::default(),
y: Default::default(),
}
}
}
impl fmt::Display for Point {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "({}, {})", self.x, self.y)
}
}
#[derive(Clone, Debug)]
pub struct Size {
pub width: SIZE,
pub height: SIZE,
}
impl Size {
pub fn from_terminal_size(width: usize, height: usize) -> Self {
Self {
width: width.clamp(0, 255) as u8,
height: height.clamp(0, 255) as u8,
}
}
}
struct Range(ops::Range<SIZE>);
impl fmt::Display for Range {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(formatter, "{} to {}", self.0.start, self.0.end)
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Color {
// 4-bit colors
DarkRed,
DarkGreen,
DarkYellow,
DarkBlue,
DarkMagenta,
DarkCyan,
Black,
Gray,
DarkGray,
Red,
Green,
Yellow,
Blue,
Magenta,
Cyan,
White,
// 8-bit colors
ByteColor(u8),
// 24-bit colors
Rgb { r: u8, g: u8, b: u8 },
}
impl Default for Color {
fn default() -> Self {
Color::Black
}
}
impl Color {
pub fn invert(&self) -> Self {
use Color::*;
match self {
ByteColor(mut byte) => {
if byte >= u8::MAX - palette::GRAYSCALE_COLOR_COUNT {
byte = u8::MAX - byte;
byte += u8::MAX - palette::GRAYSCALE_COLOR_COUNT - 1;
} else {
byte = u8::MAX - byte - palette::FOUR_BIT_COLOR_COUNT + 1;
}
ByteColor(byte)
}
Rgb { r, g, b } => Rgb {
r: u8::MAX - r,
g: u8::MAX - g,
b: u8::MAX - b,
},
Black | DarkGray => White,
_ => Black,
}
}
}
/// Tries to parse the input into an RGB color.
/// It can parse the following RGB notations:
///
/// 8-bit, e.g. (255, 0, 0),
/// Hexadecimal, e.g. #FF0000
///
/// See https://en.wikipedia.org/wiki/RGB_color_model for more information.
// TODO:
// Float, e.g. (1.0, 0.0, 0.0),
// Percentage, e.g. (100%, 0%, 0%),
pub fn parse_rgb_color(string: &str) -> Option<Color> {
let mut r: Option<u8> = None;
let mut g: Option<u8> = None;
let mut b: Option<u8> = None;
let mut component = &mut r;
let mut hexdigits_in_a_row = 0;
let mut index = 0;
for char in string.chars() {
match char {
'0'..='9' => {
if let Some(byte) = char.to_digit(10) {
*component = if let Some(component) = *component {
Some(
u8::try_from(component as usize * 10 + byte as usize)
.unwrap_or(u8::MAX),
)
} else {
Some(byte as u8)
};
};
hexdigits_in_a_row += 1;
}
_ if char.is_ascii_hexdigit() => {
if let Some(color) = parse_hex(string, index) {
return Some(color);
}
hexdigits_in_a_row += 1;
}
_ => {
component = match (r, g, b) {
(None, None, None) => &mut r,
(Some(_), None, None) => &mut g,
(Some(_), Some(_), None) => &mut b,
(Some(r), Some(g), Some(b)) => return Some(Color::Rgb { r, g, b }),
_ => return None,
};
hexdigits_in_a_row = 0;
}
}
index += 1;
if hexdigits_in_a_row == 6 && index >= hexdigits_in_a_row {
if let Some(color) = parse_hex(string, index - hexdigits_in_a_row) {
return Some(color);
}
}
}
match (r, g, b) {
(Some(r), None, None) => Some(Color::Rgb { r, g: 0, b: 0 }),
(Some(r), Some(g), None) => Some(Color::Rgb { r, g, b: 0 }),
(Some(r), Some(g), Some(b)) => Some(Color::Rgb { r, g, b }),
_ => None,
}
}
fn parse_hex(string: &str, index: usize) -> Option<Color> {
if let (Some(r), Some(g), Some(b)) = (
&string.get(index..index + 2),
&string.get(index + 2..index + 4),
&string.get(index + 4..index + 6),
) {
let r = u8::from_str_radix(r, 16);
let g = u8::from_str_radix(g, 16);
let b = u8::from_str_radix(b, 16);
if let (Ok(r), Ok(g), Ok(b)) = (r, g, b) {
Some(Color::Rgb { r, g, b })
} else {
None
}
} else {
None
}
}
#[cfg(test)]
mod tests {
use super::*;
fn parse(string: &str) -> Option<Color> {
parse_rgb_color(string)
}
fn rgb(r: u8, g: u8, b: u8) -> Option<Color> {
Some(Color::Rgb { r, g, b })
}
#[test]
fn test_parse_rgb_color() {
assert_eq!(parse("255, 255, 255"), rgb(255, 255, 255));
assert_eq!(parse("200,255,255"), rgb(200, 255, 255));
assert_eq!(parse("-200,-255,-255"), rgb(200, 255, 255));
assert_eq!(parse("(255,200,255)"), rgb(255, 200, 255));
assert_eq!(parse("www255,255,200www"), rgb(255, 255, 200));
assert_eq!(parse(" www100www,www0www,www100www"), rgb(100, 0, 100));
assert_eq!(parse("www100www,www20www,,,"), rgb(100, 20, 0));
assert_eq!(parse(" 123"), rgb(123, 0, 0));
assert_eq!(parse("99999,99999,99999"), rgb(255, 255, 255));
assert_eq!(parse("FF0000,00FF00,0000FF"), rgb(255, 0, 0));
assert_eq!(parse("00FF00"), rgb(0, 255, 0));
assert_eq!(parse(" 00FF00"), rgb(0, 255, 0));
assert_eq!(parse("-50,-50,-50-00FF00"), rgb(50, 50, 50));
assert_eq!(parse("256"), rgb(255, 0, 0));
assert_eq!(parse("99999"), rgb(255, 0, 0));
assert_eq!(parse("rgb(123,255,100)"), rgb(123, 255, 100));
assert_eq!(parse("123,255,100"), rgb(123, 255, 100));
// assert_eq!(parse("255,255,255555555"), rgb(255, 255, 255));
// assert_eq!(parse("255,255,255efefef"), rgb(255, 255, 255));
}
}
| true
|
cb2259c54fed5622e37546d8c7fe67f0f91fe05e
|
Rust
|
ZipFast/lifetime-variance-example
|
/code/ch01-04-variance-in-practice/simple-message-collector/src/main.rs
|
UTF-8
| 1,426
| 3.421875
| 3
|
[
"CC0-1.0"
] |
permissive
|
#![allow(dead_code)]
fn main() {}
use std::collections::HashSet;
use std::fmt;
struct Message<'msg> {
message: &'msg str,
}
struct MessageCollector<'a, 'msg> {
list: &'a mut Vec<Message<'msg>>,
}
impl<'a, 'msg> MessageCollector<'a, 'msg> {
fn add_message(&mut self, message: Message<'msg>) {
self.list.push(message);
}
}
struct SimpleMessageDisplayer<'a> {
list: &'a Vec<Message<'a>>,
}
impl<'a> fmt::Display for SimpleMessageDisplayer<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for message in self.list {
write!(f, "{}\n", message.message)?;
}
Ok(())
}
}
// ANCHOR: SimpleMessageCollector
struct SimpleMessageCollector<'a> {
list: &'a mut Vec<Message<'a>>,
}
impl<'a> SimpleMessageCollector<'a> {
// This adds a message to the end of the list.
fn add_message(&mut self, message: Message<'a>) {
self.list.push(message);
}
}
fn collect_and_display_3<'msg>(message_pool: &'msg HashSet<String>) {
// OK, one more time.
let mut list = vec![];
// Collect some messages.
let mut collector = SimpleMessageCollector { list: &mut list };
for message in message_pool {
collector.add_message(Message { message });
}
// Finally, display them.
let displayer = SimpleMessageDisplayer { list: &list };
println!("{}", displayer);
}
// ANCHOR_END: SimpleMessageCollector
| true
|
800ff7c6b620ca111817f030f3c03d7dca2b6214
|
Rust
|
uglyoldbob/electronics_design
|
/src/window/component_name.rs
|
UTF-8
| 3,107
| 2.71875
| 3
|
[
"OFL-1.1",
"MIT"
] |
permissive
|
//! This window asks the user for a name of the new library
use egui_multiwin::egui_glow::EguiGlow;
use egui_multiwin::{
egui,
multi_window::NewWindowRequest,
tracked_window::{RedrawResponse, TrackedWindow},
};
use crate::library::LibraryAction;
use crate::MyApp;
/// The window structure
pub struct Name {
/// The name of the library being modified
lib_name: String,
/// The name of the new symbol
name: String,
}
impl Name {
/// Create a new window
pub fn request(lib_name: String) -> NewWindowRequest<MyApp> {
NewWindowRequest {
window_state: Box::new(Self {
lib_name,
name: "".to_string(),
}),
builder: egui_multiwin::winit::window::WindowBuilder::new()
.with_resizable(true)
.with_inner_size(egui_multiwin::winit::dpi::LogicalSize {
width: 320.0,
height: 240.0,
})
.with_title("New Library"),
options: egui_multiwin::tracked_window::TrackedWindowOptions {
vsync: false,
shader: None,
},
}
}
}
impl TrackedWindow<MyApp> for Name {
fn is_root(&self) -> bool {
false
}
fn set_root(&mut self, _root: bool) {}
fn redraw(
&mut self,
c: &mut MyApp,
egui: &mut EguiGlow,
_window: &egui_multiwin::winit::window::Window,
) -> RedrawResponse<MyApp> {
let mut quit = false;
let windows_to_create = vec![];
let mut actionlog = Vec::new();
egui::CentralPanel::default().show(&egui.egui_ctx, |ui| {
ui.label("Please enter a name for the new component");
let te =
egui::widgets::TextEdit::singleline(&mut self.name).hint_text("Component name");
ui.add(te).request_focus();
let lib = c.libraries.get_mut(&self.lib_name);
if let Some(lib) = lib {
if let Some(library) = &lib.library {
if !self.name.is_empty() && library.components.contains_key(&self.name) {
ui.colored_label(egui::Color32::RED, "Component already exists");
} else if ui.button("Create").clicked()
|| ui.input(|i| i.key_pressed(egui::Key::Enter))
{
if !library.syms.contains_key(&self.name) {
actionlog.push(LibraryAction::CreateComponent {
libname: self.lib_name.clone(),
comname: self.name.clone(),
});
}
quit = true;
}
}
} else {
ui.label("Library does not exist for some reason");
}
});
for a in actionlog {
c.library_log.apply(&mut c.libraries, a);
}
RedrawResponse {
quit,
new_windows: windows_to_create,
}
}
}
| true
|
4a62ba56b57f912a15018098afde0fde1e0509bc
|
Rust
|
22388o/minimint
|
/minimint-api/src/outcome.rs
|
UTF-8
| 1,519
| 2.765625
| 3
|
[
"MIT"
] |
permissive
|
use crate::SigResponse;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
pub enum TransactionStatus {
/// The transaction was successfully submitted
AwaitingConsensus,
/// The error state is only recorded if the error happens after consensus is achieved on the
/// transaction. This should happen only rarely, e.g. on double spends since a basic validity
/// check is performed on transaction submission.
Error(String),
/// The transaction was accepted and is now being processed
Accepted {
epoch: u64,
outputs: Vec<OutputOutcome>,
},
}
#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
pub enum OutputOutcome {
Mint(Option<SigResponse>),
// TODO: maybe include the transaction id eventually. But unclear how to propagate it cleanly right now.
Wallet(()),
}
pub trait Final {
fn is_final(&self) -> bool;
}
impl Final for OutputOutcome {
fn is_final(&self) -> bool {
match self {
OutputOutcome::Mint(Some(_)) => true,
OutputOutcome::Mint(None) => false,
OutputOutcome::Wallet(()) => true,
}
}
}
impl Final for TransactionStatus {
fn is_final(&self) -> bool {
match self {
TransactionStatus::AwaitingConsensus => false,
TransactionStatus::Error(_) => true,
TransactionStatus::Accepted { outputs, .. } => outputs.iter().all(|out| out.is_final()),
}
}
}
| true
|
185eecdfbcd58f95f371ae4b834a1c608d442d9a
|
Rust
|
second-super-secret-squirrel-account/rust_tic_tac_toe
|
/src/player_manager/player/mod.rs
|
UTF-8
| 613
| 3.046875
| 3
|
[] |
no_license
|
use game_board::board_token::BoardToken;
#[derive(Debug, Eq, PartialEq, Clone)]
pub struct Player {
player_type: PlayerType,
board_token: BoardToken,
}
#[derive(Debug, Eq, PartialEq, Clone)]
pub enum PlayerType {
Human,
Computer,
}
impl Player {
pub fn new(player_type: PlayerType, board_token: BoardToken) -> Player {
Player {
player_type: player_type,
board_token: board_token,
}
}
pub fn player_type(&self) -> &PlayerType {
&self.player_type
}
pub fn board_token(&self) -> &BoardToken {
&self.board_token
}
}
| true
|
28af1b1e203cf579b21eba1d5cf7d41ae149dc82
|
Rust
|
FaultyPine/SSBU_Twitch_Integration
|
/src/twitch.rs
|
UTF-8
| 5,015
| 2.8125
| 3
|
[] |
no_license
|
use std::{io::BufRead, net::*};
use std::io::*;
use crate::{*, utils::*};
/* socket variables */
const SERVER: &str = "34.217.198.238"; // irc.chat.twitch.tv
const PORT: u16 = 80;
// IRC SPEC: https://tools.ietf.org/html/rfc1459
pub unsafe fn get_chat_msg_info_loop(stream: &mut TcpStream, CHANNEL: String) -> Result<()> {
let _ = stream.flush();
let mut chat_msg = String::new();
let mut chatter_name = String::new();
/* Read data from stream into bufreader so we can deal with it more precisely */
let conn = BufReader::new(stream.try_clone().unwrap());
/*
Get chat messages out of current tcp buffer.
According to the IRC spec, messages always end with CR-LF (carrige return, line feed)
so splitting over newline will seperate it into each chat msg
*/
for line_res in conn.lines() {
if let Ok(chat_info) = line_res {
/* api checks if we're still here every once in a while, sending this notifies them that we're still here */
if chat_info.starts_with("PING") {
let _ = stream.write_all("PONG\r\n".as_bytes());
continue;
}
/* Example chat_info (This is how chat messages look from the twitch api's pov):
":monchenjiners!monchenjiners@monchenjiners.tmi.twitch.tv PRIVMSG #moonmoon :monkaGIGA PianoTime\r\n"
^ user ^ also user ^ also user ^ channel ^^^^^^^^^^^^^^^^^^^^^^^ message
*/
/* Parse chat msg for chatter name and their corresponding chat message */
if chat_info.contains("PRIVMSG") {
/* Parsing chatter name. First find ".tmi.twitch.tv" and then look at the text behind that until an "@" */
if let Some(end_idx) = chat_info.find(".tmi.twitch.tv") {
let start_idx = chat_info.slice( .. end_idx).rfind("@").unwrap_or(0);
chatter_name = chat_info.slice(start_idx+1..end_idx).to_string();
}
/* Find channel name and if its found, our index is at that spot + the length of the channel string + 2 to get us at the start of the username */
let mut chat_msg_begin_idx = 0;
if let Some(idx) = chat_info.find(&CHANNEL) {
chat_msg_begin_idx = idx + CHANNEL.chars().count() + 2;
}
chat_msg = chat_info.slice(chat_msg_begin_idx ..).to_string();
/* Print chatter name and chat msg. Used for debugging. */
println!("|{}| {}", chatter_name.clone(), chat_msg);
}
}
voting::update_votes(&chat_msg, chatter_name.clone());
let _ = stream.flush();
chat_msg = String::new();
std::thread::sleep(std::time::Duration::from_millis(1));
}
Err(std::io::Error::new(ErrorKind::Other, "End of stream"))
}
pub unsafe fn start_twitch_integration() {
//voting::init_votes(&mut voting::VOTES.lock().unwrap());
let CONFIG = config::CONFIG.clone().unwrap();
/* Ideally i'd like to use connect_timeout, but using it creates soooo much UB for whatever reason */
if let Ok(mut stream) = TcpStream::connect((SERVER, PORT)) {
let mut channel = CONFIG.channel; channel.insert_str(0, "#");
let token = CONFIG.oauth;
/* Write relevant info to stream to "connect" to the chat */
let _ = stream.write_all(format!("PASS {}\r\n", token).as_bytes());
let _ = stream.write_all(format!("NICK bruh\r\n").as_bytes());
let _ = stream.write_all(format!("JOIN {}\r\n", channel).as_bytes());
let _ = stream.set_nonblocking(true);
let _ = stream.set_ttl(16666666);
let _ = stream.set_read_timeout(Some(std::time::Duration::new(0, 16666666))); // <- one sixty-th of a second (~~1 frame)
println!("[Twitch Integration] Connected to {}'s chat", channel.replace("#", ""));
/* Main loop to get and handle chat messages */
std::thread::spawn(move ||{
loop {
/* Because the buffer in this func continually gets chat info, this func is itself an infinite loop. */
if let Err(e) = get_chat_msg_info_loop(&mut stream, channel.clone()) {
println!("[Twitch Integration] Error: {}", e);
let _ = stream.flush();
let _ = stream.shutdown(std::net::Shutdown::Both);
if skyline_web::Dialog::yes_no("Twitch Integration plugin failed to connect to twitch! Would you like to try reconnecting?") {
start_twitch_integration();
}
break;
}
}
});
}
else {
println!("[Twitch Integration] Failed to connect to twitch :(");
if skyline_web::Dialog::yes_no("Twitch Integration plugin failed to connect to twitch! Would you like to try reconnecting?") {
start_twitch_integration();
}
}
}
| true
|
273bfb2225ddc309e07091823fccab7f863df033
|
Rust
|
reitermarkus/heating
|
/vessel/src/cuboid_tank.rs
|
UTF-8
| 1,166
| 3.53125
| 4
|
[] |
no_license
|
use measurements::Length;
use measurements::Volume;
use crate::level::Level;
use crate::tank::Tank;
#[derive(Debug)]
pub struct CuboidTank {
length: Length,
width: Length,
height: Length,
}
impl CuboidTank {
pub fn new(length: Length, width: Length, height: Length) -> Self {
Self { length, width, height }
}
pub fn length(&self) -> Length {
self.length
}
pub fn width(&self) -> Length {
self.width
}
pub fn height(&self) -> Length {
self.height
}
}
impl Tank for CuboidTank {
fn volume(&self) -> Volume {
Volume::from_liters(self.length.as_decimeters() * self.width.as_decimeters() * self.height.as_decimeters())
}
fn level(&self, filling_height: Length) -> Level {
Level {
volume: Volume::from_liters(self.length.as_decimeters() * self.width.as_decimeters() * filling_height.as_decimeters()),
percentage: filling_height / self.height,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn volume() {
let tank = CuboidTank::new(Length::from_meters(1.0), Length::from_meters(2.0), Length::from_meters(3.0));
assert_eq!(tank.volume(), Volume::from_liters(6000.0));
}
}
| true
|
5397d0cf55f401ee4ce010511550709f598f0cf5
|
Rust
|
tamerh/rosalind2
|
/src/graph/nwc.rs
|
UTF-8
| 3,220
| 2.90625
| 3
|
[] |
no_license
|
use petgraph::graph::Graph;
use std::collections::{BTreeMap, HashSet};
// slight change of bfs.rs
fn negative_weight_cycle(n: usize, edges: Vec<Vec<i32>>, start: usize) -> bool {
let mut g = Graph::new();
let mut nodes = BTreeMap::new();
for i in 1..=n {
let node = g.add_node(i);
nodes.insert(i, node);
}
for e in &edges {
let x = *nodes.get(&(e[0] as usize)).unwrap();
let y = *nodes.get(&(e[1] as usize)).unwrap();
g.add_edge(x, y, e[2]);
}
// initial values and intial selected node
let s = *nodes.get(&start).unwrap();
let mut distance = BTreeMap::new();
for (v, _) in &nodes {
distance.insert(*v, std::i32::MAX);
}
let mut min = std::i32::MAX;
let mut sel_node = 0;
let mut sel_node_id = None;
for neg in g.neighbors(s) {
let dis = g[g.find_edge(s, neg).unwrap()];
distance.insert(g[neg], dis);
if dis < min {
min = dis;
sel_node = g[neg];
sel_node_id = Some(neg);
}
}
distance.insert(start, 0);
// repating steps
let mut discovered = HashSet::new();
discovered.insert(start);
loop {
for neg in g.neighbors(sel_node_id.unwrap()) {
let dis =
g[g.find_edge(sel_node_id.unwrap(), neg).unwrap()] + distance.get(&sel_node).unwrap();
// check for Relaxation
if dis < *distance.get(&g[neg]).unwrap() {
distance.insert(g[neg], dis);
}
}
discovered.insert(sel_node);
// select smallest among remaining remainings
min = std::i32::MAX;
sel_node = 0;
sel_node_id = None;
for (v, dist) in &distance {
if !discovered.contains(v) && min > *dist {
min = *dist;
sel_node = *v;
sel_node_id = Some(*nodes.get(v).unwrap());
}
}
if sel_node_id == None {
break;
}
}
for i in g.edge_indices() {
let (source, target) = g.edge_endpoints(i).unwrap();
let w = g[i];
if distance.get(&g[source]).unwrap() + w < *distance.get(&g[target]).unwrap() {
return true;
}
}
false
}
fn nwc(all_edges: Vec<(usize, Vec<Vec<i32>>)>) {
for (n, edges) in all_edges {
let n = negative_weight_cycle(n, edges, 1);
if n {
print!("1 ");
} else {
print!("-1 ");
}
}
println!("");
}
pub fn solve() -> std::io::Result<()> {
let f = std::fs::read_to_string("inputs/nwc.txt").unwrap();
let mut input = f.lines();
// pass the first size line
let size = input
.next()
.unwrap()
.split_whitespace()
.map(|s| s.parse::<usize>().unwrap())
.collect::<Vec<usize>>();
let n = size[0];
let mut all_edges = Vec::new();
for i in 1..=size[0] {
let line = input.next().unwrap().trim();
if line.len() != 0 {
panic!("invalid input->{}", line);
}
let s = input
.next()
.unwrap()
.split_whitespace()
.map(|s| s.parse::<usize>().unwrap())
.collect::<Vec<usize>>();
let mut edges = Vec::new();
for _ in 1..=s[1] {
let pair = input
.next()
.unwrap()
.trim()
.split_whitespace()
.map(|s| s.parse::<i32>().unwrap())
.collect::<Vec<i32>>();
edges.push(pair);
}
all_edges.push((s[0], edges));
}
nwc(all_edges);
Ok(())
}
| true
|
79cfb59a2e16b959cef7e63cda63325f7f7270a2
|
Rust
|
mathiasmagnusson/whm
|
/src/tests.rs
|
UTF-8
| 2,733
| 3.109375
| 3
|
[] |
no_license
|
use super::*;
#[test]
fn factorial() {
assert_eq!(0.factorial(), 1);
assert_eq!(1.factorial(), 1);
assert_eq!(2.factorial(), 2);
assert_eq!(3.factorial(), 6);
assert_eq!(4.factorial(), 24);
assert_eq!(10.factorial(), 3628800);
}
#[test]
fn permutations() {
assert_eq!(Integer::permutations(6, 3), 6 * 5 * 4);
assert_eq!(Integer::permutations(6, 6), 6 * 5 * 4 * 3 * 2 * 1);
}
#[test]
fn combinations() {
assert_eq!(Integer::combinations(6, 2), 15);
assert_eq!(Integer::combinations(6, 6), 1);
for n in 0..10 {
assert_eq!(Integer::combinations(n, 0), 1);
assert_eq!(Integer::combinations(n, 1), n);
for k in 0..=n {
assert_eq!(Integer::combinations(n, k), Integer::combinations(n, n - k));
}
}
}
#[test]
fn binomial() {
assert_eq!(Integer::binomial(4, 5, 1), 4 + 5);
assert_eq!(Integer::binomial(4, 5, 2), (4 + 5) * (4 + 5));
assert_eq!(
Integer::binomial(4, 5, 7),
(4 + 5) * (4 + 5) * (4 + 5) * (4 + 5) * (4 + 5) * (4 + 5) * (4 + 5)
);
}
// #[test]
// fn solve_mat4x3() {
// let mat = Matrix3x4::from([
// 1.0, 1.0, 1.0, 7.0,
// 1.0, 2.0, 3.0, 11.0,
// 2.0, 1.0, 2.0, 12.0,
// ]);
// assert_eq!(mat.solve(), Ok(Vector3::new(4.0, 2.0, 1.0)));
// let mat = Matrix3x4::from([
// [1.0, 2.0, 3.0, -1.0],
// [2.0, 4.0, 7.0, 0.0],
// [2.0, 5.0, 10.0, 5.0],
// ]);
// assert_eq!(mat.solve(), Ok(Vector3::new(-5.0, -1.0, 2.0)));
// let mat = Matrix3x4::from([
// Vector4::new(1.0, 0.0, 0.0, 4.0),
// [0.0, 1.0, 0.0, 2.0].into(),
// (0.0, 0.0, 1.0, 0.0).into(),
// ]);
// assert_eq!(mat.solve(), Ok((4.0, 2.0, 0.0).into()));
// }
// #[test]
// fn solve_mat3x2() {
// let mat = Matrix2x3::from([
// 1.0, 0.0, 69.0,
// 0.0, 1.0, 420.0,
// ]);
// assert_eq!(mat.solve(), Ok((69.0, 420.0).into()));
// let mat = Matrix2x3::from([
// [69.0, 1337.0, 420.0],
// [1337.0, 420.0, 69.0],
// ]);
// assert_eq!(mat.solve(), Ok([-0.047849655, 0.31660554].into()));
// }
#[test]
fn mat_neg() {
assert_eq!(
Matrix3x3::from([
1.0, std::f32::consts::SQRT_2, 3.14,
-123.0, 0.0, -std::f32::consts::FRAC_PI_3,
0.0, 1.0, -6.28,
]),
-Matrix3x3::from([
-1.0, -std::f32::consts::SQRT_2, -3.14,
123.0, -0.0, std::f32::consts::FRAC_PI_3,
0.0, -1.0, 6.28,
]),
);
}
#[test]
fn mat_eq() {
assert_eq!(Matrix3x4::identity(), Matrix3x4::identity());
assert_ne!(Matrix3x4::identity(), -Matrix3x4::identity());
}
#[test]
fn phi() {
assert_eq!(Integer::phi(710), 280);
}
#[test]
fn mod_exp() {
assert_eq!(11.mod_exp(13, 53), 52);
assert_eq!(1.mod_exp(1337, 53), 1);
}
#[test]
fn determinants() {
assert_eq!(Matrix3x3::zero().det(), 0.0);
assert_eq!(Matrix3x3::identity().det(), 1.0);
assert_eq!((Matrix3x3::identity() * 3.0).det(), Float::powi(3.0, 3));
}
| true
|
a5134dd0ba9fd8ebdac3a9855380fd4196e8eb6f
|
Rust
|
Disasm/usb-tester
|
/software/usb-switch-cli/src/device.rs
|
UTF-8
| 2,364
| 2.59375
| 3
|
[] |
no_license
|
use std::time::Duration;
use libusb::*;
use usb_switch_common::{USB_DEVICE_VID, USB_DEVICE_PID, Selection, REQ_SELECT};
use serialport::SerialPortType;
pub const TIMEOUT: Duration = Duration::from_secs(1);
pub struct DeviceHandles<'a> {
pub handle: DeviceHandle<'a>,
pub serial_path: String,
}
impl DeviceHandles<'_> {
pub fn select(&mut self, selection: Selection) -> Result<()> {
self.write_control(
request_type(Direction::Out, RequestType::Vendor, Recipient::Interface),
REQ_SELECT, selection.0, 2, &[], TIMEOUT
).map(|_| ())
}
pub fn get_selection(&mut self) -> Result<Selection> {
let mut buf = [0; 2];
let n = self.read_control(
request_type(Direction::In, RequestType::Vendor, Recipient::Interface),
REQ_SELECT, 0, 2, &mut buf, TIMEOUT
)?;
if n == 2 {
Ok(Selection(u16::from_le_bytes(buf)))
} else {
Err(Error::Other)
}
}
}
impl<'a> ::std::ops::Deref for DeviceHandles<'a> {
type Target = DeviceHandle<'a>;
fn deref(&self) -> &DeviceHandle<'a> {
&self.handle
}
}
impl<'a> ::std::ops::DerefMut for DeviceHandles<'a> {
fn deref_mut(&mut self) -> &mut DeviceHandle<'a> {
&mut self.handle
}
}
pub fn open_device(ctx: &Context) -> libusb::Result<DeviceHandles<'_>> {
for device in ctx.devices()?.iter() {
let device_descriptor = device.device_descriptor()?;
if !(device_descriptor.vendor_id() == USB_DEVICE_VID
&& device_descriptor.product_id() == USB_DEVICE_PID) {
continue;
}
let handle = device.open()?;
let mut serial_path = None;
for port_info in serialport::available_ports().unwrap() {
let usb_info = match port_info.port_type {
SerialPortType::UsbPort(usb_info) => usb_info,
_ => continue,
};
if usb_info.vid == USB_DEVICE_VID && usb_info.pid == USB_DEVICE_PID {
serial_path = Some(port_info.port_name);
break;
}
}
let serial_path = serial_path.ok_or(libusb::Error::NoDevice)?;
//handle.reset()?;
return Ok(DeviceHandles {
handle,
serial_path,
});
}
Err(libusb::Error::NoDevice)
}
| true
|
e3ccaea7a8dfc1af416f2fd9299f63255c34736e
|
Rust
|
dylanaraps/eww-static-test
|
/src/widgets/mod.rs
|
UTF-8
| 6,107
| 2.625
| 3
|
[
"MIT"
] |
permissive
|
use crate::{
config::{element::WidgetDefinition, window_definition::WindowName},
eww_state::*,
value::AttrName,
};
use anyhow::*;
use gtk::prelude::*;
use itertools::Itertools;
use std::collections::HashMap;
use std::process::Command;
use widget_definitions::*;
pub mod widget_definitions;
pub mod widget_node;
const CMD_STRING_PLACEHODLER: &str = "{}";
/// Run a command that was provided as an attribute. This command may use a
/// placeholder ('{}') which will be replaced by the value provided as [`arg`]
pub(self) fn run_command<T: 'static + std::fmt::Display + Send + Sync>(cmd: &str, arg: T) {
use wait_timeout::ChildExt;
let cmd = cmd.to_string();
std::thread::spawn(move || {
let cmd = cmd.replace(CMD_STRING_PLACEHODLER, &format!("{}", arg));
log::debug!("Running command from widget: {}", cmd);
let child = Command::new("/bin/sh").arg("-c").arg(&cmd).spawn();
match child {
Ok(mut child) => match child.wait_timeout(std::time::Duration::from_millis(200)) {
// child timed out
Ok(None) => {
log::error!("WARNING: command {} timed out", &cmd);
let _ = child.kill();
let _ = child.wait();
}
Err(err) => log::error!("Failed to execute command {}: {}", cmd, err),
Ok(Some(_)) => {}
},
Err(err) => log::error!("Failed to launch child process: {}", err),
}
});
}
struct BuilderArgs<'a, 'b, 'c, 'd, 'e> {
eww_state: &'a mut EwwState,
widget: &'b widget_node::Generic,
unhandled_attrs: Vec<&'c AttrName>,
window_name: &'d WindowName,
widget_definitions: &'e HashMap<String, WidgetDefinition>,
}
/// build a [`gtk::Widget`] out of a [`element::WidgetUse`] that uses a
/// **builtin widget**. User defined widgets are handled by
/// [widget_use_to_gtk_widget].
///
/// Also registers all the necessary handlers in the `eww_state`.
///
/// This may return `Err` in case there was an actual error while parsing or
/// resolving the widget, Or `Ok(None)` if the widget_use just didn't match any
/// widget name.
fn build_builtin_gtk_widget(
eww_state: &mut EwwState,
window_name: &WindowName,
widget_definitions: &HashMap<String, WidgetDefinition>,
widget: &widget_node::Generic,
) -> Result<Option<gtk::Widget>> {
let mut bargs =
BuilderArgs { eww_state, widget, window_name, unhandled_attrs: widget.attrs.keys().collect(), widget_definitions };
let gtk_widget = match widget_to_gtk_widget(&mut bargs) {
Ok(Some(gtk_widget)) => gtk_widget,
result => {
return result.with_context(|| {
format!(
"{}Error building widget {}",
bargs.widget.text_pos.map(|x| format!("{} |", x)).unwrap_or_default(),
bargs.widget.name,
)
})
}
};
// run resolve functions for superclasses such as range, orientable, and widget
if let Some(gtk_widget) = gtk_widget.dynamic_cast_ref::<gtk::Container>() {
resolve_container_attrs(&mut bargs, >k_widget);
for child in &widget.children {
let child_widget = child.render(bargs.eww_state, window_name, widget_definitions).with_context(|| {
format!(
"{}error while building child '{:#?}' of '{}'",
widget.text_pos.map(|x| format!("{} |", x)).unwrap_or_default(),
&child,
>k_widget.get_widget_name()
)
})?;
gtk_widget.add(&child_widget);
child_widget.show();
}
}
if let Some(w) = gtk_widget.dynamic_cast_ref() {
resolve_range_attrs(&mut bargs, &w)
}
if let Some(w) = gtk_widget.dynamic_cast_ref() {
resolve_orientable_attrs(&mut bargs, &w)
};
resolve_widget_attrs(&mut bargs, >k_widget);
if !bargs.unhandled_attrs.is_empty() {
log::error!(
"{}: Unknown attribute used in {}: {}",
widget.text_pos.map(|x| format!("{} | ", x)).unwrap_or_default(),
widget.name,
bargs.unhandled_attrs.iter().map(|x| x.to_string()).join(", ")
)
}
Ok(Some(gtk_widget))
}
#[macro_export]
macro_rules! resolve_block {
($args:ident, $gtk_widget:ident, {
$(
prop( $( $attr_name:ident : $typecast_func:ident $(= $default:expr)?),*) $code:block
),+ $(,)?
}) => {
$({
$(
$args.unhandled_attrs.retain(|a| &a.0 != &::std::stringify!($attr_name).replace('_', "-"));
)*
let attr_map: Result<_> = try {
::maplit::hashmap! {
$(
crate::value::AttrName(::std::stringify!($attr_name).to_owned()) =>
resolve_block!(@get_value $args, &::std::stringify!($attr_name).replace('_', "-"), $(= $default)?)
),*
}
};
if let Ok(attr_map) = attr_map {
$args.eww_state.resolve(
$args.window_name,
attr_map,
::glib::clone!(@strong $gtk_widget => move |attrs| {
$(
let $attr_name = attrs.get( ::std::stringify!($attr_name) ).context("something went terribly wrong....")?.$typecast_func()?;
)*
$code
Ok(())
})
);
}
})+
};
(@get_value $args:ident, $name:expr, = $default:expr) => {
$args.widget.get_attr($name).cloned().unwrap_or(AttrVal::from_primitive($default))
};
(@get_value $args:ident, $name:expr,) => {
$args.widget.get_attr($name)?.clone()
}
}
#[allow(unused)]
macro_rules! log_errors {
($body:expr) => {{
let result = try { $body };
if let Err(e) = result {
log::warn!("{}", e);
}
}};
}
| true
|
be56d38fb8dde486b0d105709c1513826af89e8c
|
Rust
|
georust/proj
|
/src/geo_types.rs
|
UTF-8
| 11,167
| 3.140625
| 3
|
[
"MIT",
"Apache-2.0"
] |
permissive
|
use crate::{Proj, ProjError, Transform};
use geo_types::{coord, Geometry};
///```rust
/// # use approx::assert_relative_eq;
/// extern crate proj;
/// use proj::Proj;
/// use geo_types::coord;
///
/// let from = "EPSG:2230";
/// let to = "EPSG:26946";
/// let nad_ft_to_m = Proj::new_known_crs(&from, &to, None).unwrap();
/// let result = nad_ft_to_m
/// .convert(coord! { x: 4760096.421921f64, y: 3744293.729449f64 })
/// .unwrap();
/// assert_relative_eq!(result.x, 1450880.29f64, epsilon=1.0e-2);
/// assert_relative_eq!(result.y, 1141263.01f64, epsilon=1.0e-2);
/// ```
impl<T: crate::proj::CoordinateType> crate::Coord<T> for geo_types::Coord<T> {
fn x(&self) -> T {
self.x
}
fn y(&self) -> T {
self.y
}
fn from_xy(x: T, y: T) -> Self {
coord! { x: x, y: y }
}
}
///```rust
/// # use approx::assert_relative_eq;
/// extern crate proj;
/// use proj::Proj;
/// use geo_types::Point;
///
/// let from = "EPSG:2230";
/// let to = "EPSG:26946";
/// let nad_ft_to_m = Proj::new_known_crs(&from, &to, None).unwrap();
/// let result = nad_ft_to_m
/// .convert(Point::new(4760096.421921f64, 3744293.729449f64))
/// .unwrap();
/// assert_relative_eq!(result.x(), 1450880.29f64, epsilon=1.0e-2);
/// assert_relative_eq!(result.y(), 1141263.01f64, epsilon=1.0e-2);
/// ```
impl<T: crate::proj::CoordinateType> crate::Coord<T> for geo_types::Point<T> {
fn x(&self) -> T {
geo_types::Point::x(*self)
}
fn y(&self) -> T {
geo_types::Point::y(*self)
}
fn from_xy(x: T, y: T) -> Self {
Self::new(x, y)
}
}
impl<T> Transform<T> for geo_types::Geometry<T>
where
T: crate::proj::CoordinateType,
{
type Output = Self;
fn transformed(&self, proj: &Proj) -> Result<Self, ProjError> {
let mut output = self.clone();
output.transform(proj)?;
Ok(output)
}
fn transform(&mut self, proj: &Proj) -> Result<(), ProjError> {
match self {
Geometry::Point(g) => g.transform(proj),
Geometry::Line(g) => g.transform(proj),
Geometry::LineString(g) => g.transform(proj),
Geometry::Polygon(g) => g.transform(proj),
Geometry::MultiPoint(g) => g.transform(proj),
Geometry::MultiLineString(g) => g.transform(proj),
Geometry::MultiPolygon(g) => g.transform(proj),
Geometry::GeometryCollection(g) => g.transform(proj),
Geometry::Rect(g) => g.transform(proj),
Geometry::Triangle(g) => g.transform(proj),
}
}
}
impl<T> Transform<T> for geo_types::Coord<T>
where
T: crate::proj::CoordinateType,
{
type Output = Self;
fn transformed(&self, proj: &Proj) -> Result<Self, ProjError> {
let mut output = *self;
output.transform(proj)?;
Ok(output)
}
fn transform(&mut self, proj: &Proj) -> Result<(), ProjError> {
*self = proj.convert(*self)?;
Ok(())
}
}
impl<T> Transform<T> for geo_types::Point<T>
where
T: crate::proj::CoordinateType,
{
type Output = Self;
fn transformed(&self, proj: &Proj) -> Result<Self, ProjError> {
let mut output = *self;
output.transform(proj)?;
Ok(output)
}
fn transform(&mut self, proj: &Proj) -> Result<(), ProjError> {
self.0.transform(proj)
}
}
impl<T> Transform<T> for geo_types::Line<T>
where
T: crate::proj::CoordinateType,
{
type Output = Self;
fn transformed(&self, proj: &Proj) -> Result<Self, ProjError> {
let mut output = *self;
output.transform(proj)?;
Ok(output)
}
fn transform(&mut self, proj: &Proj) -> Result<(), ProjError> {
self.start.transform(proj)?;
self.end.transform(proj)?;
Ok(())
}
}
impl<T> Transform<T> for geo_types::LineString<T>
where
T: crate::proj::CoordinateType,
{
type Output = Self;
fn transformed(&self, proj: &Proj) -> Result<Self, ProjError> {
let mut output = self.clone();
output.transform(proj)?;
Ok(output)
}
fn transform(&mut self, proj: &Proj) -> Result<(), ProjError> {
proj.convert_array(&mut self.0)?;
Ok(())
}
}
impl<T> Transform<T> for geo_types::Polygon<T>
where
T: crate::proj::CoordinateType,
{
type Output = Self;
fn transformed(&self, proj: &Proj) -> Result<Self, ProjError> {
let mut output = self.clone();
output.transform(proj)?;
Ok(output)
}
fn transform(&mut self, proj: &Proj) -> Result<(), ProjError> {
let mut exterior_result = Ok(());
self.exterior_mut(|exterior| {
exterior_result = exterior.transform(proj);
});
exterior_result?;
let mut interiors_result = Ok(());
self.interiors_mut(|interiors| {
interiors_result = interiors
.iter_mut()
.try_for_each(|interior| interior.transform(proj))
});
interiors_result?;
Ok(())
}
}
impl<T> Transform<T> for geo_types::MultiPoint<T>
where
T: crate::proj::CoordinateType,
{
type Output = Self;
fn transformed(&self, proj: &Proj) -> Result<Self, ProjError> {
let mut output = self.clone();
output.transform(proj)?;
Ok(output)
}
fn transform(&mut self, proj: &Proj) -> Result<(), ProjError> {
proj.convert_array(&mut self.0)?;
Ok(())
}
}
impl<T> Transform<T> for geo_types::MultiLineString<T>
where
T: crate::proj::CoordinateType,
{
type Output = Self;
fn transformed(&self, proj: &Proj) -> Result<Self, ProjError> {
let mut output = self.clone();
output.transform(proj)?;
Ok(output)
}
fn transform(&mut self, proj: &Proj) -> Result<(), ProjError> {
for line_string in &mut self.0 {
line_string.transform(proj)?;
}
Ok(())
}
}
impl<T> Transform<T> for geo_types::MultiPolygon<T>
where
T: crate::proj::CoordinateType,
{
type Output = Self;
fn transformed(&self, proj: &Proj) -> Result<Self, ProjError> {
let mut output = self.clone();
output.transform(proj)?;
Ok(output)
}
fn transform(&mut self, proj: &Proj) -> Result<(), ProjError> {
for polygon in &mut self.0 {
polygon.transform(proj)?;
}
Ok(())
}
}
impl<T> Transform<T> for geo_types::GeometryCollection<T>
where
T: crate::proj::CoordinateType,
{
type Output = Self;
fn transformed(&self, proj: &Proj) -> Result<Self, ProjError> {
let mut output = self.clone();
output.transform(proj)?;
Ok(output)
}
fn transform(&mut self, proj: &Proj) -> Result<(), ProjError> {
for geometry in &mut self.0 {
geometry.transform(proj)?;
}
Ok(())
}
}
impl<T> Transform<T> for geo_types::Rect<T>
where
T: crate::proj::CoordinateType,
{
type Output = Self;
fn transformed(&self, proj: &Proj) -> Result<Self, ProjError> {
let mut output = *self;
output.transform(proj)?;
Ok(output)
}
fn transform(&mut self, proj: &Proj) -> Result<(), ProjError> {
let a = self.min();
let b = self.max();
let new = geo_types::Rect::new(proj.convert(a)?, proj.convert(b)?);
*self = new;
Ok(())
}
}
impl<T> Transform<T> for geo_types::Triangle<T>
where
T: crate::proj::CoordinateType,
{
type Output = Self;
fn transformed(&self, proj: &Proj) -> Result<Self, ProjError> {
let mut output = *self;
output.transform(proj)?;
Ok(output)
}
fn transform(&mut self, proj: &Proj) -> Result<(), ProjError> {
self.0.transform(proj)?;
self.1.transform(proj)?;
self.2.transform(proj)?;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use geo_types::{point, MultiPoint, Rect};
#[test]
fn test_point() {
let mut subject = point!(x: 4760096.421921f64, y: 3744293.729449f64);
subject
.transform_crs_to_crs("EPSG:2230", "EPSG:26946")
.unwrap();
let expected = point!(x: 1450880.29f64, y: 1141263.01f64);
assert_relative_eq!(subject, expected, epsilon = 0.2);
}
#[test]
fn test_rect() {
let mut subject = {
let point_a = point!(x: 4760096.421921f64, y: 3744293.729449f64);
let point_b = point!(x: 4760196.421921f64, y: 3744393.729449f64);
Rect::new(point_a, point_b)
};
subject
.transform_crs_to_crs("EPSG:2230", "EPSG:26946")
.unwrap();
let expected = {
let point_a = point!(x: 1450880.2910605022, y: 1141263.0111604782);
let point_b = point!(x: 1450910.771121464, y: 1141293.4912214363);
Rect::new(point_a, point_b)
};
assert_relative_eq!(subject, expected, epsilon = 0.2);
}
#[test]
fn test_multi_point() {
let mut subject = {
let point_a = point!(x: 4760096.421921f64, y: 3744293.729449f64);
let point_b = point!(x: 4760196.421921f64, y: 3744393.729449f64);
MultiPoint(vec![point_a, point_b])
};
subject
.transform_crs_to_crs("EPSG:2230", "EPSG:26946")
.unwrap();
let expected = {
let point_a = point!(x: 1450880.2910605022, y: 1141263.0111604782);
let point_b = point!(x: 1450910.771121464, y: 1141293.4912214363);
MultiPoint(vec![point_a, point_b])
};
assert_relative_eq!(subject, expected, epsilon = 0.2);
}
#[test]
fn test_geometry_collection() {
let mut subject = {
let multi_point = {
let point_a = point!(x: 4760096.421921f64, y: 3744293.729449f64);
let point_b = point!(x: 4760196.421921f64, y: 3744393.729449f64);
MultiPoint(vec![point_a, point_b])
};
let rect = {
let point_a = point!(x: 4760096.421921f64, y: 3744293.729449f64);
let point_b = point!(x: 4760196.421921f64, y: 3744393.729449f64);
Rect::new(point_a, point_b)
};
geo_types::GeometryCollection(vec![Geometry::from(multi_point), Geometry::from(rect)])
};
subject
.transform_crs_to_crs("EPSG:2230", "EPSG:26946")
.unwrap();
let expected = {
let multi_point = {
let point_a = point!(x: 1450880.2910605022, y: 1141263.0111604782);
let point_b = point!(x: 1450910.771121464, y: 1141293.4912214363);
MultiPoint(vec![point_a, point_b])
};
let rect = {
let point_a = point!(x: 1450880.2910605022, y: 1141263.0111604782);
let point_b = point!(x: 1450910.771121464, y: 1141293.4912214363);
Rect::new(point_a, point_b)
};
geo_types::GeometryCollection(vec![Geometry::from(multi_point), Geometry::from(rect)])
};
assert_relative_eq!(subject, expected, epsilon = 0.2);
}
}
| true
|
169f2cac28fa49aacc5291b73e23e6f7ce2282af
|
Rust
|
ydzz/EternalR
|
/compiler/src/utils.rs
|
UTF-8
| 2,583
| 2.78125
| 3
|
[
"MIT"
] |
permissive
|
use typed_arena::{Arena};
use gluon::base::pos::{BytePos,Span};
use ast::types::{SourceSpan,SourcePos};
pub(crate) trait ArenaExt<T> {
fn alloc_fixed<'a, I>(&'a self, iter: I) -> &'a mut [T]
where
I: IntoIterator<Item = T>,
T: Default;
}
impl<T> ArenaExt<T> for Arena<T> {
fn alloc_fixed<'a, I>(&'a self, iter: I) -> &'a mut [T]
where
I: IntoIterator<Item = T>,
T: Default,
{
use std::{mem::MaybeUninit, ptr};
let iter = iter.into_iter();
unsafe {
struct FillRemainingOnDrop<U: Default> {
ptr: *mut U,
end: *mut U,
}
impl<U: Default> Drop for FillRemainingOnDrop<U> {
fn drop(&mut self) {
unsafe {
while self.ptr != self.end {
ptr::write(self.ptr, U::default());
self.ptr = self.ptr.add(1);
}
}
}
}
let (len, max) = iter.size_hint();
assert!(Some(len) == max);
let elems = self.alloc_uninitialized(len);
{
let elems = elems as *mut _ as *mut MaybeUninit<T>;
let mut fill = FillRemainingOnDrop {
ptr: elems as *mut T,
end: elems.add(len) as *mut T,
};
for elem in iter {
assert!(fill.ptr != fill.end);
ptr::write(fill.ptr, elem);
fill.ptr = fill.ptr.add(1);
}
}
let elems = elems as *mut _ as *mut [T];
&mut *elems
}
}
}
pub fn split_last(source:&str,ch:char) -> (&str,&str) {
let mut last_find_idx = 0;
let mut idx = 0;
for chr in source.chars() {
if chr == ch {
last_find_idx = idx;
}
idx += 1
}
let (s,_) = source.split_at(last_find_idx);
let (_,e) = source.split_at(last_find_idx + 1);
(s,e)
}
pub fn source_span_to_byte_span(source_span:&SourceSpan) -> Span<BytePos> {
let start = source_pos_to_byte_pos(&source_span.start);
let end =source_pos_to_byte_pos(&source_span.end);
Span::new(start, end)
}
pub fn source_pos_to_byte_pos(source_pos:&SourcePos) -> BytePos {
let uline = source_pos.line as u32;
let ucol = source_pos.col as u32;
let hight16 = (uline << 16) & 0xffff0000;
let low16 = ucol & & 0x0000ffff;
let value = hight16 | low16;
BytePos(value)
}
| true
|
4f8d396bb7737637a40860b2472338e5e08c1b3a
|
Rust
|
intendednull/yew
|
/examples/boids/src/slider.rs
|
UTF-8
| 2,536
| 2.953125
| 3
|
[
"Apache-2.0",
"MIT"
] |
permissive
|
use std::cell::Cell;
use yew::{html, Callback, Component, ComponentLink, Html, InputData, Properties, ShouldRender};
thread_local! {
static SLIDER_ID: Cell<usize> = Cell::default();
}
fn next_slider_id() -> usize {
SLIDER_ID.with(|cell| cell.replace(cell.get() + 1))
}
#[derive(Clone, Debug, PartialEq, Properties)]
pub struct Props {
pub label: &'static str,
pub value: f64,
pub onchange: Callback<f64>,
#[prop_or_default]
pub precision: Option<usize>,
#[prop_or_default]
pub percentage: bool,
#[prop_or_default]
pub min: f64,
pub max: f64,
#[prop_or_default]
pub step: Option<f64>,
}
pub struct Slider {
props: Props,
id: usize,
}
impl Component for Slider {
type Message = ();
type Properties = Props;
fn create(props: Self::Properties, _link: ComponentLink<Self>) -> Self {
Self {
props,
id: next_slider_id(),
}
}
fn update(&mut self, _msg: Self::Message) -> ShouldRender {
unimplemented!()
}
fn change(&mut self, props: Self::Properties) -> ShouldRender {
if self.props != props {
self.props = props;
true
} else {
false
}
}
fn view(&self) -> Html {
let Props {
label,
value,
ref onchange,
precision,
percentage,
min,
max,
step,
} = self.props;
let precision = precision.unwrap_or_else(|| if percentage { 1 } else { 0 });
let display_value = if percentage {
format!("{:.p$}%", 100.0 * value, p = precision)
} else {
format!("{:.p$}", value, p = precision)
};
let id = format!("slider-{}", self.id);
let step = step.unwrap_or_else(|| {
let p = if percentage { precision + 2 } else { precision };
10f64.powi(-(p as i32))
});
html! {
<div class="slider">
<label for=id.clone() class="slider__label">{ label }</label>
<input type="range"
id=id
class="slider__input"
min=min.to_string() max=max.to_string() step=step.to_string()
oninput=onchange.reform(|data: InputData| data.value.parse().unwrap())
value=value.to_string()
/>
<span class="slider__value">{ display_value }</span>
</div>
}
}
}
| true
|
fe1ec5b8d830a5a3ad6ec719c252e29003b99774
|
Rust
|
hekarusindo/pumltestrust
|
/src/main.rs
|
UTF-8
| 6,851
| 2.84375
| 3
|
[
"MIT"
] |
permissive
|
use std::env;
use std::fs;
use c_lexer;
use c_lexer::token::Token::*;
use c_lexer::token::Token;
//TODO do while, if else without {},switch, bug fix
fn main() {
let args: Vec<String> = env::args().collect();
let path = args[1].to_string();
let _output = args[1].to_string();
let code = fs::read_to_string(path).unwrap();
let l=c_lexer::Lexer::lex(&code);
let ll=l.unwrap();
//let mut scopes = Vec::new();
let mut _depth = 0;
let mut _depth: usize = 0;
let mut _id = false;
let mut _state=FuncName;
let mut tk_itr = ll.clone();
f_eq(&mut tk_itr.iter());
}
//if,brace,while,for or line
fn f_eq(tokens_iter: &mut std::slice::Iter<Token>){
loop {
match tokens_iter.next() {
Some(tk) => {
match tk {
IF => {
print!("\nif");
f_if(tokens_iter);
println!("\nendif");},
LBrace => {
println!(";");
f_eq(tokens_iter)},
WHILE => {
print!("\nwhile");
f_while(tokens_iter);
println!("\nendwhile");},
FOR => {
//for==while in plantuml
print!("\nwhile");
f_while(tokens_iter);
println!("\nendwhile");},
RBrace=> {
f_else(tokens_iter);
break},
LineTerminator=>{}
_ => {
print!(":");
print_token(tk);
f_line(tokens_iter);},
}
},
None => break,
};
}
}
fn f_line(tokens_iter: &mut std::slice::Iter<Token>){
loop {
match tokens_iter.next() {
Some(tk) => {
match tk {
LineTerminator => {
//to do ""
println!(";");
break},
LBrace => {
println!(";");
f_eq(tokens_iter);break},
_ => {print_token(tk);},
}
},
None => break,
};
}
}
fn f_if(tokens_iter: &mut std::slice::Iter<Token>){
loop {
match tokens_iter.next() {
Some(tk) => {
match tk {
// TODO
//~ LineTerminator=>{
//~ //no scope,"if" that is 1 line
//~ println!("then");
//~ break},
LBrace => {
println!("then");
f_eq(tokens_iter);break},
_ => {print_token(tk);},
}
},
None => break,
};
}
}
fn f_elif(tokens_iter: &mut std::slice::Iter<Token>){
loop {
match tokens_iter.next() {
Some(tk) => {
match tk {
//else
LineTerminator=>break,
//elseif
IF=> {print!("if");
f_if(tokens_iter);break},
//else
LBrace => {
println!("");
f_eq(tokens_iter);break},
_ => {print_token(tk);},
}
},
None => break,
};
}
}
fn f_else(tokens_iter: &mut std::slice::Iter<Token>){
loop {
match tokens_iter.next() {
Some(tk) => {
match tk {
//endif
LineTerminator=>break,
//else or elseif
ELSE => {
print!("\nelse");
f_elif(tokens_iter);
break},
LBrace => {
println!("");
f_eq(tokens_iter);break},
_ => {print_token(tk);},
}
},
None => break,
};
}
}
fn f_for(){}
fn f_while(tokens_iter: &mut std::slice::Iter<Token>){
loop {
match tokens_iter.next() {
Some(tk) => {
match tk {
LBrace => {
println!("");
f_eq(tokens_iter);break},
_ => {print_token(tk);},
}
},
None => break,
};
}
}
fn f_switch(){}
fn print_token(a: &c_lexer::token::Token){
let b=match a {
LBrace => "{",
RBrace => "}",
LParen => "(",
RParen => ")",
LBracket => "[",
RBracket => "]",
Semicolon => ";",
Assign => "=",
Lt => "<",
Gt => ">",
Minus => "-",
Tilde => "~",
Exclamation => "!",
Plus => "+",
Multi => "*",
Slash => "/",
Colon => ":",
QuestionMark => "?",
Comma => ",",
Dot => ".",
SingleAnd => "&",
InclusiveOr => "|",
ExclusiveOr => "^",
Mod => "%",
//Identifier(IStr) => //IStr.as_str(),
//NumericLiteral(Number)
//StringLiteral(String)
//FuncName => "__func__",
SIZEOF => "sizeof",
PtrOp => "->",
IncOp => "++",
DecOp => "--",
LeftOp => "<<",
RightOp => ">>",
LeOp => "<=",
GeOp => ">=",
EqOp => "==",
NeOp => "!=",
AndOp => "&&",
OrOp => "||",
MulAssign => "*=",
DivAssign => "/=",
ModAssign => "%=",
AddAssign => "+=",
SubAssign => "-=",
LeftAssign => "<<=",
RightAssign => ">>=",
AndAssign => "&=",
XorAssign => "^=",
OrAssign => "|=",
//ELLIPSIS => ...
LineTerminator => "\n",
BREAK => "beark",
RETURN => "return",
CONTINUE => "continue",
_ =>{" "},
};
match a {
Identifier(iii) => {print!("{}",iii.as_str());},
NumericLiteral(n)=> {
print!("{}",n.integer);},
_ =>{
print!("{}",b);
},
}
}
| true
|
a25f9336eaf8f602c2b79f10b3205ff8b6fa6fd2
|
Rust
|
21eleven/leetcode-solutions
|
/rust/1342_number_of_steps_to_reduce_a_number_to_zero/sim.rs
|
UTF-8
| 1,223
| 3.75
| 4
|
[] |
no_license
|
/*
1342. Number of Steps to Reduce a Number to Zero
Easy
Given a non-negative integer num, return the number of steps to reduce it to zero. If the current number is even, you have to divide it by 2, otherwise, you have to subtract 1 from it.
Example 1:
Input: num = 14
Output: 6
Explanation:
Step 1) 14 is even; divide by 2 and obtain 7.
Step 2) 7 is odd; subtract 1 and obtain 6.
Step 3) 6 is even; divide by 2 and obtain 3.
Step 4) 3 is odd; subtract 1 and obtain 2.
Step 5) 2 is even; divide by 2 and obtain 1.
Step 6) 1 is odd; subtract 1 and obtain 0.
Example 2:
Input: num = 8
Output: 4
Explanation:
Step 1) 8 is even; divide by 2 and obtain 4.
Step 2) 4 is even; divide by 2 and obtain 2.
Step 3) 2 is even; divide by 2 and obtain 1.
Step 4) 1 is odd; subtract 1 and obtain 0.
Example 3:
Input: num = 123
Output: 12
Constraints:
0 <= num <= 10^6
*/
impl Solution {
pub fn number_of_steps (mut num: i32) -> i32 {
let mut count = 0;
loop {
if num == 0 {
break;
} else if num % 2 == 0 {
num /= 2;
} else {
num -= 1;
}
count += 1;
}
count
}
}
| true
|
6cf2d38ed4106f636e08c48ca290475d786c6770
|
Rust
|
tlafebre/address_book
|
/src/db.rs
|
UTF-8
| 2,137
| 2.890625
| 3
|
[] |
no_license
|
extern crate rusqlite;
use rusqlite::{params, Connection, Error, Result};
use std::path::PathBuf;
use super::contact;
use contact::Contact;
#[derive(Debug)]
pub struct Database {
pub path: PathBuf,
}
impl Database {
pub fn create_table(&self) -> Result<()> {
let conn = self.connect()?;
conn.execute(
"CREATE TABLE contacts (
id INTEGER PRIMARY KEY,
first_name TEXT NOT NULL,
last_name TEXT NOT NULL,
date_of_birth TEXT NOT NULL,
address TEXT NOT NULL,
email TEXT NOT NULL
)",
params![],
)
.expect("failed to create table");
Ok(())
}
pub fn connect(&self) -> Result<Connection, Error> {
let conn = Connection::open(self.path.clone()).expect("failed to connect to database");
Ok(conn)
}
pub fn insert(&self, contact: Contact) -> Result<()> {
let conn = self.connect()?;
conn.execute(
"INSERT INTO contacts (first_name, last_name, date_of_birth, address, email) VALUES (?1, ?2, ?3, ?4, ?5)",
params![contact.first_name, contact.last_name, contact.date_of_birth, contact.address, contact.email],
)?;
Ok(())
}
pub fn list_contacts(&self) -> Result<Vec<Contact>, Error> {
let conn = self.connect().unwrap();
let mut results = conn.prepare(
"SELECT first_name, last_name, date_of_birth, address, email FROM contacts
ORDER BY last_name ASC, first_name ASC",
)?;
let rows = results.query_map(params![], |row| {
Ok(Contact {
first_name: row.get(0)?,
last_name: row.get(1)?,
date_of_birth: row.get(2)?,
address: row.get(3)?,
email: row.get(4)?,
})
})?;
let mut contacts = Vec::new();
for contact in rows {
contacts.push(contact.unwrap());
}
Ok(contacts)
}
}
| true
|
84f3092247bfbccce0c016cde0b7961b576dd4eb
|
Rust
|
AbsoluteVirtueXI/api-test
|
/src/bin/routing.rs
|
UTF-8
| 2,118
| 2.96875
| 3
|
[] |
no_license
|
#![deny(warnings)]
use warp::Filter;
use serde::{Deserialize};
#[derive(Deserialize)]
struct SumQuery {
left: u32,
right: u32,
}
#[tokio::main]
async fn main() {
let sumquery = warp::path("sumquery")
.and(warp::query::<SumQuery>())
.and(warp::path::end())
.map(|sum_query: SumQuery|{
format!("{} + {} = {}", sum_query.left, sum_query.right, sum_query.left + sum_query.right)
});
let rawquery = warp::path("rawquery")
.and(warp::query::raw())
.map(|receive| {
receive
});
// GET /hi
let hi = warp::path("hi").and(warp::path::end()).map(|| "Hello, world");
// GET /bye/:string
let bye = warp::path("bye")
.and(warp::path::param())
.and(warp::path::end())
.map(|name: String| format!("Good bye, {}!", name));
// GET /hello/from/warp
let hello_from_warp = warp::path!("hello" / "from" / "warp")
.map(|| "Hello from warp");
// GET /sum/:u32/:u32
let sum = warp::path!("sum" / u32 / u32).map(|a, b| format!{"{} + {} = {}", a, b, a + b});
// GET /:u16/times/:u16
let times = warp::path!(u16 / "times" / u16)
.map(|a, b| format!{"{} times {} = {}", a, b, a*b });
// GET /math/sum/:u32/:u32
// GEt /math/:16/times/:16
let math = warp::path("math").and(sum.or(times));
// GET /math
let help = warp::path("math")
.and(warp::path::end())
.map(|| "This is the Math api. Try calling /math/sum/:u32/:u32 or /math/:u16/times/:u16");
let math = help.or(math);
let sum =
sum.map(|output| format!("(This route has moved to /math/sum/:u16/:u16) {}", output));
let times =
times.map(|output| format!("(This route has moved to /math/:u16/times/:u16) {}", output));
let routes = warp::get()
.and(
hi
.or(bye)
.or(hello_from_warp)
.or(math)
.or(sum)
.or(times)
.or(sumquery)
.or(rawquery));
warp::serve(routes).run(([192, 168, 0, 10], 3030)).await;
}
| true
|
015552cc805c4711cd6aadea2d4adef1f3591669
|
Rust
|
fluxxu/actix-web-async-compat
|
/src/lib.rs
|
UTF-8
| 981
| 2.796875
| 3
|
[] |
no_license
|
//! Actix web 1.x async/await shim.
use futures::{self, compat::Compat, FutureExt, TryFutureExt};
use std::pin::Pin;
/// Convert a async fn into a actix-web handler.
///
/// ```rust
/// use actix_web::{web, App, HttpResponse, Error};
/// use std::time::{Instant, Duration};
/// use tokio::timer::Delay;
/// use actix_web_async_compat::async_compat;
///
/// async fn index() -> Result<HttpResponse, Error> {
/// // wait 2s
/// Delay::new(Instant::now() + Duration::from_secs(2)).await?;
/// ok(HttpResponse::Ok().finish())
/// }
///
/// App::new().service(web::resource("/").route(
/// web::to_async(async_compat(index)))
/// );
/// ```
pub fn async_compat<F, P, R, O, E>(
f: F,
) -> impl Fn(P) -> Compat<Pin<Box<dyn futures::Future<Output = Result<O, E>>>>> + Clone
where
F: Fn(P) -> R + Clone + 'static,
P: 'static,
R: futures::Future<Output = Result<O, E>> + 'static,
O: 'static,
E: 'static,
{
move |u| f(u).boxed_local().compat()
}
| true
|
0f9b95ad1a2c8dbb9aa0f5db5712f519314c1d07
|
Rust
|
7e4/himalaya
|
/src/domain/msg/flag_arg.rs
|
UTF-8
| 3,278
| 3.296875
| 3
|
[] |
no_license
|
//! Message flag CLI module.
//!
//! This module provides subcommands, arguments and a command matcher related to the message flag
//! domain.
use anyhow::Result;
use clap::{self, App, AppSettings, Arg, ArgMatches, SubCommand};
use log::{debug, trace};
use crate::domain::msg::msg_arg;
type SeqRange<'a> = &'a str;
type Flags<'a> = Vec<&'a str>;
/// Represents the flag commands.
pub enum Command<'a> {
/// Represents the add flags command.
Add(SeqRange<'a>, Flags<'a>),
/// Represents the set flags command.
Set(SeqRange<'a>, Flags<'a>),
/// Represents the remove flags command.
Remove(SeqRange<'a>, Flags<'a>),
}
/// Defines the flag command matcher.
pub fn matches<'a>(m: &'a ArgMatches) -> Result<Option<Command<'a>>> {
if let Some(m) = m.subcommand_matches("add") {
debug!("add subcommand matched");
let seq_range = m.value_of("seq-range").unwrap();
trace!(r#"seq range: "{}""#, seq_range);
let flags: Vec<&str> = m.values_of("flags").unwrap_or_default().collect();
trace!(r#"flags: "{:?}""#, flags);
return Ok(Some(Command::Add(seq_range, flags)));
}
if let Some(m) = m.subcommand_matches("set") {
debug!("set subcommand matched");
let seq_range = m.value_of("seq-range").unwrap();
trace!(r#"seq range: "{}""#, seq_range);
let flags: Vec<&str> = m.values_of("flags").unwrap_or_default().collect();
trace!(r#"flags: "{:?}""#, flags);
return Ok(Some(Command::Set(seq_range, flags)));
}
if let Some(m) = m.subcommand_matches("remove") {
trace!("remove subcommand matched");
let seq_range = m.value_of("seq-range").unwrap();
trace!(r#"seq range: "{}""#, seq_range);
let flags: Vec<&str> = m.values_of("flags").unwrap_or_default().collect();
trace!(r#"flags: "{:?}""#, flags);
return Ok(Some(Command::Remove(seq_range, flags)));
}
Ok(None)
}
/// Defines the flags argument.
fn flags_arg<'a>() -> Arg<'a, 'a> {
Arg::with_name("flags")
.help("IMAP flags")
.long_help("IMAP flags. Flags are case-insensitive, and they do not need to be prefixed with `\\`.")
.value_name("FLAGS…")
.multiple(true)
.required(true)
}
/// Contains flag subcommands.
pub fn subcmds<'a>() -> Vec<App<'a, 'a>> {
vec![SubCommand::with_name("flag")
.aliases(&["flags", "flg"])
.about("Handles flags")
.setting(AppSettings::SubcommandRequiredElseHelp)
.subcommand(
SubCommand::with_name("add")
.aliases(&["a"])
.about("Adds flags to a message")
.arg(msg_arg::seq_range_arg())
.arg(flags_arg()),
)
.subcommand(
SubCommand::with_name("set")
.aliases(&["s", "change", "c"])
.about("Replaces all message flags")
.arg(msg_arg::seq_range_arg())
.arg(flags_arg()),
)
.subcommand(
SubCommand::with_name("remove")
.aliases(&["rem", "rm", "r", "delete", "del", "d"])
.about("Removes flags from a message")
.arg(msg_arg::seq_range_arg())
.arg(flags_arg()),
)]
}
| true
|
8bca9c6ca31b3ca0738bb958f37ece1aa3f3a4a8
|
Rust
|
isgasho/dialectic
|
/dialectic/src/types/split.rs
|
UTF-8
| 1,935
| 2.90625
| 3
|
[
"MIT"
] |
permissive
|
use std::{any::Any, marker::PhantomData};
use super::sealed::IsSession;
use super::*;
/// Split the connection into send-only and receive-only halves using [`split`](crate::Chan::split).
///
/// The type `Split<P, Q, R>` means: do the [`Transmit`](crate::backend::Transmit)-only session `P`
/// concurrently with the [`Receive`](crate::backend::Receive)-only session `Q`, running them both
/// to [`Done`], and when they've completed, do the session `R`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Split<P, Q, R>(
PhantomData<fn() -> P>,
PhantomData<fn() -> Q>,
PhantomData<fn() -> R>,
);
impl<P, Q, R> Default for Split<P, Q, R> {
fn default() -> Self {
Split(PhantomData, PhantomData, PhantomData)
}
}
impl<P: Any, Q: Any, R: Any> IsSession for Split<P, Q, R> {}
impl<P: HasDual, Q: HasDual, R: HasDual> HasDual for Split<P, Q, R> {
/// Note how the dual flips the position of `P` and `Q`, because `P::Dual` is a receiving
/// session, and therefore belongs on the right of the split, and `Q::Dual` is a sending
/// session, and therefore belongs on the left of the split.
type DualSession = Split<Q::DualSession, P::DualSession, R::DualSession>;
}
impl<P: 'static, Q: 'static, R: 'static> Actionable for Split<P, Q, R> {
type NextAction = Self;
}
impl<N: Unary, P: Scoped<N>, Q: Scoped<N>, R: Scoped<N>> Scoped<N> for Split<P, Q, R> {}
impl<N: Unary, P: Subst<S, N>, Q: Subst<S, N>, R: Subst<S, N>, S> Subst<S, N> for Split<P, Q, R> {
type Substituted = Split<P::Substituted, Q::Substituted, R::Substituted>;
}
impl<N: Unary, P: 'static, Q: 'static, R: Then<S, N>, S> Then<S, N> for Split<P, Q, R> {
type Combined = Split<P, Q, R::Combined>;
}
impl<N: Unary, Level: Unary, P: Lift<N, Level>, Q: Lift<N, Level>, R: Lift<N, Level>> Lift<N, Level>
for Split<P, Q, R>
{
type Lifted = Split<P::Lifted, Q::Lifted, R::Lifted>;
}
| true
|
68bee3340c94ee7db2e817ff5695a45dba9120cb
|
Rust
|
UkolovaOlga/rust-lnpbp
|
/src/rgb/stash/stash.rs
|
UTF-8
| 6,214
| 2.578125
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
// LNP/BP Rust Library
// Written in 2020 by
// Dr. Maxim Orlovsky <orlovsky@pandoracore.com>
//
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neighboring rights to this software to
// the public domain worldwide. This software is distributed without
// any warranty.
//
// You should have received a copy of the MIT License
// along with this software.
// If not, see <https://opensource.org/licenses/MIT>.
//use bitcoin::Transaction;
//use std::collections::HashSet;
use crate::rgb::{Anchor, Consignment, ContractId, Node, SealDefinition, Transition};
#[derive(Clone, PartialEq, Eq, Debug, Display, From, Error)]
#[display_from(Debug)]
pub enum Error {}
pub trait Stash {
fn consign(
&self,
contract_id: ContractId,
transition: Transition,
anchor: Anchor,
endpoints: Vec<SealDefinition>,
) -> Result<Consignment, Error>;
fn merge(&mut self, consignment: Consignment) -> Result<Vec<Box<dyn Node>>, Error>;
}
/*
/// Top-level structure used by client wallets to manage all known RGB smart
/// contracts and related data
pub struct Stash {
/// A contract is a genesis + the whole known history graph under specific
/// genesis
pub contracts: Vec<Contract>,
/// We have to keep anchors at this level, since they may link many
/// state transitions under multiple contracts at the same time (via
/// LNPBP-4 multimessage commitments)
pub anchors: Vec<Anchor>,
}
/// With `Stash` we define a simple and uniform interface for all low-level
/// operations that are possible for smart contract management
impl Stash {
/// When we have received data from other peer (which usually relate to our
/// newly owned state, like assets) we do `merge` with the [Consignment], and
/// it gets into the known data.
pub fn merge(&mut self, _consignment: Consignment) {
unimplemented!()
}
/// Now, when we need to send over to somebody else an update (like we have
/// transferred him some state, for instance an asset) for each transfer we
/// ask [Stash] to create a new [Consignment] for the given set of seals
/// under some specific [Genesis] (contract creation genesis)
pub fn consign(&self, _seals: Vec<SealDefinition>, _under: Genesis) -> Consignment {
unimplemented!()
}
/// If we need to forget about the state which is not owned by us anymore
/// (we have done the transfer and would like to prune this specific info
/// we call this function
pub fn forget(&mut self, _consignment: Consignment) {
unimplemented!()
}
/// Clears all data that are not related to the contract state owned by
/// us in this moment — under all known contracts
pub fn prune(&mut self) {
unimplemented!()
}
/// When we need to organize a transfer of some state we use this function.
/// The difference with [consign] is that this function *creates new
/// state transition data and anchors*, when [consign] allows to export a
/// [Consignment] for already existing state transitions and anchors.
/// The workflow is the following:
/// 1. Use [transit] function to create an instance of [CoordinatedTransition]
/// for the selected seals
/// 2. Use [Coordinator] (wallet-provided instance via trait interface)
/// to coordinate different contracts which are related to the given
/// set of seals (see [CoordinatedTransition] implementation below.
/// 3. When you are happy with the new state assignments (i.e. new set of
/// seals that will hold the state) call [CoordinatedTransition::finalize].
/// This will generate required bitcoin transaction(s) that will close
/// given set of seals and commit to a newly defined seals. For building
/// transaction structure [CoordinatedTransition::finalize] will use
/// [TxResolver] (providing blockchain information or LN channel
/// transaction graph) and [TxConductor] for fine-tuning individual
/// parameters of the transaction. This will generate
/// [CoordinatedUpdate] containing information on all generated
/// state transitions, anchors and transaction(s).
/// 4. Call [apply] (next method on [Stash] with the [CoordinatedUpdate];
/// this will change the state of the Stash itself and publish all
/// transactions with [TxResolver] (will work with both on-chain and LN
/// part); after this a new state ownership structure will come in place.
/// The function will produce a [Consignment] which may be discarded;
/// since it will take complete information about all state changes and
/// not only those changes which are related to the state you'd like
/// to share (for instance, if you are transferring some asset and leaving
/// change for yourself + moving other assets under your control which
/// were allocated to the same transaction outputs, this `Consignment`
/// will hold information on both transfer and change).
/// 5. Use [consign] function to create a version of the `Consignment`
/// that will hold only information that is related to the state you'd
/// like to send to some other party; serialize it and send it over
/// the wire protocol.
pub fn transit(&self, _seals: Vec<SealDefinition>) -> CoordinatedTransition {
unimplemented!()
}
pub fn apply(
&mut self,
_update: CoordinatedUpdate,
_resolver: &impl TxResolver,
) -> Consignment {
unimplemented!()
}
}
pub struct CoordinatedTransition {
pub transitions: HashSet<ContractId, Transition>,
pub multi_commits: HashSet<SealDefinition, MultimsgCommitment>,
}
impl CoordinatedTransition {
pub fn coordinate(&mut self, _coordinator: &impl Coordinator) {
unimplemented!()
}
pub fn finalize(
self,
_resolver: &impl TxResolver,
_conductor: &impl TxConductor,
) -> CoordinatedUpdate {
unimplemented!()
}
}
pub struct CoordinatedUpdate {
pub transitions: Vec<Transition>,
pub anchor: Anchor,
pub inner_witness: Transaction,
}
*/
| true
|
a01064badedc9cda72a89eb329902db05e21c258
|
Rust
|
sunng87/tower-web
|
/src/response/context.rs
|
UTF-8
| 1,796
| 3.0625
| 3
|
[
"MIT"
] |
permissive
|
use response::{Serializer, ContentType};
use bytes::Bytes;
use http::header::HeaderValue;
use serde::Serialize;
/// Context available when serializing the response.
#[derive(Debug)]
pub struct Context<'a, S: Serializer + 'a> {
serializer: &'a S,
default_content_type: Option<&'a ContentType<S::Format>>,
}
impl<'a, S> Context<'a, S>
where
S: Serializer,
{
/// Create a new response context.
pub fn new(serializer: &'a S,
default_content_type: Option<&'a ContentType<S::Format>>) -> Context<'a, S>
{
Context {
serializer,
default_content_type,
}
}
/// Serialize a value.
///
/// This uses the default content type for the action.
///
/// # Panics
///
/// Calling this function *requires* a default content type. If set to
/// `None`, this function will panic.
pub fn serialize<T>(&self, value: &T) -> Result<Bytes, ::Error>
where
T: Serialize,
{
let content_type = self.default_content_type
.expect("no default content type associated with action");
match content_type.format() {
Some(format) => self.serializer.serialize(value, format),
None => panic!("no serializer associated with content type `{:?}`", content_type.header()),
}
}
/// Serialize a value as the specified content type.
pub fn serialize_as<T>(&self, _value: &T, _content_type: &str) -> Result<Bytes, ::Error>
where
T: Serialize,
{
unimplemented!();
}
/// Returns a `HeaderValue` representation of the default content type.
pub fn content_type_header(&self) -> Option<&HeaderValue> {
self.default_content_type
.map(|content_type| content_type.header())
}
}
| true
|
d272c81c196848c6c3899da60cbba959493886bf
|
Rust
|
sandmor/moving
|
/src/dpi.rs
|
UTF-8
| 1,150
| 3.203125
| 3
|
[
"MIT"
] |
permissive
|
#[derive(Debug, Copy, Clone, PartialOrd, PartialEq)]
pub struct LogicalSize {
pub w: f64,
pub h: f64,
}
impl LogicalSize {
pub fn width(&self) -> f64 {
self.w
}
pub fn height(&self) -> f64 {
self.h
}
pub fn from_physical(physical: PhysicalSize, dpi: Dpi) -> Self {
Self {
w: physical.w * dpi,
h: physical.h * dpi,
}
}
pub fn to_physical(&self, dpi: Dpi) -> PhysicalSize {
PhysicalSize {
w: self.w / dpi,
h: self.h / dpi,
}
}
}
#[derive(Debug, Copy, Clone, PartialOrd, PartialEq)]
pub struct PhysicalSize {
pub w: f64,
pub h: f64,
}
impl PhysicalSize {
pub fn width(&self) -> f64 {
self.w
}
pub fn height(&self) -> f64 {
self.h
}
pub fn from_logical(logical: LogicalSize, dpi: Dpi) -> Self {
Self {
w: logical.w / dpi,
h: logical.h / dpi,
}
}
pub fn to_logical(&self, dpi: Dpi) -> LogicalSize {
LogicalSize {
w: self.w * dpi,
h: self.h * dpi,
}
}
}
pub type Dpi = f64;
| true
|
f460259a920a8f0cb542fc150d1bcd0b7af2a355
|
Rust
|
songlinshu/win-crypto-ng
|
/src/symmetric.rs
|
UTF-8
| 20,592
| 3.328125
| 3
|
[
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
//! Symmetric encryption algorithms
//!
//! Symmetric encryption algorithms uses the same key (the shared-secret) to encrypt and decrypt the
//! data. It is usually more performant and secure to use this type of encryption than using
//! asymmetric encryption algorithms.
//!
//! # Usage
//!
//! The first step is to create an instance of the algorithm needed. All the block ciphers
//! algorithms supported are defined in the [`SymmetricAlgorithmId`] enum. Since they encrypt per
//! block, a chaining mode is also needed. All the supported chaining modes are defined in the
//! [`ChainingMode`] enum.
//!
//! The creation of an algorithm can be relatively time-intensive. Therefore, it is advised to cache
//! and reuse the created algorithms.
//!
//! Once the algorithm is created, multiple keys can be created. Each key is initialized with a
//! secret of a specific size. To check what key sizes are supported, see
//! [`SymmetricAlgorithm.valid_key_sizes`].
//!
//! With the key in hand, it is then possible to encrypt or decrypt data. Padding is always added
//! to fit a whole block. If the data fits exactly in a block, an extra block of padding is added.
//! When encrypting or decrypting, an initialization vector (IV) may be required.
//!
//! The following example encrypts then decrypts a message using AES with CBC chaining mode:
//! ```
//! use win_crypto_ng::symmetric::{ChainingMode, SymmetricAlgorithm, SymmetricAlgorithmId};
//! use win_crypto_ng::symmetric::Padding;
//!
//! const KEY: &'static str = "0123456789ABCDEF";
//! const IV: &'static str = "asdfqwerasdfqwer";
//! const DATA: &'static str = "This is a test.";
//!
//! let iv = IV.as_bytes().to_owned();
//!
//! let algo = SymmetricAlgorithm::open(SymmetricAlgorithmId::Aes, ChainingMode::Cbc).unwrap();
//! let key = algo.new_key(KEY.as_bytes()).unwrap();
//! let ciphertext = key.encrypt(Some(&mut iv.clone()), DATA.as_bytes(), Some(Padding::Block)).unwrap();
//! let plaintext = key.decrypt(Some(&mut iv.clone()), ciphertext.as_slice(), Some(Padding::Block)).unwrap();
//!
//! assert_eq!(std::str::from_utf8(&plaintext.as_slice()[..DATA.len()]).unwrap(), DATA);
//! ```
//!
//! [`SymmetricAlgorithmId`]: enum.SymmetricAlgorithmId.html
//! [`ChainingMode`]: enum.ChainingMode.html
//! [`SymmetricAlgorithm.valid_key_sizes`]: struct.SymmetricAlgorithm.html#method.valid_key_sizes
use crate::buffer::Buffer;
use crate::helpers::{AlgoHandle, Handle, KeyHandle, WindowsString};
use crate::property::{self, BlockLength, KeyLength, KeyLengths, MessageBlockLength, ObjectLength};
use crate::{Error, Result};
use std::mem::MaybeUninit;
use std::ptr::null_mut;
use winapi::shared::bcrypt::*;
use winapi::shared::minwindef::{PUCHAR, ULONG};
/// Symmetric algorithm identifiers
#[derive(Debug, Clone, Copy, PartialOrd, PartialEq)]
pub enum SymmetricAlgorithmId {
/// The advanced encryption standard symmetric encryption algorithm.
///
/// Standard: FIPS 197.
Aes,
/// The data encryption standard symmetric encryption algorithm.
///
/// Standard: FIPS 46-3, FIPS 81.
Des,
/// The extended data encryption standard symmetric encryption algorithm.
///
/// Standard: None.
DesX,
/// The RC2 block symmetric encryption algorithm.
///
/// Standard: RFC 2268.
Rc2,
// The RC4 symmetric encryption algorithm.
//
// Standard: Various.
//Rc4,
/// The triple data encryption standard symmetric encryption algorithm.
///
/// Standard: SP800-67, SP800-38A.
TripleDes,
/// The 112-bit triple data encryption standard symmetric encryption algorithm.
///
/// Standard: SP800-67, SP800-38A.
TripleDes112,
// The advanced encryption standard symmetric encryption algorithm in XTS mode.
//
// Standard: SP-800-38E, IEEE Std 1619-2007.
//
// **Windows 10**: Support for this algorithm begins.
//XtsAes,
}
impl SymmetricAlgorithmId {
fn to_str(self) -> &'static str {
match self {
Self::Aes => BCRYPT_AES_ALGORITHM,
Self::Des => BCRYPT_DES_ALGORITHM,
Self::DesX => BCRYPT_DESX_ALGORITHM,
Self::Rc2 => BCRYPT_RC2_ALGORITHM,
//Self::Rc4 => BCRYPT_RC4_ALGORITHM,
Self::TripleDes => BCRYPT_3DES_ALGORITHM,
Self::TripleDes112 => BCRYPT_3DES_112_ALGORITHM,
//Self::XtsAes => BCRYPT_XTS_AES_ALGORITHM,
}
}
}
/// Symmetric algorithm chaining modes
#[derive(Debug, Clone, Copy, PartialOrd, PartialEq)]
pub enum ChainingMode {
/// Electronic Codebook
///
/// Standard: SP800-38A
Ecb,
/// Cipher Block Chaining
///
/// Standard: SP800-38A
Cbc,
/// Cipher Feedback
///
/// Standard: SP800-38A
Cfb,
// Counter with CBC. Only available on AES algorithm.
//
// Standard: SP800-38C
//
// **Windows Vista**: This value is supported beginning with Windows Vista with SP1.
//Ccm,
// Galois/Counter Mode. Only available on AES algorithm.
//
// Standard: SP800-38D
//
// **Windows Vista**: This value is supported beginning with Windows Vista with SP1.
//Gcm,
}
impl ChainingMode {
fn to_str(self) -> &'static str {
match self {
Self::Ecb => BCRYPT_CHAIN_MODE_ECB,
Self::Cbc => BCRYPT_CHAIN_MODE_CBC,
Self::Cfb => BCRYPT_CHAIN_MODE_CFB,
//Self::Ccm => BCRYPT_CHAIN_MODE_CCM,
//Self::Gcm => BCRYPT_CHAIN_MODE_GCM,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// Padding to be used together with symmetric algorithms
pub enum Padding {
/// Pad the data to the next block size.
///
/// N.B. Data equal in length to the block size will be padded to the *next*
/// block size.
Block,
}
/// Symmetric algorithm
pub struct SymmetricAlgorithm {
handle: AlgoHandle,
chaining_mode: ChainingMode,
}
impl SymmetricAlgorithm {
/// Open a symmetric algorithm provider
///
/// # Examples
///
/// ```
/// # use win_crypto_ng::symmetric::{ChainingMode, SymmetricAlgorithm, SymmetricAlgorithmId};
/// let algo = SymmetricAlgorithm::open(SymmetricAlgorithmId::Aes, ChainingMode::Cbc);
///
/// assert!(algo.is_ok());
/// ```
pub fn open(id: SymmetricAlgorithmId, chaining_mode: ChainingMode) -> Result<Self> {
let handle = AlgoHandle::open(id.to_str())?;
let value = WindowsString::from(chaining_mode.to_str());
handle.set_property::<property::ChainingMode>(value.as_slice_with_nul())?;
Ok(Self {
handle,
chaining_mode,
})
}
/// Returns the chaining mode of the algorithm.
///
/// # Examples
///
/// ```
/// # use win_crypto_ng::symmetric::{ChainingMode, SymmetricAlgorithm, SymmetricAlgorithmId};
/// let algo = SymmetricAlgorithm::open(SymmetricAlgorithmId::Aes, ChainingMode::Cbc).unwrap();
/// let chaining_mode = algo.chaining_mode();
///
/// assert_eq!(ChainingMode::Cbc, chaining_mode);
/// ```
pub fn chaining_mode(&self) -> ChainingMode {
self.chaining_mode
}
/// Returns a list of all the valid key sizes for an algorithm.
///
/// The key sizes are defined in bits.
///
/// # Examples
///
/// ```
/// # use win_crypto_ng::symmetric::{ChainingMode, SymmetricAlgorithm, SymmetricAlgorithmId};
/// let algo = SymmetricAlgorithm::open(SymmetricAlgorithmId::Aes, ChainingMode::Cbc).unwrap();
/// let valid_key_sizes = algo.valid_key_sizes().unwrap();
///
/// assert_eq!([128, 192, 256], valid_key_sizes.as_slice());
/// ```
pub fn valid_key_sizes(&self) -> Result<Vec<usize>> {
let key_sizes = self.handle.get_property::<KeyLengths>()?;
if key_sizes.dwIncrement != 0 {
Ok(
(key_sizes.dwMinLength as usize..=key_sizes.dwMaxLength as usize)
.step_by(key_sizes.dwIncrement as usize)
.collect(),
)
} else {
Ok(vec![key_sizes.dwMinLength as usize])
}
}
/// Creates a new key from the algorithm
///
/// The secret value is the shared-secret between the two parties.
/// For example, it may be a hash of a password or some other reproducible data.
/// The size of the secret must fit with one of the valid key sizes (see [`valid_key_sizes`]).
///
/// [`valid_key_sizes`]: #method.valid_key_sizes
pub fn new_key(&self, secret: &[u8]) -> Result<SymmetricAlgorithmKey> {
let object_size = self.handle.get_property::<ObjectLength>()?;
let mut key_handle = KeyHandle::new();
let mut object = Buffer::new(object_size as usize);
unsafe {
Error::check(BCryptGenerateSymmetricKey(
self.handle.as_ptr(),
key_handle.as_mut_ptr(),
object.as_mut_ptr(),
object.len() as ULONG,
secret.as_ptr() as PUCHAR,
secret.len() as ULONG,
0,
))
.map(|_| SymmetricAlgorithmKey {
handle: key_handle,
_object: object,
})
}
}
}
/// Symmetric algorithm key
pub struct SymmetricAlgorithmKey {
handle: KeyHandle,
_object: Buffer,
}
impl SymmetricAlgorithmKey {
/// Returns the key value size in bits.
///
/// # Examples
///
/// ```
/// # use win_crypto_ng::symmetric::{ChainingMode, SymmetricAlgorithm, SymmetricAlgorithmId};
/// # let algo = SymmetricAlgorithm::open(SymmetricAlgorithmId::Aes, ChainingMode::Cbc).unwrap();
/// let key = algo.new_key("0123456789ABCDEF".as_bytes()).unwrap();
/// let key_size = key.key_size().unwrap();
///
/// assert_eq!(128, key_size);
/// ```
pub fn key_size(&self) -> Result<usize> {
self.handle
.get_property::<KeyLength>()
.map(|key_size| key_size as usize)
}
/// Returns the block size in bytes.
///
/// This can be useful to find what size the IV should be.
///
/// # Examples
///
/// ```
/// # use win_crypto_ng::symmetric::{ChainingMode, SymmetricAlgorithm, SymmetricAlgorithmId};
/// # let algo = SymmetricAlgorithm::open(SymmetricAlgorithmId::Aes, ChainingMode::Cbc).unwrap();
/// let key = algo.new_key("0123456789ABCDEF".as_bytes()).unwrap();
/// let key_size = key.block_size().unwrap();
///
/// assert_eq!(16, key_size);
/// ```
pub fn block_size(&self) -> Result<usize> {
self.handle
.get_property::<BlockLength>()
.map(|block_size| block_size as usize)
}
/// Sets the message block length.
///
/// This can be set on any key handle that has the CFB chaining mode set. By
/// default, it is set to 1 for 8-bit CFB. Setting it to the block
/// size in bytes causes full-block CFB to be used. For XTS keys it is used to
/// set the size, in bytes, of the XTS Data Unit (commonly 512 or 4096).
///
/// See [here](https://docs.microsoft.com/windows/win32/seccng/cng-property-identifiers#BCRYPT_MESSAGE_BLOCK_LENGTH)
/// for more info.
pub fn set_msg_block_len(&mut self, len: usize) -> Result<()> {
self.handle
.set_property::<MessageBlockLength>(&(len as u32))
}
/// Encrypts data using the symmetric key
///
/// The IV is not needed for [`ChainingMode::Ecb`], so `None` should be used
/// in this case.
///
/// For chaining modes needing an IV, `None` can be used and a default IV will be used.
/// This is not documented on Microsoft's website and is therefore not recommended.
///
/// The data is padded with zeroes to a multiple of the block size of the cipher. If
/// the data length equals the block size of the cipher, one additional block of
/// padding is appended to the data.
///
/// # Examples
///
/// ```
/// # use win_crypto_ng::symmetric::{ChainingMode, SymmetricAlgorithm, SymmetricAlgorithmId};
/// # use win_crypto_ng::symmetric::Padding;
/// # let algo = SymmetricAlgorithm::open(SymmetricAlgorithmId::Aes, ChainingMode::Cbc).unwrap();
/// let key = algo.new_key("0123456789ABCDEF".as_bytes()).unwrap();
/// let mut iv = b"_THIS_IS_THE_IV_".to_vec();
/// let plaintext = "THIS_IS_THE_DATA".as_bytes();
/// let ciphertext = key.encrypt(Some(&mut iv), plaintext, Some(Padding::Block)).unwrap();
///
/// assert_eq!(ciphertext.as_slice(), [
/// 0xE4, 0xD9, 0x90, 0x64, 0xA6, 0xA6, 0x5F, 0x7E,
/// 0x70, 0xDB, 0xF9, 0xDD, 0xE7, 0x0D, 0x6F, 0x6A,
/// 0x0C, 0xEC, 0xDB, 0xAD, 0x01, 0xB4, 0xB1, 0xDE,
/// 0xB4, 0x4A, 0xB8, 0xA0, 0xEA, 0x0E, 0x8F, 0x31]);
/// ```
pub fn encrypt(
&self,
iv: Option<&mut [u8]>,
data: &[u8],
padding: Option<Padding>,
) -> Result<Buffer> {
let (iv_ptr, iv_len) = iv
.map(|iv| (iv.as_mut_ptr(), iv.len() as ULONG))
.unwrap_or((null_mut(), 0));
let flags = match padding {
Some(Padding::Block) => BCRYPT_BLOCK_PADDING,
_ => 0,
};
let mut encrypted_len = MaybeUninit::<ULONG>::uninit();
unsafe {
Error::check(BCryptEncrypt(
self.handle.as_ptr(),
data.as_ptr() as PUCHAR,
data.len() as ULONG,
null_mut(),
iv_ptr,
iv_len,
null_mut(),
0,
encrypted_len.as_mut_ptr(),
flags,
))?;
let mut output = Buffer::new(encrypted_len.assume_init() as usize);
Error::check(BCryptEncrypt(
self.handle.as_ptr(),
data.as_ptr() as PUCHAR,
data.len() as ULONG,
null_mut(),
iv_ptr,
iv_len,
output.as_mut_ptr(),
output.len() as ULONG,
encrypted_len.as_mut_ptr(),
flags,
))
.map(|_| output)
}
}
/// Decrypts data using the symmetric key
///
/// The IV is not needed for [`ChainingMode::Ecb`], so `None` should be used
/// in this case.
///
/// For chaining modes needing an IV, `None` can be used and a default IV will be used.
/// This is not documented on Microsoft's website and is therefore not recommended.
///
/// # Examples
///
/// ```
/// # use win_crypto_ng::symmetric::{ChainingMode, SymmetricAlgorithm, SymmetricAlgorithmId};
/// # use win_crypto_ng::symmetric::Padding;
/// # let algo = SymmetricAlgorithm::open(SymmetricAlgorithmId::Aes, ChainingMode::Cbc).unwrap();
/// let key = algo.new_key("0123456789ABCDEF".as_bytes()).unwrap();
/// let mut iv = b"_THIS_IS_THE_IV_".to_vec();
/// let ciphertext = [
/// 0xE4, 0xD9, 0x90, 0x64, 0xA6, 0xA6, 0x5F, 0x7E,
/// 0x70, 0xDB, 0xF9, 0xDD, 0xE7, 0x0D, 0x6F, 0x6A,
/// 0x0C, 0xEC, 0xDB, 0xAD, 0x01, 0xB4, 0xB1, 0xDE,
/// 0xB4, 0x4A, 0xB8, 0xA0, 0xEA, 0x0E, 0x8F, 0x31
/// ];
/// let plaintext = key.decrypt(Some(&mut iv), &ciphertext, Some(Padding::Block)).unwrap();
///
/// assert_eq!(&plaintext.as_slice()[..16], "THIS_IS_THE_DATA".as_bytes());
/// ```
pub fn decrypt(
&self,
iv: Option<&mut [u8]>,
data: &[u8],
padding: Option<Padding>,
) -> Result<Buffer> {
let (iv_ptr, iv_len) = iv
.map(|iv| (iv.as_mut_ptr(), iv.len() as ULONG))
.unwrap_or((null_mut(), 0));
let flags = match padding {
Some(Padding::Block) => BCRYPT_BLOCK_PADDING,
_ => 0,
};
let mut plaintext_len = MaybeUninit::<ULONG>::uninit();
unsafe {
Error::check(BCryptDecrypt(
self.handle.as_ptr(),
data.as_ptr() as PUCHAR,
data.len() as ULONG,
null_mut(),
iv_ptr,
iv_len,
null_mut(),
0,
plaintext_len.as_mut_ptr(),
flags,
))?;
let mut output = Buffer::new(plaintext_len.assume_init() as usize);
Error::check(BCryptDecrypt(
self.handle.as_ptr(),
data.as_ptr() as PUCHAR,
data.len() as ULONG,
null_mut(),
iv_ptr,
iv_len,
output.as_mut_ptr(),
output.len() as ULONG,
plaintext_len.as_mut_ptr(),
flags,
))
.map(|_| output)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
const SECRET: &'static str = "0123456789ABCDEF0123456789ABCDEF";
const IV: &'static str = "0123456789ABCDEF0123456789ABCDEF";
const DATA: &'static str = "0123456789ABCDEF0123456789ABCDEF";
#[test]
fn aes() {
check_common_chaining_modes(SymmetricAlgorithmId::Aes, 16, 16);
check_common_chaining_modes(SymmetricAlgorithmId::Aes, 24, 16);
check_common_chaining_modes(SymmetricAlgorithmId::Aes, 32, 16);
}
#[test]
fn des() {
check_common_chaining_modes(SymmetricAlgorithmId::Des, 8, 8);
}
#[test]
fn des_x() {
check_common_chaining_modes(SymmetricAlgorithmId::DesX, 24, 8);
}
#[test]
fn rc2() {
check_common_chaining_modes(SymmetricAlgorithmId::Rc2, 2, 8);
check_common_chaining_modes(SymmetricAlgorithmId::Rc2, 3, 8);
check_common_chaining_modes(SymmetricAlgorithmId::Rc2, 4, 8);
check_common_chaining_modes(SymmetricAlgorithmId::Rc2, 5, 8);
check_common_chaining_modes(SymmetricAlgorithmId::Rc2, 6, 8);
check_common_chaining_modes(SymmetricAlgorithmId::Rc2, 7, 8);
check_common_chaining_modes(SymmetricAlgorithmId::Rc2, 8, 8);
check_common_chaining_modes(SymmetricAlgorithmId::Rc2, 9, 8);
check_common_chaining_modes(SymmetricAlgorithmId::Rc2, 10, 8);
check_common_chaining_modes(SymmetricAlgorithmId::Rc2, 11, 8);
check_common_chaining_modes(SymmetricAlgorithmId::Rc2, 12, 8);
check_common_chaining_modes(SymmetricAlgorithmId::Rc2, 13, 8);
check_common_chaining_modes(SymmetricAlgorithmId::Rc2, 14, 8);
check_common_chaining_modes(SymmetricAlgorithmId::Rc2, 15, 8);
check_common_chaining_modes(SymmetricAlgorithmId::Rc2, 16, 8);
}
#[test]
fn triple_des() {
check_common_chaining_modes(SymmetricAlgorithmId::TripleDes, 24, 8);
}
#[test]
fn triple_des_112() {
check_common_chaining_modes(SymmetricAlgorithmId::TripleDes112, 16, 8);
}
fn check_common_chaining_modes(
algo_id: SymmetricAlgorithmId,
key_size: usize,
block_size: usize,
) {
check_encryption_decryption(
algo_id,
ChainingMode::Ecb,
&SECRET.as_bytes()[..key_size],
None,
&DATA.as_bytes()[..block_size],
block_size,
);
check_encryption_decryption(
algo_id,
ChainingMode::Cbc,
&SECRET.as_bytes()[..key_size],
Some(IV.as_bytes()[..block_size].to_vec().as_mut()),
&DATA.as_bytes(),
block_size,
);
check_encryption_decryption(
algo_id,
ChainingMode::Cfb,
&SECRET.as_bytes()[..key_size],
Some(IV.as_bytes()[..block_size].to_vec().as_mut()),
&DATA.as_bytes(),
block_size,
);
}
fn check_encryption_decryption(
algo_id: SymmetricAlgorithmId,
chaining_mode: ChainingMode,
secret: &[u8],
iv: Option<&mut [u8]>,
data: &[u8],
expected_block_size: usize,
) {
let iv_cloned = || iv.as_ref().map(|x| x.to_vec());
let algo = SymmetricAlgorithm::open(algo_id, chaining_mode).unwrap();
let key = algo.new_key(secret).unwrap();
let ciphertext = key
.encrypt(iv_cloned().as_mut().map(|x| x.as_mut()), data, None)
.unwrap();
let plaintext = key
.decrypt(
iv_cloned().as_mut().map(|x| x.as_mut()),
ciphertext.as_slice(),
None,
)
.unwrap();
assert_eq!(data, &plaintext.as_slice()[..data.len()]);
assert_eq!(secret.len() * 8, key.key_size().unwrap());
assert_eq!(expected_block_size, key.block_size().unwrap());
}
}
| true
|
50f48d49448a13081acc3f339d6206cda4dfe035
|
Rust
|
slerpyyy/ndi-rs
|
/ndi/src/send.rs
|
UTF-8
| 8,969
| 3.28125
| 3
|
[
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
use super::*;
use std::{convert::TryFrom, ffi::CString, mem::MaybeUninit};
/// Builder struct for [`Send`]
#[derive(Debug, Clone)]
pub struct SendBuilder {
ndi_name: Option<String>,
groups: Option<String>,
clock_video: Option<bool>,
clock_audio: Option<bool>,
}
impl SendBuilder {
/// Create new builder instance
pub fn new() -> Self {
Self {
ndi_name: None,
groups: None,
clock_video: None,
clock_audio: None,
}
}
/// This is the name of the NDI source to create.
///
/// This will be the name of the NDI source on the network.
/// For instance, if your network machine name is called “MyMachine” and you
/// specify this parameter as “My Video”, the NDI source on the network would be “MyMachine (My Video)”.
pub fn ndi_name(mut self, ndi_name: String) -> Self {
self.ndi_name = Some(ndi_name);
self
}
/// Specify the groups that this NDI sender should place itself into.
///
/// Groups are sets of NDI sources. Any source can be part of any
/// number of groups, and groups are comma-separated. For instance
/// "cameras,studio 1,10am show" would place a source in the three groups named.
pub fn groups(mut self, groups: String) -> Self {
self.groups = Some(groups);
self
}
/// Specify whether video "clock" themself.
///
/// When it is clocked, video frames added will be rate-limited to
/// match the current framerate they are submitted at.
/// In general, if you are submitting video and audio off a single thread you should only clock one of them
/// If you are submitting audio and video of separate threads then having both clocked can be useful.
/// A simplified view of the how works is that, when you submit a frame, it will
/// keep track of the time the next frame would be required at. If you submit a
/// frame before this time, the call will wait until that time. This ensures that, if
/// you sit in a tight loop and render frames as fast as you can go, they will be
/// clocked at the framerate that you desire.
///
/// Note that combining clocked video and audio submission combined with
/// asynchronous frame submission (see below) allows you to write very simple
/// loops to render and submit NDI frames.
pub fn clock_video(mut self, clock_video: bool) -> Self {
self.clock_video = Some(clock_video);
self
}
/// specify whether audio "clock" themself.
///
/// See above in `clock_video`
pub fn clock_audio(mut self, clock_audio: bool) -> Self {
self.clock_audio = Some(clock_audio);
self
}
/// Build the [`Send`] instance
pub fn build(self) -> Result<Send, SendCreateError> {
let mut settings = NDIlib_send_create_t {
p_ndi_name: null(),
p_groups: null(),
clock_video: true,
clock_audio: true,
};
if let Some(ndi_name) = self.ndi_name {
let cstr = CString::new(ndi_name).unwrap();
settings.p_ndi_name = cstr.as_ptr();
}
if let Some(groups) = self.groups {
let cstr = CString::new(groups).unwrap();
settings.p_groups = cstr.as_ptr();
}
if let Some(clock_video) = self.clock_video {
settings.clock_video = clock_video;
}
if let Some(clock_audio) = self.clock_audio {
settings.clock_audio = clock_audio;
}
Send::with_settings(settings)
}
}
/// A sender struct for sending NDI
pub struct Send {
p_instance: Arc<OnDrop<NDIlib_send_instance_t>>,
}
impl Send {
/// Create a new instance with default parameters
///
/// It is recommended to use [`SendBuilder`] instead
pub fn new() -> Result<Self, SendCreateError> {
let p_instance = unsafe { lib_unwrap!().NDIlib_send_create(null()) };
if p_instance.is_null() {
return Err(SendCreateError);
}
Ok(Self {
p_instance: Arc::new(OnDrop::new(p_instance, |s| unsafe {
lib_unwrap!().NDIlib_send_destroy(s)
})),
})
}
fn with_settings(settings: NDIlib_send_create_t) -> Result<Self, SendCreateError> {
let p_instance = unsafe { lib_unwrap!().NDIlib_send_create(&settings) };
if p_instance.is_null() {
return Err(SendCreateError);
}
Ok(Self {
p_instance: Arc::new(OnDrop::new(p_instance, |s| unsafe {
lib_unwrap!().NDIlib_send_destroy(s)
})),
})
}
/// Get the current tally
///
/// the return value is whether Tally was actually updated or not
pub fn get_tally(&self, tally: &mut Tally, timeout_ms: u32) -> bool {
unsafe {
let p_tally = *tally;
let is_updated = lib_unwrap!().NDIlib_send_get_tally(
**self.p_instance,
&mut p_tally.into(),
timeout_ms,
);
is_updated
}
}
/// This allows you to receive metadata from the other end of the connection
pub fn capture(&self, meta_data: &mut Option<MetaData>, timeout_ms: u32) -> FrameType {
unsafe {
let mut p_meta = if let Some(metadata) = meta_data {
MaybeUninit::new(metadata.p_instance)
} else {
MaybeUninit::uninit()
};
let frametype = lib_unwrap!().NDIlib_send_capture(
**self.p_instance,
p_meta.as_mut_ptr(),
timeout_ms,
);
*meta_data = Some(MetaData::from_binding_send(
Arc::clone(&self.p_instance),
p_meta.assume_init(),
));
let res: FrameType = FrameType::try_from(frametype).unwrap();
res
}
}
/// Retrieve the source information for the given sender instance.
pub fn get_source(&self) -> Source {
let instance = unsafe { *lib_unwrap!().NDIlib_send_get_source_name(**self.p_instance) };
let parent = SourceParent::Send(Arc::clone(&self.p_instance));
Source::from_binding(parent, instance)
}
/// This will add a metadata frame
pub fn send_metadata(&self, metadata: &MetaData) {
unsafe {
lib_unwrap!().NDIlib_send_send_metadata(**self.p_instance, &metadata.p_instance);
}
}
/// This will add an audio frame
pub fn send_audio(&self, audio_data: &AudioData) {
unsafe {
lib_unwrap!().NDIlib_send_send_audio_v3(**self.p_instance, &audio_data.p_instance);
}
}
/// This will add a video frame
pub fn send_video(&self, video_data: &VideoData) {
unsafe {
lib_unwrap!().NDIlib_send_send_video_v2(**self.p_instance, &video_data.p_instance);
}
}
/// This will add a video frame and will return immediately, having scheduled the frame to be displayed.
///
/// All processing and sending of the video will occur asynchronously. The memory accessed by NDIlib_video_frame_t
/// cannot be freed or re-used by the caller until a synchronizing event has occurred. In general the API is better
/// able to take advantage of asynchronous processing than you might be able to by simple having a separate thread
/// to submit frames.
///
/// This call is particularly beneficial when processing BGRA video since it allows any color conversion, compression
/// and network sending to all be done on separate threads from your main rendering thread.
///
/// Synchronizing events are :
/// - a call to `send_video`
/// - a call to `send_video_async` with another frame to be sent
/// - a call to `send_video` with p_video_data=NULL
/// - Dropping a [`Send`] instance
pub fn send_video_async(&self, video_data: &VideoData) {
unsafe {
lib_unwrap!()
.NDIlib_send_send_video_async_v2(**self.p_instance, &video_data.p_instance);
}
}
/// Get the current number of receivers connected to this source.
///
/// This can be used to avoid even rendering when nothing is connected to the video source.
/// which can significantly improve the efficiency if you want to make a lot of sources available on the network.
/// If you specify a timeout that is not 0 then it will wait until there are connections for this amount of time.
pub fn get_no_connections(&self, timeout_ms: u32) -> u32 {
unsafe { lib_unwrap!().NDIlib_send_get_no_connections(**self.p_instance, timeout_ms) as _ }
}
// Free the buffers returned by capture for metadata
// pub(crate) fn free_metadata(&self, metadata: &mut MetaData) {
// unsafe {
// NDIlib_send_free_metadata(*self.p_instance, &metadata.p_instance);
// }
// }
}
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.