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 |
---|---|---|---|---|---|---|---|---|---|---|---|
845317caa7ca70f8b4ce7f26344357ff540d5cfa
|
Rust
|
rust-lang/rust
|
/tests/rustdoc/check-source-code-urls-to-def-std.rs
|
UTF-8
| 1,123 | 2.640625 | 3 |
[
"Apache-2.0",
"LLVM-exception",
"NCSA",
"BSD-2-Clause",
"LicenseRef-scancode-unicode",
"MIT",
"LicenseRef-scancode-other-permissive"
] |
permissive
|
// compile-flags: -Zunstable-options --generate-link-to-definition
#![crate_name = "foo"]
// @has 'src/foo/check-source-code-urls-to-def-std.rs.html'
fn babar() {}
// @has - '//a[@href="{{channel}}/std/primitive.u32.html"]' 'u32'
// @has - '//a[@href="{{channel}}/std/primitive.str.html"]' 'str'
// @has - '//a[@href="{{channel}}/std/primitive.bool.html"]' 'bool'
// @has - '//a[@href="#7"]' 'babar'
pub fn foo(a: u32, b: &str, c: String) {
let x = 12;
let y: bool = true;
babar();
}
macro_rules! yolo { () => {}}
fn bar(a: i32) {}
macro_rules! bar {
($a:ident) => { bar($a) }
}
macro_rules! data {
($x:expr) => { $x * 2 }
}
pub fn another_foo() {
// This is known limitation: if the macro doesn't generate anything, the visitor
// can't find any item or anything that could tell us that it comes from expansion.
// @!has - '//a[@href="#19"]' 'yolo!'
yolo!();
// @has - '//a[@href="{{channel}}/std/macro.eprintln.html"]' 'eprintln!'
eprintln!();
// @has - '//a[@href="#27-29"]' 'data!'
let x = data!(4);
// @has - '//a[@href="#23-25"]' 'bar!'
bar!(x);
}
| true |
0516474a9c1e93f7ec958194e8292ec71812fd48
|
Rust
|
gemarcano/libtock-rs
|
/core/platform/src/syscalls.rs
|
UTF-8
| 933 | 2.578125 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"Apache-2.0"
] |
permissive
|
// TODO: Implement `libtock_runtime` and `libtock_unittest`, which are
// referenced in the comment on `Syscalls`.
/// `Syscalls` provides safe abstractions over Tock's system calls. It is
/// implemented for `libtock_runtime::TockSyscalls` and
/// `libtock_unittest::FakeSyscalls` (by way of `RawSyscalls`).
pub trait Syscalls {
/// Puts the process to sleep until a callback becomes pending, invokes the
/// callback, then returns.
fn yield_wait();
/// Runs the next pending callback, if a callback is pending. Unlike
/// `yield_wait`, `yield_no_wait` returns immediately if no callback is
/// pending. Returns true if a callback was executed, false otherwise.
fn yield_no_wait() -> bool;
// TODO: Add a subscribe interface.
// TODO: Add a command interface.
// TODO: Add a read-write allow interface.
// TODO: Add a read-only allow interface.
// TODO: Add memop() methods.
}
| true |
0e2b2b17496ff2fe0db3c55f0b25e35e0c9fd0be
|
Rust
|
karjonas/advent-of-code
|
/2021/day24/src/lib.rs
|
UTF-8
| 2,482 | 2.8125 | 3 |
[] |
no_license
|
extern crate common;
#[macro_use]
extern crate scan_fmt;
use std::collections::HashMap;
use std::collections::HashSet;
use std::collections::VecDeque;
fn parse_input(input: &String) -> Vec<(i64, i64, i64)> {
let mut result = Vec::new();
let mut x = 0;
let mut y;
let mut z = 0;
let mut read_x = false;
let mut read_y = false;
let mut read_z = false;
for line in input.lines() {
if read_z {
let z_scan = scan_fmt!(line, "div z {d}", i64).unwrap();
z = z_scan;
read_z = false;
read_x = true;
} else if read_x {
let x_scan = scan_fmt!(line, "add x {d}", i64).unwrap();
x = x_scan;
read_x = false;
} else if read_y {
let y_scan = scan_fmt!(line, "add y {d}", i64).unwrap();
y = y_scan;
read_y = false;
result.push((x, y, z));
}
if line == "mod x 26" {
read_z = true;
} else if line == "add y w" {
read_y = true;
}
}
assert_eq!(result.len(), 14);
return result;
}
fn backward(a: i64, b: i64, c: i64, z_goal: i64, w: i64) -> Vec<i64> {
let mut zs = Vec::new();
let x = z_goal - w - b;
if x % 26 == 0 {
zs.push(x / 26 * c);
}
if 0 <= (w - a) && (w - a) < 26 {
let z0 = z_goal * c;
zs.push(w - a + z0);
}
return zs;
}
fn solve_internal(part_two: bool, xyzs: &Vec<(i64, i64, i64)>) -> usize {
let mut zs = HashSet::from([0]);
let mut result = HashMap::<i64, VecDeque<i64>>::new();
for &(a, b, c) in xyzs.iter().rev() {
let mut newzs = HashSet::new();
for w_i in 1..10 {
let w = if part_two { 10 - w_i } else { w_i };
for &z in &zs {
let z0s = backward(a, b, c, z, w);
for z0 in z0s {
newzs.insert(z0);
let mut rz = result.entry(z).or_insert(VecDeque::new()).clone();
rz.insert(0, w);
result.insert(z0, rz);
}
}
}
zs = newzs;
}
return result
.get(&0)
.unwrap()
.iter()
.fold(0, |sum, &v| sum * 10 + v) as usize;
}
pub fn solve() {
let input = parse_input(&common::read_file("2021/day24/input"));
println!("Part one: {}", solve_internal(false, &input));
println!("Part two: {}", solve_internal(true, &input));
}
| true |
5003963ac8a296456da24ce26eba2bee0abf4482
|
Rust
|
theotherphil/kaleidoscope
|
/src/main.rs
|
UTF-8
| 295 | 3.296875 | 3 |
[] |
no_license
|
pub mod lexer;
pub use crate::lexer::*;
// def plus(x, y)
// x + y
//
// plus (1 2)
//
// extern sin(x);
//
// sin(1)
fn main() {
let program = "
# Comment line
plus(1 2) # another comment
";
let tokens = tokenize(program);
println!("TOKENS");
println!("{:#?}", tokens);
}
| true |
9d7a0d1042fe6920293492bf25c421f5441d0918
|
Rust
|
Suppr/Logitech-Led-Profile-Manager
|
/src/keyboard/layout.rs
|
UTF-8
| 37,016 | 2.59375 | 3 |
[] |
no_license
|
use std::collections::hash_map::HashMap;
use serde::{Deserialize, Serialize};
pub type KeysDB = HashMap<Key, klogi::model::Keydata>;
pub type KeydataType = (Key, klogi::model::Keydata);
//keyboard bit map representation
#[repr(C)]
#[derive(Clone, Serialize, Deserialize, Copy, Hash, Debug, PartialEq, Eq, PartialOrd, Ord)]
#[allow(non_camel_case_types, non_snake_case)]
pub enum Key {
ESC = 0,
F1 = 1,
F2 = 2,
F3 = 3,
F4 = 4,
F5 = 5,
F6 = 6,
F7 = 7,
F8 = 8,
F9 = 9,
F10 = 10,
F11 = 11,
F12 = 12,
PRINT_SCREEN = 13,
SCROLL_LOCK = 14,
PAUSE_BREAK = 15,
TILDE = 21,
ONE = 22,
TWO = 23,
THREE = 24,
FOUR = 25,
FIVE = 26,
SIX = 27,
SEVEN = 28,
EIGHT = 29,
NINE = 30,
ZERO = 31,
MINUS = 32,
EQUALS = 33,
BACKSPACE = 34,
INSERT = 35,
HOME = 36,
PAGE_UP = 37,
NUM_LOCK = 38,
NUM_SLASH = 39,
NUM_ASTERISK = 40,
NUM_MINUS = 41,
TAB = 42,
Q = 43,
W = 44,
E = 45,
R = 46,
T = 47,
Y = 48,
U = 49,
I = 50,
O = 51,
P = 52,
OPEN_BRACKET = 53,
CLOSE_BRACKET = 54,
//BACKSLASH = 55,
KEYBOARD_DELETE = 56,
END = 57,
PAGE_DOWN = 58,
NUM_SEVEN = 59,
NUM_EIGHT = 60,
NUM_NINE = 61,
NUM_PLUS = 62,
CAPS_LOCK = 63,
A = 64,
S = 65,
D = 66,
F = 67,
G = 68,
H = 69,
J = 70,
K = 71,
L = 72,
SEMICOLON = 73,
APOSTROPHE = 74,
NON_US_ASTERISK = 75,
ENTER = 76,
NUM_FOUR = 80,
NUM_FIVE = 81,
NUM_SIX = 82,
LEFT_SHIFT = 84,
NON_US_SLASH = 85,
Z = 86,
X = 87,
C = 88,
V = 89,
B = 90,
N = 91,
M = 92,
COMMA = 93,
PERIOD = 94,
FORWARD_SLASH = 95,
RIGHT_SHIFT = 97,
ARROW_UP = 99,
NUM_ONE = 101,
NUM_TWO = 102,
NUM_THREE = 103,
NUM_ENTER = 104,
LEFT_CONTROL = 105,
LEFT_WINDOWS = 106,
LEFT_ALT = 107,
SPACE = 110,
RIGHT_ALT = 116,
RIGHT_WINDOWS = 117,
APPLICATION_SELECT = 118,
RIGHT_CONTROL = 119,
ARROW_LEFT = 120,
ARROW_DOWN = 121,
ARROW_RIGHT = 122,
NUM_ZERO = 123,
NUM_PERIOD = 124,
G_1,
G_2,
G_3,
G_4,
G_5,
G_6,
G_7,
G_8,
G_9,
G_LOGO,
G_BADGE,
}
impl Key {
fn from_str(string: &str) -> Option<Key> {
let res = match string {
"ESC" => Key::ESC,
"F1" => Key::F1,
"F2" => Key::F2,
"F3" => Key::F3,
"F4" => Key::F4,
"F5" => Key::F5,
"F6" => Key::F6,
"F7" => Key::F7,
"F8" => Key::F8,
"F9" => Key::F9,
"F10" => Key::F10,
"F11" => Key::F11,
"F12" => Key::F12,
"PRINT_SCREEN" => Key::PRINT_SCREEN,
"SCROLL_LOCK" => Key::SCROLL_LOCK,
"PAUSE_BREAK" => Key::PAUSE_BREAK,
"TILDE" => Key::TILDE,
"ONE" => Key::ONE,
"TWO" => Key::TWO,
"THREE" => Key::THREE,
"FOUR" => Key::FOUR,
"FIVE" => Key::FIVE,
"SIX" => Key::SIX,
"SEVEN" => Key::SEVEN,
"EIGHT" => Key::EIGHT,
"NINE" => Key::NINE,
"ZERO" => Key::ZERO,
"MINUS" => Key::MINUS,
"EQUALS" => Key::EQUALS,
"BACKSPACE" => Key::BACKSPACE,
"INSERT" => Key::INSERT,
"HOME" => Key::HOME,
"PAGE_UP" => Key::PAGE_UP,
"NUM_LOCK" => Key::NUM_LOCK,
"NUM_SLASH" => Key::NUM_SLASH,
"NUM_ASTERISK" => Key::NUM_ASTERISK,
"NUM_MINUS" => Key::NUM_MINUS,
"TAB" => Key::TAB,
"Q" => Key::Q,
"W" => Key::W,
"E" => Key::E,
"R" => Key::R,
"T" => Key::T,
"Y" => Key::Y,
"U" => Key::U,
"I" => Key::I,
"O" => Key::O,
"P" => Key::P,
"OPEN_BRACKET" => Key::OPEN_BRACKET,
"CLOSE_BRACKET" => Key::CLOSE_BRACKET,
//"BACKSLASH" => Key::BACKSLASH,
"KEYBOARD_DELETE" => Key::KEYBOARD_DELETE,
"END" => Key::END,
"PAGE_DOWN" => Key::PAGE_DOWN,
"NUM_SEVEN" => Key::NUM_SEVEN,
"NUM_EIGHT" => Key::NUM_EIGHT,
"NUM_NINE" => Key::NUM_NINE,
"NUM_PLUS" => Key::NUM_PLUS,
"CAPS_LOCK" => Key::CAPS_LOCK,
"A" => Key::A,
"S" => Key::S,
"D" => Key::D,
"F" => Key::F,
"G" => Key::G,
"H" => Key::H,
"J" => Key::J,
"K" => Key::K,
"L" => Key::L,
"SEMICOLON" => Key::SEMICOLON,
"APOSTROPHE" => Key::APOSTROPHE,
"NON_US_ASTERISK" => Key::NON_US_ASTERISK,
"ENTER" => Key::ENTER,
"NUM_FOUR" => Key::NUM_FOUR,
"NUM_FIVE" => Key::NUM_FIVE,
"NUM_SIX" => Key::NUM_SIX,
"LEFT_SHIFT" => Key::LEFT_SHIFT,
"NON_US_SLASH" => Key::NON_US_SLASH,
"Z" => Key::Z,
"X" => Key::X,
"C" => Key::C,
"V" => Key::V,
"B" => Key::B,
"N" => Key::N,
"M" => Key::M,
"COMMA" => Key::COMMA,
"PERIOD" => Key::PERIOD,
"FORWARD_SLASH" => Key::FORWARD_SLASH,
"RIGHT_SHIFT" => Key::RIGHT_SHIFT,
"ARROW_UP" => Key::ARROW_UP,
"NUM_ONE" => Key::NUM_ONE,
"NUM_TWO" => Key::NUM_TWO,
"NUM_THREE" => Key::NUM_THREE,
"NUM_ENTER" => Key::NUM_ENTER,
"LEFT_CONTROL" => Key::LEFT_CONTROL,
"LEFT_WINDOWS" => Key::LEFT_WINDOWS,
"LEFT_ALT" => Key::LEFT_ALT,
"SPACE" => Key::SPACE,
"RIGHT_ALT" => Key::RIGHT_ALT,
"RIGHT_WINDOWS" => Key::RIGHT_WINDOWS,
"APPLICATION_SELECT" => Key::APPLICATION_SELECT,
"RIGHT_CONTROL" => Key::RIGHT_CONTROL,
"ARROW_LEFT" => Key::ARROW_LEFT,
"ARROW_DOWN" => Key::ARROW_DOWN,
"ARROW_RIGHT" => Key::ARROW_RIGHT,
"NUM_ZERO" => Key::NUM_ZERO,
"NUM_PERIOD" => Key::NUM_PERIOD,
"G1" => Key::G_1,
"G2" => Key::G_2,
"G3" => Key::G_3,
"G4" => Key::G_4,
"G5" => Key::G_5,
"G6" => Key::G_6,
"G7" => Key::G_7,
"G8" => Key::G_8,
"G9" => Key::G_9,
"Logo" => Key::G_LOGO,
"Badge" => Key::G_BADGE,
_ => return None,
};
Some(res)
}
pub fn allkeys() -> Vec<Key> {
vec![
Key::ESC,
Key::F1,
Key::F2,
Key::F3,
Key::F4,
Key::F5,
Key::F6,
Key::F7,
Key::F8,
Key::F9,
Key::F10,
Key::F11,
Key::F12,
Key::PRINT_SCREEN,
Key::SCROLL_LOCK,
Key::PAUSE_BREAK,
Key::TILDE,
Key::ONE,
Key::TWO,
Key::THREE,
Key::FOUR,
Key::FIVE,
Key::SIX,
Key::SEVEN,
Key::EIGHT,
Key::NINE,
Key::ZERO,
Key::MINUS,
Key::EQUALS,
Key::BACKSPACE,
Key::INSERT,
Key::HOME,
Key::PAGE_UP,
Key::NUM_LOCK,
Key::NUM_SLASH,
Key::NUM_ASTERISK,
Key::NUM_MINUS,
Key::TAB,
Key::Q,
Key::W,
Key::E,
Key::R,
Key::T,
Key::Y,
Key::U,
Key::I,
Key::O,
Key::P,
Key::OPEN_BRACKET,
Key::CLOSE_BRACKET,
//Key::BACKSLASH,
Key::KEYBOARD_DELETE,
Key::END,
Key::PAGE_DOWN,
Key::NUM_SEVEN,
Key::NUM_EIGHT,
Key::NUM_NINE,
Key::NUM_PLUS,
Key::CAPS_LOCK,
Key::A,
Key::S,
Key::D,
Key::F,
Key::G,
Key::H,
Key::J,
Key::K,
Key::L,
Key::SEMICOLON,
Key::APOSTROPHE,
Key::NON_US_ASTERISK,
Key::ENTER,
Key::NUM_FOUR,
Key::NUM_FIVE,
Key::NUM_SIX,
Key::LEFT_SHIFT,
Key::NON_US_SLASH,
Key::Z,
Key::X,
Key::C,
Key::V,
Key::B,
Key::N,
Key::M,
Key::COMMA,
Key::PERIOD,
Key::FORWARD_SLASH,
Key::RIGHT_SHIFT,
Key::ARROW_UP,
Key::NUM_ONE,
Key::NUM_TWO,
Key::NUM_THREE,
Key::NUM_ENTER,
Key::LEFT_CONTROL,
Key::LEFT_WINDOWS,
Key::LEFT_ALT,
Key::SPACE,
Key::RIGHT_ALT,
Key::RIGHT_WINDOWS,
Key::APPLICATION_SELECT,
Key::RIGHT_CONTROL,
Key::ARROW_LEFT,
Key::ARROW_DOWN,
Key::ARROW_RIGHT,
Key::NUM_ZERO,
Key::NUM_PERIOD,
Key::G_1,
Key::G_2,
Key::G_3,
Key::G_4,
Key::G_5,
Key::G_6,
Key::G_7,
Key::G_8,
Key::G_9,
Key::G_LOGO,
Key::G_BADGE,
]
}
pub fn firstline() -> Vec<Key> {vec![
Key::G_LOGO,
Key::ESC,
Key::F1,
Key::F2,
Key::F3,
Key::F4,
Key::F5,
Key::F6,
Key::F7,
Key::F8,
Key::F9,
Key::F10,
Key::F11,
Key::F12,
Key::PRINT_SCREEN,
Key::SCROLL_LOCK,
Key::PAUSE_BREAK,
]}
pub fn secondline() -> Vec<Key> {vec![
Key::G_1,
Key::TILDE,
Key::ONE,
Key::TWO,
Key::THREE,
Key::FOUR,
Key::FIVE,
Key::SIX,
Key::SEVEN,
Key::EIGHT,
Key::NINE,
Key::ZERO,
Key::MINUS,
Key::EQUALS,
Key::BACKSPACE,
Key::INSERT,
Key::HOME,
Key::PAGE_UP,
Key::NUM_LOCK,
Key::NUM_SLASH,
Key::NUM_ASTERISK,
Key::NUM_MINUS,
]}
pub fn thirdline() -> Vec<Key> {vec![
Key::G_2,
Key::TAB,
Key::Q,
Key::W,
Key::E,
Key::R,
Key::T,
Key::Y,
Key::U,
Key::I,
Key::O,
Key::P,
Key::OPEN_BRACKET,
Key::CLOSE_BRACKET,
//Key::BACKSLASH,
Key::ENTER,
Key::KEYBOARD_DELETE,
Key::END,
Key::PAGE_DOWN,
Key::NUM_SEVEN,
Key::NUM_EIGHT,
Key::NUM_NINE,
Key::NUM_PLUS,
]}
pub fn fourthline() -> Vec<Key> {vec![
Key::G_3,
Key::CAPS_LOCK,
Key::A,
Key::S,
Key::D,
Key::F,
Key::G,
Key::H,
Key::J,
Key::K,
Key::L,
Key::SEMICOLON,
Key::APOSTROPHE,
Key::NON_US_ASTERISK,
Key::ENTER,
Key::NUM_FOUR,
Key::NUM_FIVE,
Key::NUM_SIX,
Key::NUM_PLUS,
]}
pub fn fifthline() -> Vec<Key> {vec![
Key::G_4,
Key::LEFT_SHIFT,
Key::NON_US_SLASH,
Key::Z,
Key::X,
Key::C,
Key::V,
Key::B,
Key::N,
Key::M,
Key::COMMA,
Key::PERIOD,
Key::FORWARD_SLASH,
Key::RIGHT_SHIFT,
Key::ARROW_UP,
Key::NUM_ONE,
Key::NUM_TWO,
Key::NUM_THREE,
Key::NUM_ENTER,
]}
pub fn sixthline() -> Vec<Key> {vec![
Key::G_5,
Key::LEFT_CONTROL,
Key::LEFT_WINDOWS,
Key::LEFT_ALT,
Key::SPACE,
Key::RIGHT_ALT,
Key::RIGHT_WINDOWS,
Key::APPLICATION_SELECT,
Key::RIGHT_CONTROL,
Key::ARROW_LEFT,
Key::ARROW_DOWN,
Key::ARROW_RIGHT,
Key::NUM_ZERO,
Key::NUM_PERIOD,
Key::NUM_ENTER,
]}
pub fn gline() -> Vec<Key> {vec![
Key::G_6,
Key::G_7,
Key::G_8,
Key::G_9,
]}
pub fn gbadge() -> Vec<Key> {vec![
Key::G_BADGE
]}
}
pub fn to_logitechkey(k: &Key) -> led::Key {
let res = match k {
Key::ESC => led::Key::ESC,
Key::F1 => led::Key::F1,
Key::F2 => led::Key::F2,
Key::F3 => led::Key::F3,
Key::F4 => led::Key::F4,
Key::F5 => led::Key::F5,
Key::F6 => led::Key::F6,
Key::F7 => led::Key::F7,
Key::F8 => led::Key::F8,
Key::F9 => led::Key::F9,
Key::F10 => led::Key::F10,
Key::F11 => led::Key::F11,
Key::F12 => led::Key::F12,
Key::PRINT_SCREEN => led::Key::PRINT_SCREEN,
Key::SCROLL_LOCK => led::Key::SCROLL_LOCK,
Key::PAUSE_BREAK => led::Key::PAUSE_BREAK,
Key::TILDE => led::Key::TILDE,
Key::ONE => led::Key::ONE,
Key::TWO => led::Key::TWO,
Key::THREE => led::Key::THREE,
Key::FOUR => led::Key::FOUR,
Key::FIVE => led::Key::FIVE,
Key::SIX => led::Key::SIX,
Key::SEVEN => led::Key::SEVEN,
Key::EIGHT => led::Key::EIGHT,
Key::NINE => led::Key::NINE,
Key::ZERO => led::Key::ZERO,
Key::MINUS => led::Key::MINUS,
Key::EQUALS => led::Key::EQUALS,
Key::BACKSPACE => led::Key::BACKSPACE,
Key::INSERT => led::Key::INSERT,
Key::HOME => led::Key::HOME,
Key::PAGE_UP => led::Key::PAGE_UP,
Key::NUM_LOCK => led::Key::NUM_LOCK,
Key::NUM_SLASH => led::Key::NUM_SLASH,
Key::NUM_ASTERISK => led::Key::NUM_ASTERISK,
Key::NUM_MINUS => led::Key::NUM_MINUS,
Key::TAB => led::Key::TAB,
Key::Q => led::Key::Q,
Key::W => led::Key::W,
Key::E => led::Key::E,
Key::R => led::Key::R,
Key::T => led::Key::T,
Key::Y => led::Key::Y,
Key::U => led::Key::U,
Key::I => led::Key::I,
Key::O => led::Key::O,
Key::P => led::Key::P,
Key::OPEN_BRACKET => led::Key::OPEN_BRACKET,
Key::CLOSE_BRACKET => led::Key::CLOSE_BRACKET,
//Key::BACKSLASH =>led:: Key::BACKSLASH,
Key::KEYBOARD_DELETE => led::Key::KEYBOARD_DELETE,
Key::END => led::Key::END,
Key::PAGE_DOWN => led::Key::PAGE_DOWN,
Key::NUM_SEVEN => led::Key::NUM_SEVEN,
Key::NUM_EIGHT => led::Key::NUM_EIGHT,
Key::NUM_NINE => led::Key::NUM_NINE,
Key::NUM_PLUS => led::Key::NUM_PLUS,
Key::CAPS_LOCK => led::Key::CAPS_LOCK,
Key::A => led::Key::A,
Key::S => led::Key::S,
Key::D => led::Key::D,
Key::F => led::Key::F,
Key::G => led::Key::G,
Key::H => led::Key::H,
Key::J => led::Key::J,
Key::K => led::Key::K,
Key::L => led::Key::L,
Key::SEMICOLON => led::Key::SEMICOLON,
Key::APOSTROPHE => led::Key::APOSTROPHE,
Key::NON_US_ASTERISK => led::Key::NON_US_SLASH, //<<<< no code in logitech lib do not use
Key::ENTER => led::Key::ENTER,
Key::NUM_FOUR => led::Key::NUM_FOUR,
Key::NUM_FIVE => led::Key::NUM_FIVE,
Key::NUM_SIX => led::Key::NUM_SIX,
Key::LEFT_SHIFT => led::Key::LEFT_SHIFT,
Key::NON_US_SLASH => led::Key::NON_US_SLASH,
Key::Z => led::Key::Z,
Key::X => led::Key::X,
Key::C => led::Key::C,
Key::V => led::Key::V,
Key::B => led::Key::B,
Key::N => led::Key::N,
Key::M => led::Key::M,
Key::COMMA => led::Key::COMMA,
Key::PERIOD => led::Key::PERIOD,
Key::FORWARD_SLASH => led::Key::FORWARD_SLASH,
Key::RIGHT_SHIFT => led::Key::RIGHT_SHIFT,
Key::ARROW_UP => led::Key::ARROW_UP,
Key::NUM_ONE => led::Key::NUM_ONE,
Key::NUM_TWO => led::Key::NUM_TWO,
Key::NUM_THREE => led::Key::NUM_THREE,
Key::NUM_ENTER => led::Key::NUM_ENTER,
Key::LEFT_CONTROL => led::Key::LEFT_CONTROL,
Key::LEFT_WINDOWS => led::Key::LEFT_WINDOWS,
Key::LEFT_ALT => led::Key::LEFT_ALT,
Key::SPACE => led::Key::SPACE,
Key::RIGHT_ALT => led::Key::RIGHT_ALT,
Key::RIGHT_WINDOWS => led::Key::RIGHT_WINDOWS,
Key::APPLICATION_SELECT => led::Key::APPLICATION_SELECT,
Key::RIGHT_CONTROL => led::Key::RIGHT_CONTROL,
Key::ARROW_LEFT => led::Key::ARROW_LEFT,
Key::ARROW_DOWN => led::Key::ARROW_DOWN,
Key::ARROW_RIGHT => led::Key::ARROW_RIGHT,
Key::NUM_ZERO => led::Key::NUM_ZERO,
Key::NUM_PERIOD => led::Key::NUM_PERIOD,
Key::G_1 => led::Key::G_1,
Key::G_2 => led::Key::G_2,
Key::G_3 => led::Key::G_3,
Key::G_4 => led::Key::G_4,
Key::G_5 => led::Key::G_5,
Key::G_6 => led::Key::G_6,
Key::G_7 => led::Key::G_7,
Key::G_8 => led::Key::G_8,
Key::G_9 => led::Key::G_9,
Key::G_LOGO => led::Key::G_LOGO,
Key::G_BADGE => led::Key::G_BADGE,
};
res
}
pub fn scancode_to_key(sc: u8) -> Option<Key> {
let sc = klogi::keys::scancode_to_keycode(sc)?;
let res = match sc {
1 /*KEY_ESC */ => Key::ESC,
2 /*KEY_1 */ => Key::ONE,
3 /*KEY_2 */ => Key::TWO,
4 /*KEY_3 */ => Key::THREE,
5 /*KEY_4 */ => Key::FOUR,
6 /*KEY_5 */ => Key::FIVE,
7 /*KEY_6 */ => Key::SIX,
8 /*KEY_7 */ => Key::SEVEN,
9 /*KEY_8 */ => Key::EIGHT,
10 /*KEY_9 */ => Key::NINE,
11 /*KEY_0 */ => Key::ZERO,
12 /*KEY_MINUS */ => Key::MINUS,
13 /*KEY_EQUAL */ => Key::EQUALS,
14 /*KEY_BACKSPACE */ => Key::BACKSPACE,
15 /*KEY_TAB */ => Key::TAB,
16 /*KEY_Q */ => Key::Q,
17 /*KEY_W */ => Key::W,
18 /*KEY_E */ => Key::E,
19 /*KEY_R */ => Key::R,
20 /*KEY_T */ => Key::T,
21 /*KEY_Y */ => Key::Y,
22 /*KEY_U */ => Key::U,
23 /*KEY_I */ => Key::I,
24 /*KEY_O */ => Key::O,
25 /*KEY_P */ => Key::P,
26 /*KEY_LEFTBRACE */ => Key::OPEN_BRACKET,
27 /*KEY_RIGHTBRACE */ => Key::CLOSE_BRACKET,
28 /*KEY_ENTER */ => Key::ENTER,
29 /*KEY_LEFTCTRL */ => Key::LEFT_CONTROL,
30 /*KEY_A */ => Key::A,
31 /*KEY_S */ => Key::S,
32 /*KEY_D */ => Key::D,
33 /*KEY_F */ => Key::F,
34 /*KEY_G */ => Key::G,
35 /*KEY_H */ => Key::H,
36 /*KEY_J */ => Key::J,
37 /*KEY_K */ => Key::K,
38 /*KEY_L */ => Key::L,
39 /*KEY_SEMICOLON */ => Key::SEMICOLON,
40 /*KEY_APOSTROPHE */ => Key::APOSTROPHE,
41 /*KEY_GRAVE */ => Key::TILDE,
42 /*KEY_LEFTSHIFT */ => Key::LEFT_SHIFT,
43 /*KEY_BACKSLASH */ => Key::NON_US_ASTERISK,
44 /*KEY_Z */ => Key::Z,
45 /*KEY_X */ => Key::X,
46 /*KEY_C */ => Key::C,
47 /*KEY_V */ => Key::V,
48 /*KEY_B */ => Key::B,
49 /*KEY_N */ => Key::N,
50 /*KEY_M */ => Key::M,
51 /*KEY_COMMA */ => Key::COMMA,
52 /*KEY_DOT */ => Key::PERIOD,
53 /*KEY_SLASH */ => Key::FORWARD_SLASH,
54 /*KEY_RIGHTSHIFT */ => Key::RIGHT_SHIFT,
55 /*KEY_KPASTERISK */ => Key::NUM_ASTERISK,
56 /*KEY_LEFTALT */ => Key::LEFT_ALT,
57 /*KEY_SPACE */ => Key::SPACE,
58 /*KEY_CAPSLOCK */ => Key::CAPS_LOCK,
59 /*KEY_F1 */ => Key::F1,
60 /*KEY_F2 */ => Key::F2,
61 /*KEY_F3 */ => Key::F3,
62 /*KEY_F4 */ => Key::F4,
63 /*KEY_F5 */ => Key::F5,
64 /*KEY_F6 */ => Key::F6,
65 /*KEY_F7 */ => Key::F7,
66 /*KEY_F8 */ => Key::F8,
67 /*KEY_F9 */ => Key::F9,
68 /*KEY_F10 */ => Key::F10,
69 /*KEY_NUMLOCK */ => Key::NUM_LOCK,
70 /*KEY_SCROLLLOCK */ => Key::SCROLL_LOCK,
71 /*KEY_KP7 */ => Key::NUM_SEVEN,
72 /*KEY_KP8 */ => Key::NUM_EIGHT,
73 /*KEY_KP9 */ => Key::NUM_NINE,
74 /*KEY_KPMINUS */ => Key::NUM_MINUS,
75 /*KEY_KP4 */ => Key::NUM_FOUR,
76 /*KEY_KP5 */ => Key::NUM_FIVE,
77 /*KEY_KP6 */ => Key::NUM_SIX,
78 /*KEY_KPPLUS */ => Key::NUM_PLUS,
79 /*KEY_KP1 */ => Key::NUM_ONE,
80 /*KEY_KP2 */ => Key::NUM_TWO,
81 /*KEY_KP3 */ => Key::NUM_THREE,
82 /*KEY_KP0 */ => Key::NUM_ZERO,
83 /*KEY_KPDOT */ => Key::NUM_PERIOD,
110 /*KEY_INSERT */ => Key::INSERT,
111 /*KEY_DELETE */ => Key::KEYBOARD_DELETE,
107 /*KEY_END */ => Key::END,
102 /*KEY_HOME */ => Key::HOME,
100 /*KEY_RIGHTALT */ => Key::RIGHT_ALT,
97 /*KEY_RIGHTCTRL */ => Key::RIGHT_CONTROL,
87 /*KEY_F11 */ => Key::F11,
88 /*KEY_F12 */ => Key::F12,
103 /*KEY_UP */ => Key::ARROW_UP,
104 /*KEY_PAGEUP */ => Key::PAGE_UP,
105 /*KEY_LEFT */ => Key::ARROW_LEFT,
106 /*KEY_RIGHT */ => Key::ARROW_RIGHT,
108 /*KEY_DOWN */ => Key::ARROW_DOWN,
109 /*KEY_PAGEDOWN */ => Key::PAGE_DOWN,
119 /*KEY_PAUSE */ => Key::PAUSE_BREAK,
125 /*KEY_LEFTMETA */ => Key::LEFT_WINDOWS,
126 /*KEY_RIGHTMETA */ => Key::RIGHT_WINDOWS,
99 /*KEY_SYSRQ */ => Key::PRINT_SCREEN,
127 /*KEY_COMPOSE */ => Key::APPLICATION_SELECT,
98 /*KEY_KPSLASH */ => Key::NUM_SLASH,
96 /*KEY_KPENTER */ => Key::NUM_ENTER,
86 /*KEY_102ND */ => Key::NON_US_SLASH,
//85 /*KEY_ZENKAKUHANKAKU */ => Key::ZENKAKUHANKAKU,
//86 /*KEY_102ND */ => Key::102ND,
//89 /*KEY_RO */ => Key::RO,
//90 /*KEY_KATAKANA */ => Key::KATAKANA,
//91 /*KEY_HIRAGANA */ => Key::HIRAGANA,
//92 /*KEY_HENKAN */ => Key::HENKAN,
//93 /*KEY_KATAKANAHIRAGANA */ => Key::KATAKANAHIRAGANA,
//94 /*KEY_MUHENKAN */ => Key::MUHENKAN,
//95 /*KEY_KPJPCOMMA */ => Key::KPJPCOMMA,
//101 /*KEY_LINEFEED */ => Key::LINEFEED,
//112 /*KEY_MACRO */ => Key::MACRO,
//113 /*KEY_MUTE */ => Key::MUTE,
//114 /*KEY_VOLUMEDOWN */ => Key::VOLUMEDOWN,
//115 /*KEY_VOLUMEUP */ => Key::VOLUMEUP,
//116 /*KEY_POWER SC System Power Down */ => Key::POWER,
//117 /*KEY_KPEQUAL */ => Key::KPEQUAL,
//118 /*KEY_KPPLUSMINUS */ => Key::KPPLUSMINUS,
//120 /*KEY_SCALE AL Compiz Scale (Expose) */ => Key::SCALE,
//121 /*KEY_KPCOMMA */ => Key::KPCOMMA,
//122 /*KEY_HANGEUL */ => Key::HANGEUL,
//KEY_HANGEUL /*KEY_HANGUEL */ => Key::HANGUEL,
//123 /*KEY_HANJA */ => Key::HANJA,
//124 /*KEY_YEN */ => Key::YEN,
//128 /*KEY_STOP AC Stop */ => Key::STOP,
//129 /*KEY_AGAIN */ => Key::AGAIN,
//130 /*KEY_PROPS AC Properties */ => Key::PROPS,
//131 /*KEY_UNDO AC Undo */ => Key::UNDO,
//132 /*KEY_FRONT */ => Key::FRONT,
//133 /*KEY_COPY AC Copy */ => Key::COPY,
//134 /*KEY_OPEN AC Open */ => Key::OPEN,
//135 /*KEY_PASTE AC Paste */ => Key::PASTE,
//136 /*KEY_FIND AC Search */ => Key::FIND,
//137 /*KEY_CUT AC Cut */ => Key::CUT,
//138 /*KEY_HELP AL Integrated Help Center */ => Key::HELP,
//139 /*KEY_MENU Menu (show menu) */ => Key::MENU,
//140 /*KEY_CALC AL Calculator */ => Key::CALC,
//141 /*KEY_SETUP */ => Key::SETUP,
//142 /*KEY_SLEEP SC System Sleep */ => Key::SLEEP,
//143 /*KEY_WAKEUP System Wake Up */ => Key::WAKEUP,
//144 /*KEY_FILE AL Local Machine Browser */ => Key::FILE,
//145 /*KEY_SENDFILE */ => Key::SENDFILE,
//146 /*KEY_DELETEFILE */ => Key::DELETEFILE,
//147 /*KEY_XFER */ => Key::XFER,
//148 /*KEY_PROG1 */ => Key::PROG1,
//149 /*KEY_PROG2 */ => Key::PROG2,
//150 /*KEY_WWW AL Internet Browser */ => Key::WWW,
//151 /*KEY_MSDOS */ => Key::MSDOS,
//152 /*KEY_COFFEE AL Terminal Lock/Screensaver */ => Key::COFFEE,
//KEY_COFFEE /*KEY_SCREENLOCK */ => Key::SCREENLOCK,
//153 /*KEY_ROTATE_DISPLAY Display orientation for e.g. tablets */ => Key::ROTATE_DISPLAY,
//KEY_ROTATE_DISPLAY /*KEY_DIRECTION */ => Key::DIRECTION,
//154 /*KEY_CYCLEWINDOWS */ => Key::CYCLEWINDOWS,
//155 /*KEY_MAIL */ => Key::MAIL,
//156 /*KEY_BOOKMARKS AC Bookmarks */ => Key::BOOKMARKS,
//157 /*KEY_COMPUTER */ => Key::COMPUTER,
//158 /*KEY_BACK AC Back */ => Key::BACK,
//159 /*KEY_FORWARD AC Forward */ => Key::FORWARD,
//160 /*KEY_CLOSECD */ => Key::CLOSECD,
//161 /*KEY_EJECTCD */ => Key::EJECTCD,
//162 /*KEY_EJECTCLOSECD */ => Key::EJECTCLOSECD,
//163 /*KEY_NEXTSONG */ => Key::NEXTSONG,
//164 /*KEY_PLAYPAUSE */ => Key::PLAYPAUSE,
//165 /*KEY_PREVIOUSSONG */ => Key::PREVIOUSSONG,
//166 /*KEY_STOPCD */ => Key::STOPCD,
//167 /*KEY_RECORD */ => Key::RECORD,
//168 /*KEY_REWIND */ => Key::REWIND,
//169 /*KEY_PHONE Media Select Telephone */ => Key::PHONE,
//170 /*KEY_ISO */ => Key::ISO,
//171 /*KEY_CONFIG AL Consumer Control Configuration */ => Key::CONFIG,
//172 /*KEY_HOMEPAGE AC Home */ => Key::HOMEPAGE,
//173 /*KEY_REFRESH AC Refresh */ => Key::REFRESH,
//174 /*KEY_EXIT AC Exit */ => Key::EXIT,
//175 /*KEY_MOVE */ => Key::MOVE,
//176 /*KEY_EDIT */ => Key::EDIT,
//177 /*KEY_SCROLLUP */ => Key::SCROLLUP,
//178 /*KEY_SCROLLDOWN */ => Key::SCROLLDOWN,
//179 /*KEY_KPLEFTPAREN */ => Key::KPLEFTPAREN,
//180 /*KEY_KPRIGHTPAREN */ => Key::KPRIGHTPAREN,
//181 /*KEY_NEW AC New */ => Key::NEW,
_ => return None
};
Some(res)
}
pub struct KeyboardLayout {
keys_db: KeysDB,
}
impl KeyboardLayout {
pub fn new() -> Self {
let kl = klogi::parse_layout();
let mut keylayout = kl
.zones
.clone()
.into_iter()
.map(|z| {
z.keys.into_iter().filter_map(move |z1| {
if let Some(code) = scancode_to_key(z1.code as u8) {
Some((code, z1.clone()))
} else {
None
}
})
})
.flatten()
.collect::<HashMap<_, _>>();
keylayout.extend(
kl.zones
.into_iter()
.map(|z| {
z.keys.into_iter().filter_map(move |z1| {
if let Some(glyph) = &z1.glyph {
if let Some(gkey) = Key::from_str(glyph) {
Some((gkey, z1.clone()))
} else {
None
}
} else {
None
}
})
})
.flatten()
.collect::<HashMap<_, _>>(),
);
Self {
keys_db: keylayout,
}
}
pub fn get_keydata(&self, key: Key) -> KeydataType {
(key, self.keys_db[&key].clone())
}
pub fn get_keysdata(&self, keys: Vec<Key>) -> Vec<KeydataType> {
let mut v = Vec::with_capacity(keys.len());
for k in keys {
v.push((k, self.keys_db[&k].clone()));
}
return v;
}
}
/*
#[repr(C)]
#[derive(Clone, Copy, Hash, Debug, PartialEq, Eq, PartialOrd, Ord)]
#[allow(non_camel_case_types, non_snake_case)]
pub enum Key_fr {
ESC,
F1,
F2,
F3,
F4,
F5,
F6,
F7,
F8,
F9,
F10,
F11,
F12,
PRINT_SCREEN,
SCROLL_LOCK,
PAUSE_BREAK,
TILDE,
ONE,
TWO,
THREE,
FOUR,
FIVE,
SIX,
SEVEN,
EIGHT,
NINE,
ZERO,
MINUS,
EQUALS,
BACKSPACE,
INSERT,
HOME,
PAGE_UP,
NUM_LOCK,
NUM_SLASH,
NUM_ASTERISK,
NUM_MINUS,
TAB,
A,
Z,
E,
R,
T,
Y,
U,
I,
O,
P,
OPEN_BRACKET,
CLOSE_BRACKET,
KEYBOARD_DELETE,
END,
PAGE_DOWN,
NUM_SEVEN,
NUM_EIGHT,
NUM_NINE,
NUM_PLUS,
CAPS_LOCK,
Q,
S,
D,
F,
G,
H,
J,
K,
L,
M,
PERIOD,
NON_US_ASTERISK,
ENTER,
NUM_FOUR,
NUM_FIVE,
NUM_SIX,
LEFT_SHIFT,
NON_US_SLASH,
W,
X,
C,
V,
B,
N,
COMMA,
SEMICOLON,
FORWARD_SLASH,
EXCLAMATION,
RIGHT_SHIFT,
ARROW_UP,
NUM_ONE,
NUM_TWO,
NUM_THREE,
NUM_ENTER,
LEFT_CONTROL,
LEFT_WINDOWS,
LEFT_ALT,
SPACE,
RIGHT_ALT,
RIGHT_WINDOWS,
APPLICATION_SELECT,
RIGHT_CONTROL,
ARROW_LEFT,
ARROW_DOWN,
ARROW_RIGHT,
NUM_ZERO,
NUM_PERIOD,
}
impl From<Key_fr> for Key {
fn from(k: Key_fr) -> Self {
match k {
Key_fr::ESC => Key::ESC ,
Key_fr::F1 => Key::F1 ,
Key_fr::F2 => Key::F2 ,
Key_fr::F3 => Key::F3 ,
Key_fr::F4 => Key::F4 ,
Key_fr::F5 => Key::F5 ,
Key_fr::F6 => Key::F6 ,
Key_fr::F7 => Key::F7 ,
Key_fr::F8 => Key::F8 ,
Key_fr::F9 => Key::F9 ,
Key_fr::F10 => Key::F10 ,
Key_fr::F11 => Key::F11 ,
Key_fr::F12 => Key::F12 ,
Key_fr::PRINT_SCREEN => Key::PRINT_SCREEN ,
Key_fr::SCROLL_LOCK => Key::SCROLL_LOCK ,
Key_fr::PAUSE_BREAK => Key::PAUSE_BREAK ,
Key_fr::TILDE => Key::TILDE ,
Key_fr::ONE => Key::ONE ,
Key_fr::TWO => Key::TWO ,
Key_fr::THREE => Key::THREE ,
Key_fr::FOUR => Key::FOUR ,
Key_fr::FIVE => Key::FIVE ,
Key_fr::SIX => Key::SIX ,
Key_fr::SEVEN => Key::SEVEN ,
Key_fr::EIGHT => Key::EIGHT ,
Key_fr::NINE => Key::NINE ,
Key_fr::ZERO => Key::ZERO ,
Key_fr::MINUS => Key::MINUS ,
Key_fr::EQUALS => Key::EQUALS ,
Key_fr::BACKSPACE => Key::BACKSPACE ,
Key_fr::INSERT => Key::INSERT ,
Key_fr::HOME => Key::HOME ,
Key_fr::PAGE_UP => Key::PAGE_UP ,
Key_fr::NUM_LOCK => Key::NUM_LOCK ,
Key_fr::NUM_SLASH => Key::NUM_SLASH ,
Key_fr::NUM_ASTERISK => Key::NUM_ASTERISK ,
Key_fr::NUM_MINUS => Key::NUM_MINUS ,
Key_fr::TAB => Key::TAB ,
Key_fr::A => Key::Q ,
Key_fr::Z => Key::W ,
Key_fr::E => Key::E ,
Key_fr::R => Key::R ,
Key_fr::T => Key::T ,
Key_fr::Y => Key::Y ,
Key_fr::U => Key::U ,
Key_fr::I => Key::I ,
Key_fr::O => Key::O ,
Key_fr::P => Key::P ,
Key_fr::OPEN_BRACKET => Key::OPEN_BRACKET ,
Key_fr::CLOSE_BRACKET => Key::CLOSE_BRACKET ,
Key_fr::KEYBOARD_DELETE => Key::KEYBOARD_DELETE ,
Key_fr::END => Key::END ,
Key_fr::PAGE_DOWN => Key::PAGE_DOWN ,
Key_fr::NUM_SEVEN => Key::NUM_SEVEN ,
Key_fr::NUM_EIGHT => Key::NUM_EIGHT ,
Key_fr::NUM_NINE => Key::NUM_NINE ,
Key_fr::NUM_PLUS => Key::NUM_PLUS ,
Key_fr::CAPS_LOCK => Key::CAPS_LOCK ,
Key_fr::Q => Key::A ,
Key_fr::S => Key::S ,
Key_fr::D => Key::D ,
Key_fr::F => Key::F ,
Key_fr::G => Key::G ,
Key_fr::H => Key::H ,
Key_fr::J => Key::J ,
Key_fr::K => Key::K ,
Key_fr::L => Key::L ,
Key_fr::M => Key::SEMICOLON ,
Key_fr::PERIOD => Key::APOSTROPHE ,
Key_fr::NON_US_ASTERISK => Key::NON_US_ASTERISK ,
Key_fr::ENTER => Key::ENTER ,
Key_fr::NUM_FOUR => Key::NUM_FOUR ,
Key_fr::NUM_FIVE => Key::NUM_FIVE ,
Key_fr::NUM_SIX => Key::NUM_SIX ,
Key_fr::LEFT_SHIFT => Key::LEFT_SHIFT ,
Key_fr::NON_US_SLASH => Key::NON_US_SLASH ,
Key_fr::W => Key::Z ,
Key_fr::X => Key::X ,
Key_fr::C => Key::C ,
Key_fr::V => Key::V ,
Key_fr::B => Key::B ,
Key_fr::N => Key::N ,
Key_fr::COMMA => Key::M ,
Key_fr::SEMICOLON => Key::COMMA ,
Key_fr::FORWARD_SLASH => Key::PERIOD ,
Key_fr::EXCLAMATION => Key::FORWARD_SLASH ,
Key_fr::RIGHT_SHIFT => Key::RIGHT_SHIFT ,
Key_fr::ARROW_UP => Key::ARROW_UP ,
Key_fr::NUM_ONE => Key::NUM_ONE ,
Key_fr::NUM_TWO => Key::NUM_TWO ,
Key_fr::NUM_THREE => Key::NUM_THREE ,
Key_fr::NUM_ENTER => Key::NUM_ENTER ,
Key_fr::LEFT_CONTROL => Key::LEFT_CONTROL ,
Key_fr::LEFT_WINDOWS => Key::LEFT_WINDOWS ,
Key_fr::LEFT_ALT => Key::LEFT_ALT ,
Key_fr::SPACE => Key::SPACE ,
Key_fr::RIGHT_ALT => Key::RIGHT_ALT ,
Key_fr::RIGHT_WINDOWS => Key::RIGHT_WINDOWS ,
Key_fr::APPLICATION_SELECT => Key::APPLICATION_SELECT,
Key_fr::RIGHT_CONTROL => Key::RIGHT_CONTROL ,
Key_fr::ARROW_LEFT => Key::ARROW_LEFT ,
Key_fr::ARROW_DOWN => Key::ARROW_DOWN ,
Key_fr::ARROW_RIGHT => Key::ARROW_RIGHT ,
Key_fr::NUM_ZERO => Key::NUM_ZERO ,
Key_fr::NUM_PERIOD => Key::NUM_PERIOD ,
}
}
} */
| true |
07b8a976a5d3ee36390b42f950acfbd0b31cd964
|
Rust
|
elijahandrews/ncollide
|
/src/procedural/to_trimesh/capsule_to_trimesh.rs
|
UTF-8
| 815 | 2.65625 | 3 |
[
"BSD-2-Clause"
] |
permissive
|
use na;
use geom::Capsule;
use procedural::{ToTriMesh, TriMesh};
use procedural;
use math::{Scalar, Point, Vect};
#[cfg(feature = "3d")]
impl ToTriMesh<(u32, u32)> for Capsule {
fn to_trimesh(&self, (ntheta_subdiv, nphi_subdiv): (u32, u32)) -> TriMesh<Scalar, Point, Vect> {
let diameter = self.radius() * na::cast(2.0f64);
let height = self.half_height() * na::cast(2.0f64);
// FIXME: the fact `capsule` does not take directly the half_height and the radius feels
// inconsistant.
procedural::capsule(&diameter, &height, ntheta_subdiv, nphi_subdiv)
}
}
/*
#[cfg(not(3d))]
impl ToTriMesh<uint> for Capsule
{
fn to_trimesh(&self, ntheta_subdiv: uint) -> TriMesh<Scalar, Point, Vect>
{
// FIXME: generate a 2d rasterization of a capsule.
}
}
*/
| true |
9fb8679f2c4771b9650eacd0047e8fbb69df7e31
|
Rust
|
vthib/aoc19-rust
|
/day6/src/main.rs
|
UTF-8
| 2,536 | 3.28125 | 3 |
[
"MIT"
] |
permissive
|
use std::collections::{HashMap, HashSet};
use std::io;
use std::io::Read;
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
fn main() -> Result<()> {
let mut input = String::new();
io::stdin().read_to_string(&mut input)?;
// from star to its satellites
let mut deps = HashMap::new();
// from object to its star
let mut revdeps = HashMap::new();
for line in input.lines() {
let names: Vec<&str> = line.split(')').collect();
assert!(names.len() == 2);
deps.insert(names[1], names[0]);
let entry = revdeps.entry(names[0]).or_insert(Vec::new());
entry.push(names[1]);
}
let mut sources = Vec::new();
for obj in revdeps.keys() {
if !deps.contains_key(obj) {
sources.push(*obj);
}
}
let levels = compute_graph_levels(&revdeps, &sources);
day6a(&levels);
day6b(&deps, &levels);
Ok(())
}
fn compute_graph_levels<'a>(
deps: &'a HashMap<&str, Vec<&str>>,
sources: &'a Vec<&str>,
) -> HashMap<&'a str, u32> {
let mut todo = sources.clone();
let mut levels = HashMap::new();
let mut level = 0;
// Do a BFS and add distances to source
while todo.len() > 0 {
let mut next_todo = Vec::new();
for obj in todo {
levels.insert(obj, level);
if let Some(children) = deps.get(obj) {
for c in children {
next_todo.push(*c);
}
}
}
todo = next_todo;
level += 1;
}
levels
}
fn day6a(levels: &HashMap<&str, u32>) {
let total = levels.values().fold(0, |acc, v| acc + v);
println!("day6a number of total orbits: {}", total);
}
fn day6b(deps: &HashMap<&str, &str>, levels: &HashMap<&str, u32>) {
let mut visited = HashSet::new();
// mark all the parents of "YOU"
let mut obj = "YOU";
while let Some(parent) = deps.get(obj) {
visited.insert(parent);
obj = parent;
}
// then do the same from "SAM". As soon as a visited node is
// found, we have our path
let mut obj = "SAN";
while let Some(parent) = deps.get(obj) {
if visited.contains(parent) {
let dist_you = levels.get("YOU").unwrap() - levels.get(parent).unwrap() - 1;
let dist_san = levels.get("SAN").unwrap() - levels.get(parent).unwrap() - 1;
println!("day6b distance: {}", dist_you + dist_san);
return;
}
obj = parent;
}
assert!(false);
}
| true |
8fadeff5986784db83da7e2d31292eda9e21025c
|
Rust
|
cdecompilador/console_color-rs
|
/src/platform/windows.rs
|
UTF-8
| 5,015 | 2.8125 | 3 |
[] |
no_license
|
//! This module includes the bindings generated by `windows` crate,
//! (should be) more standard than winapi, maintained by microsoft
#![cfg(target_family = "windows")]
use bindings::{
Windows::Win32::SystemServices::{
GetConsoleScreenBufferInfo,
SetConsoleTextAttribute,
WriteConsoleA,
CONSOLE_SCREEN_BUFFER_INFO,
FOREGROUND_INTENSITY,
FOREGROUND_RED,
FOREGROUND_GREEN,
FOREGROUND_BLUE,
BACKGROUND_INTENSITY,
BACKGROUND_RED,
BACKGROUND_GREEN,
BACKGROUND_BLUE,
NonClosableHandle
},
Windows::Win32::WindowsProgramming::{
GetStdHandle,
STD_HANDLE_TYPE
}
};
use crate::color::Color;
use std::ffi::CString;
/// Raw terminal definition and implementation for windows using Win32
/// the raw terminal must implement `new` and `write`
pub struct RawTerminal {
console_handle: NonClosableHandle,
}
impl RawTerminal {
/// Instantiates an raw terminal
pub fn new() -> Self {
// Get the handle to the current terminal
let console_handle = unsafe {
GetStdHandle(STD_HANDLE_TYPE::STD_OUTPUT_HANDLE)
};
return RawTerminal {
console_handle,
};
}
/// Writes to the console using the Win32 api specifing the foreground and
/// background colors
pub fn write(&self, msg: &str, fg: Color, bg: Color)
{
// Create the console_info struct from the win32 api to store
// the old state
let mut console_info = CONSOLE_SCREEN_BUFFER_INFO::default();
unsafe {
GetConsoleScreenBufferInfo(self.console_handle, &mut console_info);
}
dbg!(&console_info);
// Set the correct win32 api color for the foreground and background
// given the `Color`
let fg_color_enum = match fg {
Color::None => (console_info.wAttributes & 0x000f) as u32,
Color::Black => 0,
Color::DarkBlue => FOREGROUND_BLUE,
Color::DarkGreen => FOREGROUND_GREEN,
Color::DarkCyan => FOREGROUND_GREEN | FOREGROUND_BLUE,
Color::DarkRed => FOREGROUND_RED,
Color::DarkMagenta => FOREGROUND_RED | FOREGROUND_BLUE,
Color::DarkYellow => FOREGROUND_RED | FOREGROUND_GREEN,
Color::DarkGray => FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE,
Color::Gray => FOREGROUND_INTENSITY,
Color::Blue => FOREGROUND_INTENSITY | FOREGROUND_BLUE,
Color::Green => FOREGROUND_INTENSITY | FOREGROUND_GREEN,
Color::Cyan => FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_BLUE,
Color::Red => FOREGROUND_INTENSITY | FOREGROUND_RED,
Color::Magenta => FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_BLUE,
Color::Yellow => FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN,
Color::White => FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE
};
let bg_color_enum = match bg {
Color::None => (console_info.wAttributes & 0x00f0) as u32,
Color::Black => 0,
Color::DarkBlue => BACKGROUND_BLUE,
Color::DarkGreen => BACKGROUND_GREEN,
Color::DarkCyan => BACKGROUND_GREEN | BACKGROUND_BLUE,
Color::DarkRed => BACKGROUND_RED,
Color::DarkMagenta => BACKGROUND_RED | BACKGROUND_BLUE,
Color::DarkYellow => BACKGROUND_RED | BACKGROUND_GREEN,
Color::DarkGray => BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE,
Color::Gray => BACKGROUND_INTENSITY,
Color::Blue => BACKGROUND_INTENSITY | BACKGROUND_BLUE,
Color::Green => BACKGROUND_INTENSITY | BACKGROUND_GREEN,
Color::Cyan => BACKGROUND_INTENSITY | BACKGROUND_GREEN | BACKGROUND_BLUE,
Color::Red => BACKGROUND_INTENSITY | BACKGROUND_RED,
Color::Magenta => BACKGROUND_INTENSITY | BACKGROUND_RED | BACKGROUND_BLUE,
Color::Yellow => BACKGROUND_INTENSITY | BACKGROUND_RED | BACKGROUND_GREEN,
Color::White => BACKGROUND_INTENSITY | BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE
};
// Set a new console state with the modified foreground and background
// colors
unsafe {
SetConsoleTextAttribute(self.console_handle,
(fg_color_enum | bg_color_enum) as u16);
}
// Write the text to the console
unsafe {
WriteConsoleA(self.console_handle,
CString::new(msg).expect("Couldn't create CString")
.to_bytes_with_nul().as_ptr() as *const _,
msg.len() as u32,
std::ptr::null_mut(),
std::ptr::null_mut());
}
// Restore the old console attributes
unsafe {
SetConsoleTextAttribute(self.console_handle,
console_info.wAttributes);
}
}
}
| true |
82999291f850feb87279787b3b25eef61b2295d3
|
Rust
|
MoxxieGIT/sylphiev3
|
/sylphie/sylphie_database/src/config/impls.rs
|
UTF-8
| 654 | 2.640625 | 3 |
[] |
no_license
|
use crate::config::ConfigType;
use std::fmt;
use sylphie_core::errors::*;
impl <T: ConfigType> ConfigType for Option<T> {
fn ui_fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Some(v) => T::ui_fmt(v, formatter),
None => formatter.write_str("(default)"),
}
}
fn ui_parse(text: &str) -> Result<Self> {
Ok(Some(T::ui_parse(text)?))
}
}
impl ConfigType for String {
fn ui_fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(&*self)
}
fn ui_parse(text: &str) -> Result<Self> {
Ok(text.to_string())
}
}
| true |
437444e2cdc9875b2c3b563fe861ed0cb77034b1
|
Rust
|
faineance/rustorm
|
/examples/delete_category.rs
|
UTF-8
| 500 | 2.640625 | 3 |
[
"MIT"
] |
permissive
|
extern crate rustorm;
use rustorm::platform::postgres::Postgres;
use rustorm::query::Query;
use rustorm::query::{Filter,Equality};
fn main(){
let pg = Postgres::connect_with_url("postgres://postgres:p0stgr3s@localhost/bazaar_v6").unwrap();
match Query::delete()
.from_table("bazaar.category")
.filter("name", Equality::LIKE, &"Test%")
.execute(&pg){
Ok(x) => println!("deleted {}", x),
Err(e) => println!("Error {}", e)
}
}
| true |
46c694d284e40de160007ebda991fc78edfbd203
|
Rust
|
peterwilli/Lightwatch
|
/PinGUIn/libpinguin/src/geospatial_fastindex/tests.rs
|
UTF-8
| 3,130 | 3.375 | 3 |
[
"MIT"
] |
permissive
|
#[cfg(test)]
mod tests {
use crate::common::Rect;
use crate::geospatial_fastindex::GeoSpatialFastIndex;
use crate::println;
#[test]
fn test_add_tile2() {
let mut fastindex = GeoSpatialFastIndex::<i16, i16, u8>::new(10, 10, 10, 10);
fastindex.add(
Rect {
x: 0,
y: 0,
w: 100,
h: 30,
},
1,
);
for i in 0..2 {
println!("Tryout {}", i);
let result = fastindex.find(&Rect {
x: 10,
y: 10,
w: 1,
h: 1,
});
assert_eq!(result[0], 1);
}
}
#[test]
fn test_add_tile() {
let mut fastindex = GeoSpatialFastIndex::<u8, u8, u8>::new(10, 10, 10, 10);
fastindex.add(
Rect::<u8> {
x: 0,
y: 0,
w: 10,
h: 10,
},
1,
);
fastindex.add(
Rect::<u8> {
x: 0,
y: 0,
w: 10,
h: 10,
},
2,
);
for i in 0..2 {
println!("Tryout {}", i);
let result = fastindex.find(&Rect::<u8> {
x: 1,
y: 5,
w: 1,
h: 1,
});
assert_eq!(result[0], 1);
assert_eq!(result[1], 2);
}
fastindex.add(
Rect::<u8> {
x: 0,
y: 0,
w: 10,
h: 10,
},
3,
);
fastindex.add(
Rect::<u8> {
x: 2,
y: 0,
w: 10,
h: 10,
},
4,
);
let result = fastindex.find(&Rect {
x: 1,
y: 5,
w: 1,
h: 1,
});
assert_eq!(result.len(), 3);
assert_eq!(result[0], 1);
assert_eq!(result[1], 2);
assert_eq!(result[2], 3);
}
#[test]
fn test_tile_converter() {
let mut fastindex = GeoSpatialFastIndex::<u8, u8, u8>::new(10, 10, 10, 10);
///
// Tile test 1
///
let rect = Rect {
x: 0,
y: 0,
w: 10,
h: 10,
};
let tiles = fastindex.rect_to_tiles(&rect);
println!("rect: {} tiles: {}", rect, tiles);
assert_eq!(
tiles,
Rect {
x: 0,
y: 0,
w: 1,
h: 1
}
);
///
// Tile test 2
///
let rect = Rect {
x: 5,
y: 5,
w: 20,
h: 10,
};
let tiles = fastindex.rect_to_tiles(&rect);
println!("rect: {} tiles: {}", rect, tiles);
assert_eq!(
tiles,
Rect {
x: 0,
y: 0,
w: 2,
h: 1
}
);
}
}
| true |
acba7bc3d7a9f8d7744519c8f39cc6105d03899c
|
Rust
|
nacleric/mdview
|
/src/main.rs
|
UTF-8
| 4,125 | 2.984375 | 3 |
[] |
no_license
|
use std::io::{BufRead, BufReader};
use std::path::PathBuf;
use pulldown_cmark::{html, Parser};
use structopt::StructOpt;
use tiny_http::{Request, Response, Server};
use webbrowser;
extern crate ispell;
use ispell::SpellLauncher;
#[derive(Debug, StructOpt)]
enum CliArgs {
#[structopt(name = "serve", about = "Serve subcommand")]
Serve {
#[structopt(help = "Input path to file", parse(from_os_str))]
path: PathBuf,
#[structopt(help = "Input port number", default_value = "5000")]
port: String,
},
#[structopt(name = "debug", about = "Debug subcommand")]
Debug {
#[structopt(help = "Input path to file", parse(from_os_str))]
path: PathBuf,
},
}
fn is_md_file<P>(path: P) -> bool
where
P: Into<PathBuf>,
{
path.into() // Into<PathBuf>::into() -> PathBuf
.extension() // PathBuf::extension() -> Option<&OsStr>
.is_some() // Option<&OsStr> -> bool
}
fn process_md(path: &PathBuf) -> String {
let mdfile = is_md_file(path);
if mdfile {
let result = std::fs::read_to_string(path);
let content = match result {
Ok(content) => content,
Err(error) => {
panic!("Can't deal with {:?}, just exit here", error);
}
};
let parser = Parser::new(&content);
let mut html_output = String::new();
html::push_html(&mut html_output, parser);
html_output
} else {
panic!("Not a Markdown file");
}
}
#[derive(Debug)]
struct WebServer<'a> {
path: &'a PathBuf,
port: &'a String,
}
impl WebServer<'_> {
fn send_response(&self, request: Request) {
let mut html_body = String::from("<link rel='stylesheet' href='https://unpkg.com/sakura.css/css/sakura.css' type='text/css'>");
let html_output = process_md(self.path);
html_body.push_str(&html_output);
let response = Response::from_data(html_body.clone().into_bytes());
request.respond(response).unwrap(); // TODO: Get rid of unwrap()
}
fn run(&self) {
let mut address = String::from("http://localhost:");
address.push_str(self.port);
let result = Server::http(&address[7..address.len()]);
let server = match result {
Ok(server) => server,
Err(error) => panic!("{:?}", error),
};
println!("Port: {}, Server is running...", self.port);
webbrowser::open(&address[..]).unwrap(); // TODO: Get rid of unwrap()
loop {
let request = match server.recv() {
Ok(request) => request,
Err(error) => {
panic!("Error: {:?}", error);
}
};
println!("{:?}", request);
self.send_response(request);
}
}
}
fn debug(path: &PathBuf) {
let mut checker = SpellLauncher::new()
.aspell()
.dictionary("en_GB")
.launch()
.unwrap();
let file = std::fs::File::open(&path).unwrap();
let file = BufReader::new(file);
let mut line_count = 0;
for line in file.lines() {
line_count += 1;
let line = match line {
Ok(line) => line,
Err(error) => {
panic!("Error: {:?}", error);
}
};
let errors = checker.check(&line).unwrap();
for e in errors {
println!(
"'{}' (line: {} pos: {}) is misspelled!",
&e.misspelled, line_count, e.position
);
if !e.suggestions.is_empty() {
println!(
"Maybe you meant '{}, {}, {}'?",
&e.suggestions[0], &e.suggestions[1], &e.suggestions[2]
);
}
}
}
}
fn main() {
let args = CliArgs::from_args();
match args {
CliArgs::Serve { path, port } => {
let server = WebServer {
path: &path,
port: &port,
};
server.run();
}
CliArgs::Debug { path } => {
debug(&path);
}
}
}
| true |
5e200d9c42e03bce0739b2a72e8377c50f3107e6
|
Rust
|
aiaoyang/processMonitorWithRust
|
/src/read.rs
|
UTF-8
| 787 | 2.953125 | 3 |
[] |
no_license
|
pub fn read_file_line_column(
file: String,
line: usize,
position: usize,
) -> Result<f64, crate::error::MyError> {
if let Ok(line) = read_file_line(file, line) {
let num = line
.split_whitespace()
.collect::<Vec<&str>>()
.get(position)
.unwrap()
.parse::<f64>()?;
return Ok(num);
};
Ok(-0.0)
}
pub fn read_file_line(file: String, line: usize) -> Result<String, crate::error::MyError> {
let content = std::fs::read_to_string(file)?;
if let Some(line) = content
.lines()
.collect::<Vec<&str>>()
.get(line)
.and_then(|line| Some(line.to_string()))
{
return Ok(line);
};
// .into();
Err(crate::error::MyError::OutOfRange)
}
| true |
3a03eec1b0f0b20f2b317e2436a1c501a62dfa45
|
Rust
|
etaoins/arret
|
/runtime-syntax/writer.rs
|
UTF-8
| 11,884 | 2.953125 | 3 |
[
"Apache-2.0"
] |
permissive
|
use std::io::{Result, Write};
use arret_runtime::boxed;
use arret_runtime::boxed::prelude::*;
use arret_runtime::boxed::refs::Gc;
use arret_runtime::intern::InternedSym;
macro_rules! process_escaped_chars {
($w:ident, $source:ident, $( $pattern:pat => $escape:expr ),*) => {
// Try to write sequential unescaped characters in chunks
// This is especially important if $w isn't buffered
let mut last_escape_end = 0;
for (index, c) in $source.char_indices() {
match c {
$(
$pattern => {
$w.write_all(&$source.as_bytes()[last_escape_end..index])?;
last_escape_end = index + c.len_utf8();
($escape)?;
}
),* ,
_ => {}
};
}
$w.write_all(&$source.as_bytes()[last_escape_end..])?;
}
}
fn write_escaped_str(w: &mut dyn Write, source: &str) -> Result<()> {
process_escaped_chars!(w, source,
'\t' => write!(w, "\\t"),
'\r' => write!(w, "\\r"),
'\n' => write!(w, "\\n"),
'\\' => write!(w, "\\\\"),
'"' => write!(w, "\\\""),
c @ '\u{0}'..='\u{19}' => write!(w, "\\x{:X};", c as u32)
);
Ok(())
}
fn write_boxed_seq(
w: &mut dyn Write,
heap: &impl AsHeap,
elems: impl Iterator<Item = Gc<boxed::Any>>,
) -> Result<()> {
let mut has_prev = false;
for elem in elems {
if has_prev {
write!(w, " ")?;
} else {
has_prev = true;
}
write_boxed(w, heap, elem)?;
}
Ok(())
}
fn write_boxed_map(
w: &mut dyn Write,
heap: &impl AsHeap,
elems: impl Iterator<Item = (Gc<boxed::Any>, Gc<boxed::Any>)>,
) -> Result<()> {
write!(w, "{{")?;
let mut has_prev = false;
for (key, value) in elems {
if has_prev {
write!(w, ", ")?;
} else {
has_prev = true;
}
write_boxed(w, heap, key)?;
write!(w, " ")?;
write_boxed(w, heap, value)?;
}
write!(w, "}}")?;
Ok(())
}
fn write_char(w: &mut dyn Write, c: char) -> Result<()> {
match c {
'\n' => write!(w, "\\newline"),
'\r' => write!(w, "\\return"),
' ' => write!(w, "\\space"),
'\t' => write!(w, "\\tab"),
'\u{21}'..='\u{126}' => write!(w, "\\{}", c),
other => write!(w, "\\u{:04X}", other as u32),
}
}
#[allow(clippy::float_cmp)]
fn write_float(w: &mut dyn Write, f: f64) -> Result<()> {
if f.is_nan() {
write!(w, "##NaN")
} else if f.is_infinite() {
if f.is_sign_positive() {
write!(w, "##Inf")
} else {
write!(w, "##-Inf")
}
} else if f == 0.0 && f.is_sign_negative() {
write!(w, "-0.0")
} else if (f as i64 as f64) == f {
// This is has no fractional part; force a .0 to mark it as a float
write!(w, "{:.1}", f)
} else {
write!(w, "{:.}", f)
}
}
fn write_interned_sym(
w: &mut dyn Write,
heap: &impl AsHeap,
interned_sym: InternedSym,
) -> Result<()> {
// TODO: We don't support quoted/raw symbols as EDN doesn't
// This assumes the symbol is a valid identifier
write!(
w,
"{}",
heap.as_heap()
.type_info()
.interner()
.unintern(&interned_sym)
)
}
fn write_record(w: &mut dyn Write, heap: &impl AsHeap, record: &boxed::Record) -> Result<()> {
use boxed::FieldValue;
// TODO: Print our source name
write!(w, "#record(")?;
let mut has_prev = false;
for field in record.field_values(heap.as_heap()) {
if has_prev {
write!(w, " ")?;
} else {
has_prev = true;
}
match field {
FieldValue::Bool(true) => write!(w, "true")?,
FieldValue::Bool(false) => write!(w, "false")?,
FieldValue::Char(c) => write_char(w, c)?,
FieldValue::Float(f) => write_float(w, f)?,
FieldValue::Int(i) => write!(w, "{}", i)?,
FieldValue::InternedSym(interned_sym) => write_interned_sym(w, heap, interned_sym)?,
FieldValue::Boxed(boxed) => write_boxed(w, heap, boxed)?,
}
}
write!(w, ")")
}
/// Writes a representation of the passed box to the writer
pub fn write_boxed(w: &mut dyn Write, heap: &impl AsHeap, any_ref: Gc<boxed::Any>) -> Result<()> {
use arret_runtime::boxed::AnySubtype;
match any_ref.as_subtype() {
AnySubtype::True(_) => write!(w, "true"),
AnySubtype::False(_) => write!(w, "false"),
AnySubtype::Nil(_) => write!(w, "()"),
AnySubtype::Int(int_ref) => write!(w, "{}", int_ref.value()),
AnySubtype::Sym(sym) => write_interned_sym(w, heap, sym.interned()),
AnySubtype::Float(float_ref) => write_float(w, float_ref.value()),
AnySubtype::Pair(list) => {
write!(w, "(")?;
write_boxed_seq(w, heap, list.as_list_ref().iter())?;
write!(w, ")")
}
AnySubtype::Vector(vec) => {
write!(w, "[")?;
write_boxed_seq(w, heap, vec.iter())?;
write!(w, "]")
}
AnySubtype::Set(set) => {
write!(w, "#{{")?;
write_boxed_seq(w, heap, set.iter())?;
write!(w, "}}")
}
AnySubtype::Char(char_ref) => write_char(w, char_ref.value()),
AnySubtype::Str(s) => {
write!(w, "\"")?;
write_escaped_str(w, s.as_str())?;
write!(w, "\"")
}
AnySubtype::FunThunk(_) => write!(w, "#fn"),
AnySubtype::Record(record) => write_record(w, heap, record),
AnySubtype::Map(map) => write_boxed_map(w, heap, map.iter()),
}
}
/// Writes a pretty-printed representation of the passed box to the writer
pub fn pretty_print_boxed(write: &mut dyn Write, heap: &impl AsHeap, any_ref: Gc<boxed::Any>) {
match any_ref.as_subtype() {
boxed::AnySubtype::Str(string) => {
write.write_all(string.as_str().as_bytes()).unwrap();
}
boxed::AnySubtype::Char(c) => {
let mut buffer = [0; 4];
write
.write_all(c.value().encode_utf8(&mut buffer).as_bytes())
.unwrap();
}
boxed::AnySubtype::Sym(sym) => {
write
.write_all(sym.name(heap.as_heap()).as_bytes())
.unwrap();
}
_ => {
write_boxed(write, heap.as_heap(), any_ref).unwrap();
}
}
}
#[cfg(test)]
mod test {
use super::*;
fn string_for_boxed(heap: &boxed::Heap, any_ref: Gc<boxed::Any>) -> String {
use std::str;
let mut output_buf: Vec<u8> = vec![];
write_boxed(&mut output_buf, heap, any_ref).unwrap();
str::from_utf8(output_buf.as_slice()).unwrap().to_owned()
}
fn assert_write(heap: &mut boxed::Heap, expected: &'static str, any_ref: Gc<boxed::Any>) {
use crate::reader;
use arret_syntax::parser::datum_from_str;
let first_output = string_for_boxed(heap, any_ref);
assert_eq!(expected, first_output);
// Try to round trip this to make sure our output and tests are sane
let reparsed_syntax = datum_from_str(None, &first_output).unwrap();
let reboxed_ref = reader::box_syntax_datum(heap, &reparsed_syntax);
let second_output = string_for_boxed(heap, reboxed_ref);
assert_eq!(expected, second_output);
}
#[test]
fn bools() {
let mut heap = boxed::Heap::empty();
assert_write(&mut heap, "false", boxed::FALSE_INSTANCE.as_any_ref());
assert_write(&mut heap, "true", boxed::TRUE_INSTANCE.as_any_ref());
}
#[test]
fn ints() {
let mut heap = boxed::Heap::empty();
let boxed_zero = boxed::Int::new(&mut heap, 0);
assert_write(&mut heap, "0", boxed_zero.as_any_ref());
let boxed_positive = boxed::Int::new(&mut heap, 120);
assert_write(&mut heap, "120", boxed_positive.as_any_ref());
let boxed_negative = boxed::Int::new(&mut heap, -120);
assert_write(&mut heap, "-120", boxed_negative.as_any_ref());
}
#[test]
fn floats() {
let mut heap = boxed::Heap::empty();
let test_floats = [
("0.0", 0.0),
("-0.0", -0.0),
("120.0", 120.0),
("0.25", 0.25),
("-120.0", -120.0),
("9007199254740992.0", 9_007_199_254_740_992.0),
("##NaN", std::f64::NAN),
("##Inf", std::f64::INFINITY),
("##-Inf", std::f64::NEG_INFINITY),
];
for (expected, f) in &test_floats {
let boxed_float = boxed::Float::new(&mut heap, *f);
assert_write(&mut heap, expected, boxed_float.as_any_ref());
}
}
#[test]
fn sym() {
let mut heap = boxed::Heap::empty();
let boxed_foo = boxed::Sym::new(&mut heap, "foo");
assert_write(&mut heap, "foo", boxed_foo.as_any_ref());
let boxed_bar = boxed::Sym::new(&mut heap, "bar");
assert_write(&mut heap, "bar", boxed_bar.as_any_ref());
}
#[test]
fn lists() {
let mut heap = boxed::Heap::empty();
let empty_list = boxed::List::from_values(&mut heap, [].iter().cloned(), boxed::Int::new);
assert_write(&mut heap, "()", empty_list.as_any_ref());
let one_list = boxed::List::from_values(&mut heap, [1].iter().cloned(), boxed::Int::new);
assert_write(&mut heap, "(1)", one_list.as_any_ref());
let three_list =
boxed::List::from_values(&mut heap, [1, 2, 3].iter().cloned(), boxed::Int::new);
assert_write(&mut heap, "(1 2 3)", three_list.as_any_ref());
}
#[test]
fn vectors() {
let mut heap = boxed::Heap::empty();
let empty_vector =
boxed::Vector::from_values(&mut heap, [].iter().cloned(), boxed::Int::new);
assert_write(&mut heap, "[]", empty_vector.as_any_ref());
let one_vector =
boxed::Vector::from_values(&mut heap, [1].iter().cloned(), boxed::Int::new);
assert_write(&mut heap, "[1]", one_vector.as_any_ref());
let three_vector =
boxed::Vector::from_values(&mut heap, [1, 2, 3].iter().cloned(), boxed::Int::new);
assert_write(&mut heap, "[1 2 3]", three_vector.as_any_ref());
}
#[test]
fn chars() {
let mut heap = boxed::Heap::empty();
let test_chars = [
("\\newline", '\n'),
("\\return", '\r'),
("\\space", ' '),
("\\tab", '\t'),
("\\a", 'a'),
("\\A", 'A'),
("\\(", '('),
("\\u03BB", '\u{03bb}'),
];
for (expected, c) in &test_chars {
let boxed_char = boxed::Char::new(&mut heap, *c);
assert_write(&mut heap, expected, boxed_char.as_any_ref());
}
}
#[test]
fn strings() {
let mut heap = boxed::Heap::empty();
let test_strings = [
(r#""""#, ""),
(r#""Hello, world!""#, "Hello, world!"),
(r#""Hello\"World""#, "Hello\"World"),
(r#""Hello\\World""#, "Hello\\World"),
(r#""Tab\t""#, "Tab\t"),
(r#""\n\nnewline""#, "\n\nnewline"),
(r#""carriage: \r""#, "carriage: \r"),
(r#""lλ""#, "lλ"),
(r#""\x0;null!""#, "\u{0}null!"),
(
r#""The word \"recursion\" has many meanings.""#,
r#"The word "recursion" has many meanings."#,
),
];
for (expected, s) in &test_strings {
let boxed_char = boxed::Str::new(&mut heap, *s);
assert_write(&mut heap, expected, boxed_char.as_any_ref());
}
}
}
| true |
525316fedd0c8af67a2a59d43a0470799ebfcf60
|
Rust
|
jirutka/git-metafile
|
/src/git.rs
|
UTF-8
| 1,679 | 2.921875 | 3 |
[
"MIT"
] |
permissive
|
use std::collections::BTreeSet;
use std::ffi::OsStr;
use std::io;
use std::os::unix::ffi::OsStrExt;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::str;
pub fn repo_root() -> io::Result<PathBuf> {
let output = Command::new("git")
.args(["rev-parse", "--show-toplevel"])
.output()?;
let path = str::from_utf8(&output.stdout)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
.map(str::trim)
.map(PathBuf::from)?;
if path.is_dir() {
Ok(path)
} else {
Err(io::Error::new(
io::ErrorKind::InvalidData,
format!("directory {:?} does not exist", path),
))
}
}
pub fn staged_files() -> io::Result<BTreeSet<PathBuf>> {
let deleted_files = BTreeSet::from_iter(ls_files(&["--deleted"])?);
let mut paths = BTreeSet::new();
for mut path in ls_files(&[""; 0])? {
// Skip files that have been deleted from FS.
if deleted_files.contains(&path) {
continue;
}
// Insert also all intermediate directories.
loop {
paths.insert(path.clone());
if !path.pop() {
break;
}
}
}
paths.remove(Path::new(""));
Ok(paths)
}
fn ls_files<S: AsRef<OsStr>>(args: &[S]) -> io::Result<Vec<PathBuf>> {
let output = Command::new("git")
.args(["ls-files", "--full-name", "-z"])
.args(args)
.env("LC_ALL", "C")
.output()?;
let files = output
.stdout
.split(|b| *b == 0)
.map(OsStr::from_bytes)
.map(PathBuf::from)
.collect::<Vec<PathBuf>>();
Ok(files)
}
| true |
b19f2bc1e61f4e79cd541229fb38426f7d170eb2
|
Rust
|
lgarcia93/rust_tcp_server
|
/src/message/message.rs
|
UTF-8
| 3,466 | 3.453125 | 3 |
[] |
no_license
|
use std::net::{TcpStream};
use std::io::Write;
use std::ops::Deref;
#[derive(Debug)]
pub enum MessageType {
ListFiles,
GetFile,
Unknown,
}
pub struct MessageHeader {
pub message_type: MessageType,
pub content_size: u32,
}
pub struct Message {
pub header: MessageHeader,
pub content: Vec<u8>,
}
impl MessageHeader {
fn deserialize(data: Vec<u8>) -> MessageHeader {
MessageHeader {
message_type: MessageType::deserialize(data[1]),
content_size: decode_int32(&data[2..6]),
}
}
fn serialize(&self) -> Vec<u8> {
let mut serialized_message_header = vec![
0x7C as u8,
self.message_type.serialize(),
];
println!("Message type{}", self.message_type.serialize());
// Content size
serialized_message_header.extend_from_slice(&serialize_message_size(self.content_size));
serialized_message_header.push(0x7C);
serialized_message_header
}
}
impl Message {
fn serialize(&mut self) -> Vec<u8> {
let mut message = Vec::new();
message.push(0x1B as u8);
message.append(&mut self.header.serialize());
message.append(&mut self.content);
message.push(0x1B);
message
}
pub fn deserialize(data: Vec<u8>) -> Message {
let header_slice = &data[1..8];
Message{
header: MessageHeader::deserialize(header_slice.to_vec()),
content: data[8..data.len() -1].to_vec(),
}
}
fn message_size(&self) -> usize {
// 7 bytes header
// 2 bytes of escape char
// content-size bytes
9 + self.header.content_size as usize
}
pub fn decode_content_as_string(&self) -> String {
String::from(String::from_utf8_lossy(&self.content).deref())
}
pub fn send(&mut self, stream: &mut TcpStream) {
let mut written_bytes_count: usize = 0;
let serialized_message = self.serialize();
println!("Serialized message: {:?}", serialized_message);
let message = serialized_message.as_slice();
while match stream.write(&message[written_bytes_count..self.message_size()]) {
Ok(written_bytes) => {
if written_bytes > 0 {
written_bytes_count += written_bytes;
true
} else {
false
}
},
Err(_) => {
false
}
} {}
println!("Message sent");
}
}
impl MessageType {
fn deserialize(value: u8) -> MessageType {
println!("Deserialize message type {}", value);
match value {
1 => MessageType::ListFiles,
2 => MessageType::GetFile,
_ => MessageType::Unknown
}
}
fn serialize(&self) -> u8 {
match self {
Self::ListFiles => 1,
Self::GetFile => 2,
Self::Unknown => 3,
}
}
}
// Transform u32 into 4-byte slice
fn serialize_message_size(x: u32) -> [u8; 4] {
let b1: u8 = ((x >> 24) & 0xff) as u8;
let b2: u8 = ((x >> 16) & 0xff) as u8;
let b3: u8 = ((x >> 8) & 0xff) as u8;
let b4: u8 = (x & 0xff) as u8;
return [b1, b2, b3, b4];
}
fn decode_int32(int_bytes: &[u8]) -> u32 {
return ((int_bytes[0] as u32) << 24) + ((int_bytes[1] as u32) << 16) + ((int_bytes[2] as u32) << 8) + (int_bytes[3]) as u32;
}
| true |
40fbbeaba1965e3ed0f16ce524f5ee4fac5d0fb0
|
Rust
|
rnleach/metfor
|
/src/test_utils.rs
|
UTF-8
| 1,645 | 3.390625 | 3 |
[
"MIT"
] |
permissive
|
//! Utilities for running unit tests.
#![macro_use]
use crate::types::*;
use std::ops::Sub;
pub fn approx_equal<L, R>(left: L, right: R, tol: <L as Sub<R>>::Output) -> bool
where
L: Quantity + From<R> + Sub<R>,
R: Quantity,
<L as Sub<R>>::Output: Quantity + PartialOrd,
{
use std::f64;
assert!(tol.unpack() > 0.0);
let passes = <L as Sub<R>>::Output::pack(f64::abs((left - right).unpack())) <= tol;
if !passes {
println!("{:?} !~= {:?} within tolerance {:?}", left, right, tol);
}
passes
}
pub fn approx_lte<L, R, T>(a: L, b: R, tol: T) -> bool
where
L: Quantity + From<R> + Sub<R>,
R: Quantity,
T: Quantity,
<L as Sub<R>>::Output: PartialOrd<T> + Quantity,
{
let passes = (a - b) <= tol;
if !passes {
println!("{:?} !~<= {:?} within tolerance {:?}", a, b, tol);
}
passes
}
pub struct DRange {
start: f64,
step: f64,
stop: f64,
}
impl Iterator for DRange {
type Item = f64;
fn next(&mut self) -> Option<Self::Item> {
if self.step > 0.0 && self.start > self.stop {
None
} else if self.step < 0.0 && self.start < self.stop {
None
} else {
let next = self.start;
self.start += self.step;
Some(next)
}
}
}
pub fn pressure_levels() -> impl Iterator<Item = HectoPascal> {
DRange {
start: 1000.0,
step: -10.0,
stop: 100.0,
}
.map(HectoPascal)
}
pub fn temperatures() -> impl Iterator<Item = Celsius> {
DRange {
start: -100.0,
step: 10.0,
stop: 100.0,
}
.map(Celsius)
}
| true |
416dbad9554bd029815e6348b07d1fce248eb664
|
Rust
|
wieslander/aoc-2019
|
/src/bin/22-01.rs
|
UTF-8
| 1,518 | 3.390625 | 3 |
[] |
no_license
|
use regex::Regex;
use aoc::get_input;
enum Shuffle {
NewStack,
Cut(i32),
Deal(i32),
}
impl Shuffle {
pub fn from(line: &str) -> Shuffle {
let new_stack = Regex::new(r"^deal into new stack$").unwrap();
let cut = Regex::new(r"^cut (?P<count>-?[0-9]*)$").unwrap();
let deal = Regex::new(r"^deal with increment (?P<increment>[0-9]*)").unwrap();
if new_stack.is_match(line) {
return Shuffle::NewStack;
} else if cut.is_match(line) {
let caps = cut.captures(line).unwrap();
let count = caps.name("count").unwrap().as_str().parse().unwrap();
return Shuffle::Cut(count);
} else if deal.is_match(line) {
let caps = deal.captures(line).unwrap();
let inc = caps.name("increment").unwrap().as_str().parse().unwrap();
return Shuffle::Deal(inc);
}
panic!("Could not parse line {}", line);
}
}
fn main() {
let input = get_input();
let shuffles = input
.lines()
.map(|l| Shuffle::from(l));
let size = 10007;
let mut card = 2019;
for shuffle in shuffles {
match shuffle {
Shuffle::NewStack => {
card = (size - 1) - card;
},
Shuffle::Cut(pos) => {
card = (size + card - pos) % size;
},
Shuffle::Deal(increment) => {
card = (card * increment) % size;
}
}
}
println!("{}", card);
}
| true |
aa0598fb416d680ec2dd1fc2d95f94553d78b596
|
Rust
|
mverleg/number2name
|
/src/encode.rs
|
UTF-8
| 8,669 | 3.46875 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
use crate::{
signed2unsigned_128, signed2unsigned_16, signed2unsigned_32, signed2unsigned_64, Charset,
};
macro_rules! number2name_for_type {
($name: ident, $int:ty) => {
/// Convert a number to a short string representation using the given character set.
pub fn $name(number: impl Into<$int>, charset: &Charset) -> String {
let size = charset.len() as $int;
let mut remainder = number.into();
let mut name = Vec::new();
loop {
let index = remainder % size;
name.push(index as usize);
remainder /= size;
if remainder == 0 {
break;
}
remainder -= 1;
}
name.into_iter().map(|index| charset[index]).rev().collect()
}
};
}
number2name_for_type!(number2name_u16, u16);
number2name_for_type!(number2name_u32, u32);
number2name_for_type!(number2name_u64, u64);
number2name_for_type!(number2name_u128, u128);
pub fn number2name_i16(number: impl Into<i16>, charset: &Charset) -> String {
number2name_u16(signed2unsigned_16(number.into()), charset)
}
pub fn number2name_i32(number: impl Into<i32>, charset: &Charset) -> String {
number2name_u32(signed2unsigned_32(number.into()), charset)
}
pub fn number2name_i64(number: impl Into<i64>, charset: &Charset) -> String {
number2name_u64(signed2unsigned_64(number.into()), charset)
}
pub fn number2name_i128(number: impl Into<i128>, charset: &Charset) -> String {
number2name_u128(signed2unsigned_128(number.into()), charset)
}
/// Convert a number to a short string representation using the given character set.
pub fn number2name(number: impl Into<u64>, charset: &Charset) -> String {
// compiler, please inline this!
number2name_u64(number, charset)
}
#[cfg(test)]
mod general {
use super::*;
use crate::Charset;
#[test]
fn single_char_first() {
let charset = Charset::case_sensitive("aBcD");
let text = number2name(0u64, &charset);
assert_eq!(text, "a");
}
#[test]
fn single_char_last() {
let charset = Charset::case_sensitive("aBcD");
let text = number2name(4u64 - 1, &charset);
assert_eq!(text, "D");
}
#[test]
fn two_char_first() {
let charset = Charset::case_sensitive("aBcD");
let text = number2name(4u64, &charset);
assert_eq!(text, "aa");
}
#[test]
fn two_char_last() {
let charset = Charset::case_sensitive("aBcD");
let text = number2name(4u64 + 16 - 1, &charset);
assert_eq!(text, "DD");
}
#[test]
fn three_char_first() {
let charset = Charset::case_sensitive("aBcD");
let text = number2name(4u64 + 16, &charset);
assert_eq!(text, "aaa");
}
#[test]
fn three_char_last() {
let charset = Charset::case_sensitive("aBcD");
let text = number2name(4u64 + 16 + 64 - 1, &charset);
assert_eq!(text, "DDD");
}
#[test]
fn four_char_first() {
let charset = Charset::case_sensitive("aBcD");
let text = number2name(4u64 + 16 + 64, &charset);
assert_eq!(text, "aaaa");
}
#[test]
fn four_char_last() {
let charset = Charset::case_sensitive("aBcD");
let text = number2name(4u64 + 16 + 64 + 256 - 1, &charset);
assert_eq!(text, "DDDD");
}
#[test]
fn random_value() {
let charset = Charset::case_sensitive("aBcD");
let text = number2name(744u64, &charset);
assert_eq!(text, "BcBBa");
}
#[test]
fn large_charset() {
let charset = Charset::case_sensitive("aBcDeFgHiJkLmNoPqRsTuVwXyZ");
let text = number2name(744u64, &charset);
assert_eq!(text, "aBq");
}
#[test]
fn small_charset() {
let charset = Charset::case_sensitive("aB");
let text = number2name(744u64, &charset);
assert_eq!(text, "aBBBaBaBa");
}
#[test]
fn tiny_charset() {
let charset = Charset::case_sensitive("0");
let text = number2name(7u64, &charset);
assert_eq!(text, "00000000");
}
}
#[cfg(test)]
mod type_u16 {
use super::*;
use crate::Charset;
#[test]
fn unsigned() {
let charset = Charset::case_sensitive("aBcD");
let text = number2name_u16(4u16 + 16, &charset);
assert_eq!(text, "aaa");
}
#[test]
fn signed() {
let charset = Charset::case_sensitive("aBcD");
let text = number2name_i16(-13i16, &charset);
assert_eq!(text, "aBB");
}
#[test]
fn unsigned_maximum() {
let charset = Charset::case_sensitive("aBcDeFgHiJkLmNoPqRsTuVwXyZ");
let text = number2name_u16(std::u16::MAX, &charset);
assert_eq!(text, "cRXP");
}
#[test]
fn signed_maximum() {
let charset = Charset::case_sensitive("aBcDeFgHiJkLmNoPqRsTuVwXyZ");
let text = number2name_i16(std::i16::MAX, &charset);
assert_eq!(text, "cRXo");
}
#[test]
fn signed_minimum() {
let charset = Charset::case_sensitive("aBcDeFgHiJkLmNoPqRsTuVwXyZ");
let text = number2name_i16(std::i16::MIN, &charset);
assert_eq!(text, "cRXP");
}
}
#[cfg(test)]
mod type_u32 {
use super::*;
use crate::Charset;
#[test]
fn unsigned() {
let charset = Charset::case_sensitive("aBcD");
let text = number2name_u32(4u32 + 16, &charset);
assert_eq!(text, "aaa");
}
#[test]
fn signed() {
let charset = Charset::case_sensitive("aBcD");
let text = number2name_i32(-13i32, &charset);
assert_eq!(text, "aBB");
}
#[test]
fn unsigned_maximum() {
let charset = Charset::case_sensitive("aBcDeFgHiJkLmNoPqRsTuVwXyZ");
let text = number2name_u32(std::u32::MAX, &charset);
assert_eq!(text, "mwLqkwV");
}
#[test]
fn signed_maximum() {
let charset = Charset::case_sensitive("aBcDeFgHiJkLmNoPqRsTuVwXyZ");
let text = number2name_i32(std::i32::MAX, &charset);
assert_eq!(text, "mwLqkwu");
}
#[test]
fn signed_minimum() {
let charset = Charset::case_sensitive("aBcDeFgHiJkLmNoPqRsTuVwXyZ");
let text = number2name_i32(std::i32::MIN, &charset);
assert_eq!(text, "mwLqkwV");
}
}
#[cfg(test)]
mod type_u64 {
use super::*;
use crate::Charset;
#[test]
fn unsigned() {
let charset = Charset::case_sensitive("aBcD");
let text = number2name_u64(4u64 + 16, &charset);
assert_eq!(text, "aaa");
}
#[test]
fn signed() {
let charset = Charset::case_sensitive("aBcD");
let text = number2name_i64(-13i64, &charset);
assert_eq!(text, "aBB");
}
#[test]
fn unsigned_maximum() {
let charset = Charset::case_sensitive("aBcDeFgHiJkLmNoPqRsTuVwXyZ");
let text = number2name_u64(std::u64::MAX, &charset);
assert_eq!(text, "gkgwByLwRXTLPP");
}
#[test]
fn signed_maximum() {
let charset = Charset::case_sensitive("aBcDeFgHiJkLmNoPqRsTuVwXyZ");
let text = number2name_i64(std::i64::MAX, &charset);
assert_eq!(text, "gkgwByLwRXTLPo");
}
#[test]
fn signed_minimum() {
let charset = Charset::case_sensitive("aBcDeFgHiJkLmNoPqRsTuVwXyZ");
let text = number2name_i64(std::i64::MIN, &charset);
assert_eq!(text, "gkgwByLwRXTLPP");
}
}
#[cfg(test)]
mod type_u128 {
use super::*;
use crate::Charset;
#[test]
fn unsigned() {
let charset = Charset::case_sensitive("aBcD");
let text = number2name_u128(4u128 + 16u128, &charset);
assert_eq!(text, "aaa");
}
#[test]
fn signed() {
let charset = Charset::case_sensitive("aBcD");
let text = number2name_i128(-13i128, &charset);
assert_eq!(text, "aBB");
}
#[test]
fn unsigned_maximum() {
let charset = Charset::case_sensitive("aBcDeFgHiJkLmNoPqRsTuVwXyZ");
let text = number2name_u128(std::u128::MAX, &charset);
assert_eq!(text, "BcgDeNLqRqwDsLRugsNLBTmFiJaV");
}
#[test]
fn signed_maximum() {
let charset = Charset::case_sensitive("aBcDeFgHiJkLmNoPqRsTuVwXyZ");
let text = number2name_i128(std::i128::MAX, &charset);
assert_eq!(text, "BcgDeNLqRqwDsLRugsNLBTmFiJau");
}
#[test]
fn signed_minimum() {
let charset = Charset::case_sensitive("aBcDeFgHiJkLmNoPqRsTuVwXyZ");
let text = number2name_i128(std::i128::MIN, &charset);
assert_eq!(text, "BcgDeNLqRqwDsLRugsNLBTmFiJaV");
}
}
| true |
47256fd7320253f1eb89d9022cfb57c983ef23b9
|
Rust
|
rune-rs/rune
|
/crates/rune/src/modules/f64.rs
|
UTF-8
| 8,776 | 3.09375 | 3 |
[
"MIT",
"Apache-2.0"
] |
permissive
|
//! The `std::f64` module.
use core::cmp::Ordering;
use core::num::ParseFloatError;
use crate as rune;
use crate::runtime::{VmErrorKind, VmResult};
use crate::{ContextError, Module};
/// Install the core package into the given functions namespace.
pub fn module() -> Result<Module, ContextError> {
let mut m = Module::with_crate_item("std", ["f64"]);
m.function_meta(parse)?
.deprecated("Use std::string::parse::<f64> instead");
m.function_meta(is_nan)?;
m.function_meta(is_infinite)?;
m.function_meta(is_finite)?;
m.function_meta(is_subnormal)?;
m.function_meta(is_normal)?;
m.function_meta(max)?;
m.function_meta(min)?;
#[cfg(feature = "std")]
m.function_meta(abs)?;
#[cfg(feature = "std")]
m.function_meta(powf)?;
#[cfg(feature = "std")]
m.function_meta(powi)?;
m.function_meta(to_integer)?;
m.function_meta(partial_eq)?;
m.function_meta(eq)?;
m.function_meta(partial_cmp)?;
m.function_meta(cmp)?;
m.constant(["EPSILON"], f64::EPSILON)?;
m.constant(["MIN"], f64::MIN)?;
m.constant(["MAX"], f64::MAX)?;
m.constant(["MIN_POSITIVE"], f64::MIN_POSITIVE)?;
m.constant(["MIN_EXP"], f64::MIN_EXP)?;
m.constant(["MAX_EXP"], f64::MAX_EXP)?;
m.constant(["MIN_10_EXP"], f64::MIN_10_EXP)?;
m.constant(["MAX_10_EXP"], f64::MAX_10_EXP)?;
m.constant(["NAN"], f64::NAN)?;
m.constant(["INFINITY"], f64::INFINITY)?;
m.constant(["NEG_INFINITY"], f64::NEG_INFINITY)?;
Ok(m)
}
#[rune::function]
fn parse(s: &str) -> Result<f64, ParseFloatError> {
str::parse::<f64>(s)
}
/// Convert a float to a an integer.
///
/// # Examples
///
/// ```rune
/// let n = 7.0_f64.to::<i64>();
/// assert_eq!(n, 7);
/// ```
#[rune::function(instance, path = to::<i64>)]
fn to_integer(value: f64) -> i64 {
value as i64
}
/// Returns `true` if this value is NaN.
///
/// # Examples
///
/// ```rune
/// let nan = f64::NAN;
/// let f = 7.0_f64;
///
/// assert!(nan.is_nan());
/// assert!(!f.is_nan());
/// ```
#[rune::function(instance)]
fn is_nan(this: f64) -> bool {
this.is_nan()
}
/// Returns `true` if this value is positive infinity or negative infinity, and
/// `false` otherwise.
///
/// ```rune
/// let f = 7.0f64;
/// let inf = f64::INFINITY;
/// let neg_inf = f64::NEG_INFINITY;
/// let nan = f64::NAN;
///
/// assert!(!f.is_infinite());
/// assert!(!nan.is_infinite());
///
/// assert!(inf.is_infinite());
/// assert!(neg_inf.is_infinite());
/// ```
#[rune::function(instance)]
fn is_infinite(this: f64) -> bool {
this.is_infinite()
}
/// Returns `true` if this number is neither infinite nor NaN.
///
/// ```rune
/// let f = 7.0f64;
/// let inf = f64::INFINITY;
/// let neg_inf = f64::NEG_INFINITY;
/// let nan = f64::NAN;
///
/// assert!(f.is_finite());
///
/// assert!(!nan.is_finite());
/// assert!(!inf.is_finite());
/// assert!(!neg_inf.is_finite());
/// ```
#[rune::function(instance)]
fn is_finite(this: f64) -> bool {
this.is_finite()
}
/// Returns `true` if the number is [subnormal].
///
/// ```
/// let min = f64::MIN_POSITIVE; // 2.2250738585072014e-308_f64
/// let max = f64::MAX;
/// let lower_than_min = 1.0e-308_f64;
/// let zero = 0.0_f64;
///
/// assert!(!min.is_subnormal());
/// assert!(!max.is_subnormal());
///
/// assert!(!zero.is_subnormal());
/// assert!(!f64::NAN.is_subnormal());
/// assert!(!f64::INFINITY.is_subnormal());
/// // Values between `0` and `min` are Subnormal.
/// assert!(lower_than_min.is_subnormal());
/// ```
/// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
#[rune::function(instance)]
fn is_subnormal(this: f64) -> bool {
this.is_subnormal()
}
/// Returns `true` if the number is neither zero, infinite, [subnormal], or NaN.
///
/// ```rune
/// let min = f64::MIN_POSITIVE; // 2.2250738585072014e-308f64
/// let max = f64::MAX;
/// let lower_than_min = 1.0e-308_f64;
/// let zero = 0.0f64;
///
/// assert!(min.is_normal());
/// assert!(max.is_normal());
///
/// assert!(!zero.is_normal());
/// assert!(!f64::NAN.is_normal());
/// assert!(!f64::INFINITY.is_normal());
/// // Values between `0` and `min` are Subnormal.
/// assert!(!lower_than_min.is_normal());
/// ```
/// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
#[rune::function(instance)]
fn is_normal(this: f64) -> bool {
this.is_normal()
}
/// Returns the maximum of the two numbers, ignoring NaN.
///
/// If one of the arguments is NaN, then the other argument is returned. This
/// follows the IEEE 754-2008 semantics for maxNum, except for handling of
/// signaling NaNs; this function handles all NaNs the same way and avoids
/// maxNum's problems with associativity. This also matches the behavior of
/// libm’s fmax.
///
/// ```rune
/// let x = 1.0_f64;
/// let y = 2.0_f64;
///
/// assert_eq!(x.max(y), y);
/// ```
#[rune::function(instance)]
fn max(this: f64, other: f64) -> f64 {
this.max(other)
}
/// Returns the minimum of the two numbers, ignoring NaN.
///
/// If one of the arguments is NaN, then the other argument is returned. This
/// follows the IEEE 754-2008 semantics for minNum, except for handling of
/// signaling NaNs; this function handles all NaNs the same way and avoids
/// minNum's problems with associativity. This also matches the behavior of
/// libm’s fmin.
///
/// ```rune
/// let x = 1.0_f64;
/// let y = 2.0_f64;
///
/// assert_eq!(x.min(y), x);
/// ```
#[rune::function(instance)]
fn min(this: f64, other: f64) -> f64 {
this.min(other)
}
/// Computes the absolute value of `self`.
///
/// # Examples
///
/// ```
/// let x = 3.5_f64;
/// let y = -3.5_f64;
///
/// let abs_difference_x = (x.abs() - x).abs();
/// let abs_difference_y = (y.abs() - (-y)).abs();
///
/// assert!(abs_difference_x < 1e-10);
/// assert!(abs_difference_y < 1e-10);
///
/// assert!(f64::NAN.abs().is_nan());
/// ```
#[rune::function(instance)]
#[cfg(feature = "std")]
fn abs(this: f64) -> f64 {
this.abs()
}
/// Raises a number to a floating point power.
///
/// # Examples
///
/// ```rune
/// let x = 2.0_f64;
/// let abs_difference = (x.powf(2.0) - (x * x)).abs();
///
/// assert!(abs_difference < 1e-10);
/// ```
#[rune::function(instance)]
#[cfg(feature = "std")]
fn powf(this: f64, other: f64) -> f64 {
this.powf(other)
}
/// Raises a number to an integer power.
///
/// Using this function is generally faster than using `powf`. It might have a
/// different sequence of rounding operations than `powf`, so the results are
/// not guaranteed to agree.
///
/// # Examples
///
/// ```rune
/// let x = 2.0_f64;
/// let abs_difference = (x.powi(2) - (x * x)).abs();
///
/// assert!(abs_difference < 1e-10);
/// ```
#[rune::function(instance)]
#[cfg(feature = "std")]
fn powi(this: f64, other: i32) -> f64 {
this.powi(other)
}
/// Test two floats for partial equality.
///
/// # Examples
///
/// ```rune
/// assert!(5.0 == 5.0);
/// assert!(5.0 != 10.0);
/// assert!(10.0 != 5.0);
/// assert!(10.0 != f64::NAN);
/// assert!(f64::NAN != f64::NAN);
/// ```
#[rune::function(instance, protocol = PARTIAL_EQ)]
#[inline]
fn partial_eq(this: f64, rhs: f64) -> bool {
this.eq(&rhs)
}
/// Test two floats for total equality.
///
/// # Examples
///
/// ```rune
/// use std::ops::eq;
///
/// assert_eq!(eq(5.0, 5.0), true);
/// assert_eq!(eq(5.0, 10.0), false);
/// assert_eq!(eq(10.0, 5.0), false);
/// ```
#[rune::function(instance, protocol = EQ)]
#[inline]
fn eq(this: f64, rhs: f64) -> VmResult<bool> {
let Some(ordering) = this.partial_cmp(&rhs) else {
return VmResult::err(VmErrorKind::IllegalFloatComparison { lhs: this, rhs });
};
VmResult::Ok(matches!(ordering, Ordering::Equal))
}
/// Perform a partial ordered comparison between two floats.
///
/// # Examples
///
/// ```rune
/// use std::cmp::Ordering;
/// use std::ops::partial_cmp;
///
/// assert_eq!(partial_cmp(5.0, 10.0), Some(Ordering::Less));
/// assert_eq!(partial_cmp(10.0, 5.0), Some(Ordering::Greater));
/// assert_eq!(partial_cmp(5.0, 5.0), Some(Ordering::Equal));
/// assert_eq!(partial_cmp(5.0, f64::NAN), None);
/// ```
#[rune::function(instance, protocol = PARTIAL_CMP)]
#[inline]
fn partial_cmp(this: f64, rhs: f64) -> Option<Ordering> {
this.partial_cmp(&rhs)
}
/// Perform a partial ordered comparison between two floats.
///
/// # Examples
///
/// ```rune
/// use std::cmp::Ordering;
/// use std::ops::cmp;
///
/// assert_eq!(cmp(5.0, 10.0), Ordering::Less);
/// assert_eq!(cmp(10.0, 5.0), Ordering::Greater);
/// assert_eq!(cmp(5.0, 5.0), Ordering::Equal);
/// ```
#[rune::function(instance, protocol = CMP)]
#[inline]
fn cmp(this: f64, rhs: f64) -> VmResult<Ordering> {
let Some(ordering) = this.partial_cmp(&rhs) else {
return VmResult::err(VmErrorKind::IllegalFloatComparison { lhs: this, rhs });
};
VmResult::Ok(ordering)
}
| true |
89481e6472b9737107419ca678d18c54ef79f905
|
Rust
|
aDotInTheVoid/picoCTF-2019-writeup
|
/categorys/reversing/20-Times-Up-Again/solve/src/main.rs
|
UTF-8
| 2,804 | 3.015625 | 3 |
[] |
no_license
|
use std::io::*;
use std::process::*;
struct Solver<'a> {
pub prob: &'a [u8],
}
impl<'a> Solver<'a> {
fn new(prob: &'a [u8]) -> Self {
Self { prob }
}
fn peek(&self) -> u8 {
*self.prob.get(0).unwrap_or(&0)
}
fn get(&mut self) -> u8 {
let ret = self.peek();
self.prob = &self.prob[1..];
ret
}
fn number(&mut self) -> i64 {
let mut ret: i64 = (self.get() - b'0') as i64;
while self.peek() >= b'0' && self.peek() <= b'9' {
ret = 10 * ret + (self.get() - b'0') as i64;
}
ret
}
fn factor(&mut self) -> i64 {
if self.peek() >= b'0' && self.peek() <= b'9' {
self.number()
} else if self.peek() == b'(' {
self.get();
let ret = self.expr();
self.get();
ret
} else if self.peek() == b'-' {
self.get();
return -self.factor();
} else {
unreachable!(
"{},{}",
self.peek() as char,
std::str::from_utf8(self.prob).unwrap()
)
}
}
fn term(&mut self) -> i64 {
let mut res = self.factor();
while self.peek() == b'*' || self.peek() == b'/' {
if self.get() == b'*' {
res *= self.factor()
} else {
res /= self.factor()
}
}
res
}
fn expr(&mut self) -> i64 {
let mut res = self.term();
while self.peek() == b'+' || self.peek() == b'-' {
if self.get() == b'+' {
res += self.term()
} else {
res -= self.term()
}
}
res
}
}
//https://stackoverflow.com/questions/9329406/evaluating-arithmetic-expressions-from-string-in-c
const DIR: &str = "/problems/time-s-up--again-_6_3b092353ed59a3db99109f8c0f6f5cd0/";
const COMMAND: &str =
"/problems/time-s-up--again-_6_3b092353ed59a3db99109f8c0f6f5cd0/times-up-again";
fn main() {
let mut process = Command::new(COMMAND)
.current_dir(DIR)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap();
let answer = process.stdin.as_mut().unwrap();
let mut question = BufReader::new(process.stdout.as_mut().unwrap());
let mut buff = String::new();
question.read_line(&mut buff).unwrap();
let q = &buff["Challenge: ".len()..buff.len()];
let q = q.replace(" ", "");
let mut solver = Solver::new(q.as_bytes());
let mut ans = solver.expr().to_string();
ans.push('\n');
answer.write(ans.as_bytes());
question.read_line(&mut buff).unwrap();
question.read_line(&mut buff).unwrap();
println!("{}", buff);
}
| true |
290e8a3a0963f4589848ce46128ff1843c2074b7
|
Rust
|
glium/glium
|
/examples/shadow_mapping.rs
|
UTF-8
| 16,835 | 2.59375 | 3 |
[
"Apache-2.0"
] |
permissive
|
#[macro_use]
extern crate glium;
use cgmath::SquareMatrix;
use std::time::Instant;
use glium::{Surface, Display, VertexBuffer, IndexBuffer, Program, texture::DepthTexture2d};
use glutin::surface::WindowSurface;
use support::{ApplicationContext, State};
mod support;
fn create_box(display: &glium::Display<WindowSurface>) -> (glium::VertexBuffer<Vertex>, glium::IndexBuffer<u16>) {
let box_vertex_buffer = glium::VertexBuffer::new(display, &[
// Max X
Vertex { position: [ 0.5,-0.5,-0.5, 1.0], normal: [ 1.0, 0.0, 0.0, 0.0] },
Vertex { position: [ 0.5,-0.5, 0.5, 1.0], normal: [ 1.0, 0.0, 0.0, 0.0] },
Vertex { position: [ 0.5, 0.5, 0.5, 1.0], normal: [ 1.0, 0.0, 0.0, 0.0] },
Vertex { position: [ 0.5, 0.5,-0.5, 1.0], normal: [ 1.0, 0.0, 0.0, 0.0] },
// Min X
Vertex { position: [-0.5,-0.5,-0.5, 1.0], normal: [-1.0, 0.0, 0.0, 0.0] },
Vertex { position: [-0.5, 0.5,-0.5, 1.0], normal: [-1.0, 0.0, 0.0, 0.0] },
Vertex { position: [-0.5, 0.5, 0.5, 1.0], normal: [-1.0, 0.0, 0.0, 0.0] },
Vertex { position: [-0.5,-0.5, 0.5, 1.0], normal: [-1.0, 0.0, 0.0, 0.0] },
// Max Y
Vertex { position: [-0.5, 0.5,-0.5, 1.0], normal: [ 0.0, 1.0, 0.0, 0.0] },
Vertex { position: [ 0.5, 0.5,-0.5, 1.0], normal: [ 0.0, 1.0, 0.0, 0.0] },
Vertex { position: [ 0.5, 0.5, 0.5, 1.0], normal: [ 0.0, 1.0, 0.0, 0.0] },
Vertex { position: [-0.5, 0.5, 0.5, 1.0], normal: [ 0.0, 1.0, 0.0, 0.0] },
// Min Y
Vertex { position: [-0.5,-0.5,-0.5, 1.0], normal: [ 0.0,-1.0, 0.0, 0.0] },
Vertex { position: [-0.5,-0.5, 0.5, 1.0], normal: [ 0.0,-1.0, 0.0, 0.0] },
Vertex { position: [ 0.5,-0.5, 0.5, 1.0], normal: [ 0.0,-1.0, 0.0, 0.0] },
Vertex { position: [ 0.5,-0.5,-0.5, 1.0], normal: [ 0.0,-1.0, 0.0, 0.0] },
// Max Z
Vertex { position: [-0.5,-0.5, 0.5, 1.0], normal: [ 0.0, 0.0, 1.0, 0.0] },
Vertex { position: [-0.5, 0.5, 0.5, 1.0], normal: [ 0.0, 0.0, 1.0, 0.0] },
Vertex { position: [ 0.5, 0.5, 0.5, 1.0], normal: [ 0.0, 0.0, 1.0, 0.0] },
Vertex { position: [ 0.5,-0.5, 0.5, 1.0], normal: [ 0.0, 0.0, 1.0, 0.0] },
// Min Z
Vertex { position: [-0.5,-0.5,-0.5, 1.0], normal: [ 0.0, 0.0,-1.0, 0.0] },
Vertex { position: [ 0.5,-0.5,-0.5, 1.0], normal: [ 0.0, 0.0,-1.0, 0.0] },
Vertex { position: [ 0.5, 0.5,-0.5, 1.0], normal: [ 0.0, 0.0,-1.0, 0.0] },
Vertex { position: [-0.5, 0.5,-0.5, 1.0], normal: [ 0.0, 0.0,-1.0, 0.0] },
]).unwrap();
let mut indexes = Vec::new();
for face in 0..6u16 {
indexes.push(4 * face + 0);
indexes.push(4 * face + 1);
indexes.push(4 * face + 2);
indexes.push(4 * face + 0);
indexes.push(4 * face + 2);
indexes.push(4 * face + 3);
}
let box_index_buffer = glium::IndexBuffer::new(display, glium::index::PrimitiveType::TrianglesList, &indexes).unwrap();
(box_vertex_buffer, box_index_buffer)
}
#[derive(Clone, Copy, Debug)]
struct Vertex {
position: [f32; 4],
normal: [f32; 4],
}
implement_vertex!(Vertex, position, normal);
#[derive(Clone, Debug)]
struct ModelData {
model_matrix: cgmath::Matrix4<f32>,
depth_mvp: cgmath::Matrix4<f32>,
color: [f32; 4],
}
impl ModelData {
pub fn color(c: [f32; 3]) -> Self {
Self {
model_matrix: cgmath::Matrix4::identity(),
depth_mvp: cgmath::Matrix4::identity(),
color: [c[0], c[1], c[2], 1.0],
}
}
pub fn scale(mut self, s: f32) -> Self {
self.model_matrix = self.model_matrix * cgmath::Matrix4::from_scale(s);
self
}
pub fn translate(mut self, t: [f32; 3]) -> Self {
self.model_matrix = self.model_matrix * cgmath::Matrix4::from_translation(t.into());
self
}
}
#[derive(Clone, Copy, Debug)]
struct DebugVertex {
position: [f32; 2],
tex_coords: [f32; 2],
}
implement_vertex!(DebugVertex, position, tex_coords);
impl DebugVertex {
pub fn new(position: [f32; 2], tex_coords: [f32; 2]) -> Self {
Self {
position,
tex_coords,
}
}
}
struct Application {
pub start: Instant,
pub camera_t: f64,
pub camera_rotating: bool,
pub light_t: f64,
pub light_rotating: bool,
pub shadow_texture: DepthTexture2d,
pub model_vertex_buffer: VertexBuffer<Vertex>,
pub model_index_buffer: IndexBuffer<u16>,
pub shadow_map_shaders: Program,
pub render_shaders: Program,
pub debug_vertex_buffer: VertexBuffer<DebugVertex>,
pub debug_index_buffer: IndexBuffer<u16>,
pub debug_shadow_map_shaders: Program,
pub model_data: [ModelData; 4],
}
impl ApplicationContext for Application {
const WINDOW_TITLE:&'static str = "Glium shadow_mapping example";
fn new(display: &Display<WindowSurface>) -> Self {
let shadow_map_size = 1024;
// Create the boxes to render in the scene
let (model_vertex_buffer, model_index_buffer) = create_box(display);
let model_data = [
ModelData::color([0.4, 0.4, 0.4]).translate([0.0, -2.5, 0.0]).scale(5.0),
ModelData::color([0.6, 0.1, 0.1]).translate([0.0, 0.252, 0.0]).scale(0.5),
ModelData::color([0.1, 0.6, 0.1]).translate([0.9, 0.5, 0.1]).scale(0.5),
ModelData::color([0.1, 0.1, 0.6]).translate([-0.8, 0.75, 0.1]).scale(0.5),
];
let shadow_map_shaders = glium::Program::from_source(
display,
// Vertex Shader
"
#version 330 core
in vec4 position;
uniform mat4 depth_mvp;
void main() {
gl_Position = depth_mvp * position;
}
",
// Fragement Shader
"
#version 330 core
layout(location = 0) out float fragmentdepth;
void main(){
fragmentdepth = gl_FragCoord.z;
}
",
None).unwrap();
let render_shaders = glium::Program::from_source(
display,
// Vertex Shader
"
#version 330 core
uniform mat4 mvp;
uniform mat4 depth_bias_mvp;
uniform mat4 model_matrix;
uniform vec4 model_color;
in vec4 position;
in vec4 normal;
out vec4 shadow_coord;
out vec4 model_normal;
void main() {
gl_Position = mvp * position;
model_normal = model_matrix * normal;
shadow_coord = depth_bias_mvp * position;
}
",
// Fragement Shader
"
#version 330 core
uniform sampler2DShadow shadow_map;
uniform vec3 light_loc;
uniform vec4 model_color;
in vec4 shadow_coord;
in vec4 model_normal;
out vec4 color;
void main() {
vec3 light_color = vec3(1,1,1);
float bias = 0.0; // Geometry does not require bias
float lum = max(dot(normalize(model_normal.xyz), normalize(light_loc)), 0.0);
float visibility = texture(shadow_map, vec3(shadow_coord.xy, (shadow_coord.z-bias)/shadow_coord.w));
color = vec4(max(lum * visibility, 0.05) * model_color.rgb * light_color, 1.0);
}
",
None).unwrap();
// Debug Resources (for displaying shadow map)
let debug_vertex_buffer = glium::VertexBuffer::new(
display,
&[
DebugVertex::new([0.25, -1.0], [0.0, 0.0]),
DebugVertex::new([0.25, -0.25], [0.0, 1.0]),
DebugVertex::new([1.0, -0.25], [1.0, 1.0]),
DebugVertex::new([1.0, -1.0], [1.0, 0.0]),
],
).unwrap();
let debug_index_buffer = glium::IndexBuffer::new(
display,
glium::index::PrimitiveType::TrianglesList,
&[0u16, 1, 2, 0, 2, 3],
).unwrap();
let debug_shadow_map_shaders = glium::Program::from_source(
display,
// Vertex Shader
"
#version 140
in vec2 position;
in vec2 tex_coords;
out vec2 v_tex_coords;
void main() {
gl_Position = vec4(position, 0.0, 1.0);
v_tex_coords = tex_coords;
}
",
// Fragement Shader
"
#version 140
uniform sampler2D tex;
in vec2 v_tex_coords;
out vec4 f_color;
void main() {
f_color = vec4(texture(tex, v_tex_coords).rgb, 1.0);
}
",
None).unwrap();
let shadow_texture = glium::texture::DepthTexture2d::empty(display, shadow_map_size, shadow_map_size).unwrap();
let start = Instant::now();
let light_t: f64 = 8.7;
let light_rotating = false;
let camera_t: f64 = 8.22;
let camera_rotating = false;
Self {
start,
camera_t,
camera_rotating,
light_t,
light_rotating,
shadow_texture,
model_data,
model_vertex_buffer,
model_index_buffer,
shadow_map_shaders,
render_shaders,
debug_vertex_buffer,
debug_index_buffer,
debug_shadow_map_shaders,
}
}
fn handle_window_event(&mut self, event: &winit::event::WindowEvent, _window: &winit::window::Window) {
match event {
winit::event::WindowEvent::KeyboardInput { input, .. } => if input.state == winit::event::ElementState::Pressed {
if let Some(key) = input.virtual_keycode {
match key {
winit::event::VirtualKeyCode::C => self.camera_rotating = !self.camera_rotating,
winit::event::VirtualKeyCode::L => self.light_rotating = !self.light_rotating,
_ => {}
}
}
},
_ => return,
}
}
fn draw_frame(&mut self, display: &Display<WindowSurface>) {
// Rotate the light around the center of the scene
let light_loc = {
let x = 3.0 * self.light_t.cos();
let z = 3.0 * self.light_t.sin();
[x as f32, 5.0, z as f32]
};
// Render the scene from the light's point of view into depth buffer
// ===============================================================================
{
// Orthographic projection used to demostrate a far-away light source
let w = 4.0;
let depth_projection_matrix: cgmath::Matrix4<f32> = cgmath::ortho(-w, w, -w, w, -10.0, 20.0);
let view_center: cgmath::Point3<f32> = cgmath::Point3::new(0.0, 0.0, 0.0);
let view_up: cgmath::Vector3<f32> = cgmath::Vector3::new(0.0, 1.0, 0.0);
let depth_view_matrix = cgmath::Matrix4::look_at_rh(light_loc.into(), view_center, view_up);
let mut draw_params: glium::draw_parameters::DrawParameters<'_> = Default::default();
draw_params.depth = glium::Depth {
test: glium::draw_parameters::DepthTest::IfLessOrEqual,
write: true,
..Default::default()
};
draw_params.backface_culling = glium::BackfaceCullingMode::CullClockwise;
// Write depth to shadow map texture
let mut target = glium::framebuffer::SimpleFrameBuffer::depth_only(display, &self.shadow_texture).unwrap();
target.clear_color(1.0, 1.0, 1.0, 1.0);
target.clear_depth(1.0);
// Draw each model
for md in &mut self.model_data {
let depth_mvp = depth_projection_matrix * depth_view_matrix * md.model_matrix;
md.depth_mvp = depth_mvp;
let uniforms = uniform! {
depth_mvp: Into::<[[f32; 4]; 4]>::into(depth_mvp),
};
target.draw(
&self.model_vertex_buffer,
&self.model_index_buffer,
&self.shadow_map_shaders,
&uniforms,
&draw_params,
).unwrap();
}
}
// Render the scene from the camera's point of view
// ===============================================================================
let (width, height) = display.get_framebuffer_dimensions();
let screen_ratio = (width / height) as f32;
let perspective_matrix: cgmath::Matrix4<f32> = cgmath::perspective(cgmath::Deg(45.0), screen_ratio, 0.0001, 100.0);
let camera_x = 3.0 * self.camera_t.cos();
let camera_z = 3.0 * self.camera_t.sin();
let view_eye: cgmath::Point3<f32> = cgmath::Point3::new(camera_x as f32, 2.0, camera_z as f32);
let view_center: cgmath::Point3<f32> = cgmath::Point3::new(0.0, 0.0, 0.0);
let view_up: cgmath::Vector3<f32> = cgmath::Vector3::new(0.0, 1.0, 0.0);
let view_matrix: cgmath::Matrix4<f32> = cgmath::Matrix4::look_at_rh(view_eye, view_center, view_up);
let bias_matrix: cgmath::Matrix4<f32> = [
[0.5, 0.0, 0.0, 0.0],
[0.0, 0.5, 0.0, 0.0],
[0.0, 0.0, 0.5, 0.0],
[0.5, 0.5, 0.5, 1.0],
].into();
let mut draw_params: glium::draw_parameters::DrawParameters<'_> = Default::default();
draw_params.depth = glium::Depth {
test: glium::draw_parameters::DepthTest::IfLessOrEqual,
write: true,
..Default::default()
};
draw_params.backface_culling = glium::BackfaceCullingMode::CullCounterClockwise;
draw_params.blend = glium::Blend::alpha_blending();
let mut target = display.draw();
target.clear_color_and_depth((0.0, 0.0, 0.0, 0.0), 1.0);
// Draw each model
for md in &self.model_data {
let mvp = perspective_matrix * view_matrix * md.model_matrix;
let depth_bias_mvp = bias_matrix * md.depth_mvp;
let uniforms = uniform! {
light_loc: light_loc,
perspective_matrix: Into::<[[f32; 4]; 4]>::into(perspective_matrix),
view_matrix: Into::<[[f32; 4]; 4]>::into(view_matrix),
model_matrix: Into::<[[f32; 4]; 4]>::into(md.model_matrix),
model_color: md.color,
mvp: Into::<[[f32;4];4]>::into(mvp),
depth_bias_mvp: Into::<[[f32;4];4]>::into(depth_bias_mvp),
shadow_map: glium::uniforms::Sampler::new(&self.shadow_texture)
.magnify_filter(glium::uniforms::MagnifySamplerFilter::Nearest)
.minify_filter(glium::uniforms::MinifySamplerFilter::Nearest)
.depth_texture_comparison(Some(glium::uniforms::DepthTextureComparison::LessOrEqual)),
};
target.draw(
&self.model_vertex_buffer,
&self.model_index_buffer,
&self.render_shaders,
&uniforms,
&draw_params,
).unwrap();
}
{
let uniforms = uniform! {
tex: glium::uniforms::Sampler::new(&self.shadow_texture)
.magnify_filter(glium::uniforms::MagnifySamplerFilter::Nearest)
.minify_filter(glium::uniforms::MinifySamplerFilter::Nearest)
};
target.clear_depth(1.0);
target
.draw(
&self.debug_vertex_buffer,
&self.debug_index_buffer,
&self.debug_shadow_map_shaders,
&uniforms,
&Default::default(),
)
.unwrap();
}
target.finish().unwrap();
}
fn update(&mut self) {
let elapsed_dur = self.start.elapsed();
let secs = (elapsed_dur.as_secs() as f64) + (elapsed_dur.subsec_nanos() as f64) * 1e-9;
self.start = Instant::now();
if self.camera_rotating { self.camera_t += secs * 0.7; }
if self.light_rotating { self.light_t += secs * 0.7; }
}
}
fn main() {
println!("This example demonstrates real-time shadow mapping. Press C to toggle camera");
println!("rotation; press L to toggle light rotation.");
State::<Application>::run_loop();
}
| true |
df9e2af118a9ec7bc2add2f46def5150401d2bfb
|
Rust
|
foriequal0/advent-of-code-2019
|
/src/bin/03-a.rs
|
UTF-8
| 3,178 | 3.484375 | 3 |
[] |
no_license
|
use std::collections::HashSet;
use std::error::Error;
use std::io;
use std::io::prelude::*;
use std::str::FromStr;
type BoxedError = Box<dyn Error + 'static>;
type Result<T> = std::result::Result<T, BoxedError>;
enum Direction {
R,
L,
D,
U,
}
struct Segment {
direction: Direction,
distance: u32,
}
impl FromStr for Segment {
type Err = BoxedError;
fn from_str(s: &str) -> Result<Segment> {
let direction = match s.chars().nth(0).ok_or("No direction")? {
'R' => Direction::R,
'L' => Direction::L,
'D' => Direction::D,
'U' => Direction::U,
_ => unreachable!(),
};
let distance = s.get(1..).ok_or("No distance")?.parse::<u32>()?;
Ok(Segment {
direction,
distance,
})
}
}
fn get_wires<R: BufRead>(read: R) -> Result<(Vec<Segment>, Vec<Segment>)> {
fn get_wire(line: &str) -> Result<Vec<Segment>> {
line.split(',').map(Segment::from_str).collect()
}
let mut lines = read.lines();
let line1 = lines.next().expect("No first line")?;
let line2 = lines.next().expect("No second line")?;
Ok((get_wire(&line1)?, (get_wire(&line2)?)))
}
#[derive(Eq, PartialEq, Hash, Clone, Copy, Default)]
struct Cursor {
x: i32,
y: i32,
}
struct WireIterator<'a> {
cursor: Cursor,
segments: &'a [Segment],
distance: u32,
}
impl<'a> WireIterator<'a> {
fn new(segments: &'a [Segment]) -> Self {
Self {
segments,
cursor: Default::default(),
distance: 0,
}
}
}
impl<'a> Iterator for WireIterator<'a> {
type Item = Cursor;
fn next(&mut self) -> Option<Self::Item> {
let current = self.segments.get(0)?;
match current.direction {
Direction::R => {
self.cursor.x += 1;
}
Direction::L => {
self.cursor.x -= 1;
}
Direction::D => {
self.cursor.y += 1;
}
Direction::U => {
self.cursor.y -= 1;
}
}
self.distance += 1;
if current.distance == self.distance {
self.segments = &self.segments[1..];
self.distance = 0;
}
Some(self.cursor)
}
}
fn find_closest_intersection(wire1: Vec<Segment>, wire2: Vec<Segment>) -> Result<i32> {
let mut buf = HashSet::new();
for cursor in WireIterator::new(&wire1) {
buf.insert(cursor);
}
let mut min_distance = std::i32::MAX;
for cursor in WireIterator::new(&wire2) {
if buf.contains(&cursor) {
min_distance = min_distance.min(cursor.x.abs() + cursor.y.abs())
}
}
Ok(min_distance)
}
fn run<R: BufRead>(read: R) -> Result<i32> {
let (line1, line2) = get_wires(read)?;
find_closest_intersection(line1, line2)
}
fn main() -> Result<()> {
let stdin = io::stdin();
let result = run(stdin.lock())?;
println!("result: {}", result);
Ok(())
}
#[test]
fn test() {
let input = include_bytes!("../../input/03");
assert_eq!(run(&input[..]).ok(), Some(375));
}
| true |
bf053b301f17f4b2ec022d8a344706fcedd734d1
|
Rust
|
cawfeecoder/travs
|
/src/authenticator.rs
|
UTF-8
| 14,398 | 2.84375 | 3 |
[] |
no_license
|
use serde_json::json;
use std::fmt::{Formatter, Display};
use once_cell::sync::OnceCell;
use crate::db;
use std::collections::HashMap;
use serde_derive::{Deserialize, Serialize};
use failure_derive::*;
use crate::entity::{Entity, EntityStore, EntityError};
use crate::identifier::{Identifier, IdentifierStore, IdentifierType, IdentifierError};
use crate::system::{System, SystemStore};
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct AuthenticatorRoot {
pub authenticator: Vec<Authenticator>
}
#[derive(Debug, Fail)]
pub enum AuthenticatorError {
#[fail(display = "An authenticator with of this type exists and is associated to this identity")]
AuthenticatorExists(),
#[fail(display = "Field {} cannot be empty", 0)]
EmptyField(String),
#[fail(display = "Authenticator type does not match the identifier type being associated")]
AuthTypeIdentTypeMisMatch(),
#[fail(display = "Cannot extract authenticator value from an empty array or None value")]
Empty(),
#[fail(display = "Authenticator with uid does not exist")]
DoesNotExist(),
}
impl From<String> for AuthenticatorError {
fn from(e: String) -> Self {
AuthenticatorError::EmptyField(e)
}
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub enum AuthenticatorType {
username_password,
phone_password,
email_password,
public_key_authentication
}
impl Display for AuthenticatorType {
fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
write!(f, "{:?}", self)
}
}
#[derive(Serialize, Deserialize, Debug, Clone, Default)]
pub struct Authenticator {
pub uid: Option<String>,
#[serde(rename = "identifier")]
pub identifiers: Option<Vec<Identifier>>,
#[serde(rename = "entity")]
pub entities: Option<Vec<Entity>>,
#[serde(rename = "system")]
pub systems: Option<Vec<System>>,
pub authenticator_type: Option<AuthenticatorType>,
pub value: Option<String>,
#[serde(rename = "dgraph.type")]
pub dtype: Option<Vec<String>>
}
impl Authenticator {
pub fn new() -> Authenticator {
Authenticator {
dtype: Some(vec!["Authenticator".to_string()]),
..Default::default()
}
}
pub fn uid(mut self, uid: String) -> Self {
self.uid = Some(uid);
self
}
pub fn authenticator_type(mut self, authenticator_type: AuthenticatorType) -> Self {
self.authenticator_type = Some(authenticator_type);
self
}
pub fn add_identifier(mut self, identifier: Identifier) -> Self {
if self.identifiers.is_none() {
self.identifiers = Some(vec![])
}
let mut curr_ident = self.identifiers.unwrap();
curr_ident.push(identifier);
self.identifiers = Some(curr_ident);
self
}
pub fn add_entity(mut self, entity: Entity) -> Self {
if self.entities.is_none() {
self.entities = Some(vec![])
}
let mut curr_ents = self.entities.unwrap();
curr_ents.push(entity);
self.entities = Some(curr_ents);
self
}
pub fn add_system(mut self, s: System) -> Self {
if self.systems.is_none() {
self.systems = Some(vec![])
}
let mut curr_sys = self.systems.unwrap();
curr_sys.push(s);
self.systems = Some(curr_sys);
self
}
pub fn value(mut self, value: String) -> Self {
self.value = Some(value);
self
}
pub fn validate(&mut self) -> bool {
if self.entities.is_none() || self.identifiers.is_none() {
return false
}
return self.authenticator_type.is_some() && self.value.is_some()
}
}
pub struct AuthenticatorStore {}
static TEMPLATE_ENGINE_AUTH_STORE: OnceCell<handlebars::Handlebars> = OnceCell::new();
impl AuthenticatorStore {
pub fn _validate_authenticator_type(auth_type: &AuthenticatorType, ident_type: &IdentifierType) -> bool {
return match auth_type {
AuthenticatorType::phone_password => {
ident_type == &IdentifierType::phone
},
AuthenticatorType::public_key_authentication => {
ident_type == &IdentifierType::public_key
},
AuthenticatorType::email_password => {
ident_type == &IdentifierType::email
},
AuthenticatorType::username_password => {
ident_type == &IdentifierType::username
}
}
}
pub fn create(a: Authenticator, fields: Vec<String>) -> Result<Option<Authenticator>, failure::Error> {
let create_auth_type = a.clone()
.authenticator_type
.ok_or(AuthenticatorError::EmptyField("authenticator_type".to_string()))?.clone();
let mut create_auth_ident = a.clone().
identifiers.
ok_or(AuthenticatorError::Empty())?
.clone()
.get(0)
.ok_or(AuthenticatorError::Empty())?
.clone();
if !Self::_validate_authenticator_type(&a.clone()
.authenticator_type
.ok_or(AuthenticatorError::Empty())?
, &create_auth_ident.clone().identifier_type.ok_or(AuthenticatorError::Empty())?
) {
return Err(AuthenticatorError::AuthTypeIdentTypeMisMatch().into())
}
if !EntityStore::exists(
a.clone().entities
.ok_or(AuthenticatorError::Empty())?
.get(0)
.ok_or(AuthenticatorError::Empty())?
.uid.as_ref().ok_or(AuthenticatorError::Empty())?
) {
return Err(AuthenticatorError::DoesNotExist().into())
}
if !IdentifierStore::exists(
&a.clone().identifiers
.ok_or(AuthenticatorError::Empty())?
.get(0)
.ok_or(AuthenticatorError::Empty())?
.uid.as_ref().ok_or(AuthenticatorError::Empty())?
) {
return Err(AuthenticatorError::DoesNotExist().into())
}
if create_auth_ident.identifier_type.is_none() {
create_auth_ident = IdentifierStore::find_by_uid(
&create_auth_ident.uid.ok_or(AuthenticatorError::Empty())?,
vec!["uid".to_string(),
"identifier_type".to_string()])?.ok_or(AuthenticatorError::Empty()
)?
}
let exists = Self::find_by_type_identifier(
&create_auth_type,
&create_auth_ident,
vec!["uid".to_string()]
)?;
if exists.is_some() {
return Err(AuthenticatorError::AuthenticatorExists().into())
}
if a.clone().validate() {
let res = db::save(serde_json::to_vec(&a)?)?;
let mut ass = a.clone();
for (_, uid) in res.uids {
ass.uid = Some(uid);
break;
}
EntityStore::associate_authenticator(a.clone().entities
.ok_or(AuthenticatorError::Empty())?
.get(0)
.ok_or(AuthenticatorError::Empty())?
.uid.as_ref().ok_or(AuthenticatorError::Empty())?
, ass.clone(), vec!["uid".to_string()]);
SystemStore::associate_authenticator(a.clone().systems
.ok_or(AuthenticatorError::Empty())?
.get(0)
.ok_or(AuthenticatorError::Empty())?
.guid.as_ref().ok_or(AuthenticatorError::Empty())?
, ass.clone(), vec!["uid".to_string()]);
IdentifierStore::associate_authenticator(a.clone().identifiers
.ok_or(AuthenticatorError::Empty())?
.get(0)
.ok_or(AuthenticatorError::Empty())?
.uid.as_ref().ok_or(AuthenticatorError::Empty())?
, ass.clone(), vec!["uid".to_string()]);
return Self::find_by_type_identifier(&create_auth_type, &create_auth_ident, fields)
}
Err(AuthenticatorError::AuthenticatorExists().into())
}
pub fn associate_system(uid: &str, s: System, fields: Vec<String>) -> Result<Option<Authenticator>, failure::Error> {
let res = Self::find_by_uid(uid, vec!["uid".to_string(), "system { uid }".to_string()])?;
if res.is_none() {
return Err(EntityError::DoesNotExist().into())
}
let update: Authenticator = res.clone().ok_or(AuthenticatorError::Empty())?.add_system(s);
db::save(serde_json::to_vec(&update)?)?;
return Self::find_by_uid(uid, fields);
}
pub fn associate_identifier(uid: &str, s: Identifier, fields: Vec<String>) -> Result<Option<Authenticator>, failure::Error> {
let res = Self::find_by_uid(uid, vec!["uid".to_string(), "system { uid }".to_string()])?;
if res.is_none() {
return Err(EntityError::DoesNotExist().into())
}
let update: Authenticator = res.clone().ok_or(AuthenticatorError::Empty())?.add_identifier(s);
db::save(serde_json::to_vec(&update)?)?;
return Self::find_by_uid(uid, fields);
}
pub fn find_by_type_identifier(authenticator_type: &AuthenticatorType, i: &Identifier, fields: Vec<String>) -> Result<Option<Authenticator>, failure::Error> {
if i.uid.is_none() {
return Err(AuthenticatorError::EmptyField("uid".to_string()).into())
}
let reg = TEMPLATE_ENGINE_AUTH_STORE.get_or_init(|| {
handlebars::Handlebars::new()
});
let req: &'static str = r#"
query authenticator($type: string, $uid: string) {
authenticator(func: eq(authenticator_type, $type)) @filter(eq(dgraph.type, "Authenticator")) {
{{#each fields }}
{{this}}
{{/each}}
_: identifier @filter(uid($uid)) {
uid
}
}
}
"#;
let template_vars = &json!({
"fields": fields
});
let query = reg.render_template(req, template_vars)?;
let mut vars: HashMap<String, String> = [
("$type".to_string(), authenticator_type.to_string()),
("$uid".to_string(), format!("{}", i.uid.as_ref().ok_or(AuthenticatorError::Empty())?))
].iter().cloned().collect();
let res = db::query(query, vars)?;
let e: AuthenticatorRoot = serde_json::from_slice(&res.json)?;
match e.authenticator.len() {
0 => Ok(None),
_ => Ok(Some(e.authenticator.get(0).ok_or(AuthenticatorError::Empty())?.clone()))
}
}
pub fn login(a: Authenticator, i: Identifier, s: System) -> Result<bool, failure::Error> {
let reg = TEMPLATE_ENGINE_AUTH_STORE.get_or_init(|| {
handlebars::Handlebars::new()
});
let req: &'static str = r#"
query authenticator($auth_type: string, $ident_type: string, $ident_value: string, $sys_guid: string) {
identifier(func: eq(identifier_type, $ident_type)) @filter(eq(value, $ident_value)) {
A as authenticator @filter(eq(authenticator_type, $auth_type))
}
authenticator(func: uid(A)) {
value
system @filter(eq(guid, $sys_guid)) {
uid
}
}
}
"#;
let template_vars = &json!({});
let query = reg.render_template(req, template_vars)?;
let mut vars: HashMap<String, String> = [
("$auth_type".to_string(), format!("{}", a.authenticator_type.as_ref().ok_or(AuthenticatorError::Empty())?)),
("$ident_type".to_string(), format!("{}", i.identifier_type.as_ref().ok_or(AuthenticatorError::Empty())?)),
("$ident_value".to_string(), format!("{}", i.value.as_ref().ok_or(AuthenticatorError::Empty())?)),
("$sys_guid".to_string(), format!("{}", s.guid.as_ref().ok_or(AuthenticatorError::Empty())?))
].iter().cloned().collect();
let res = db::query(query, vars)?;
let e: AuthenticatorRoot = serde_json::from_slice(&res.json)?;
match e.authenticator.len() {
0 => return Ok(false),
_ => {
let extracted_auth = e.authenticator.get(0).ok_or(AuthenticatorError::Empty())?.clone();
if extracted_auth.systems.is_none() {
return Ok(false)
}
let cmp = argon2::verify_encoded(extracted_auth.value.unwrap().as_str(), a.clone().value.unwrap().as_bytes());
match cmp {
Ok(v) => {
Ok(v)
}
Err(e) => {
Err(e.into())
}
}
}
}
}
pub fn find_by_uid(uid: &str, fields: Vec<String>) -> Result<Option<Authenticator>, failure::Error> {
let reg = TEMPLATE_ENGINE_AUTH_STORE.get_or_init(|| {
handlebars::Handlebars::new()
});
let req: &'static str = r#"
query authenticator($uid: string) {
authenticator(func: uid($uid)) @filter(eq(dgraph.type, "Authenticator")) {
{{#each fields }}
{{this}}
{{/each}}
}
}
"#;
let template_vars = &json!({
"fields": fields
});
let query = reg.render_template(req, template_vars)?;
let mut vars: HashMap<String, String> = [
("$uid".to_string(), uid.to_string())
].iter().cloned().collect();
let res = db::query(query, vars)?;
let e: AuthenticatorRoot = serde_json::from_slice(&res.json)?;
match e.authenticator.len() {
0 => Ok(None),
_ => Ok(Some(e.authenticator.get(0).ok_or(AuthenticatorError::Empty())?.clone()))
}
}
}
| true |
a48afd539a71a91f2c9b8f439c93d87a968aa572
|
Rust
|
JamesMcGuigan/ecosystem-research
|
/rust/rust-crash-course/src/vars.rs
|
UTF-8
| 569 | 3.6875 | 4 |
[
"MIT"
] |
permissive
|
// Source: https://stackoverflow.com/questions/21747136/how-do-i-print-the-type-of-a-variable-in-rust?answertab=votes#tab-top
fn type_of<T>(_: &T) -> String {
return format!("{}", std::any::type_name::<T>())
}
pub fn run() {
let name = "James";
let mut age: f64 = 37.0;
age = age + 1.0 / (2 as f64);
println!("My name is {} and I am {} years old", name, age);
const ID: i128 = 001;
println!("ID: {} ({})", ID, type_of(&ID));
let (thing_1, thing_2) = ("Hello", "World");
println!("thing_1 = {} | thing_2 = {}", thing_1, thing_2);
}
| true |
8e8edbf5ca5ea382861694eb94f280143c7f4ad5
|
Rust
|
rust-lang/stdarch
|
/crates/core_arch/src/x86/sse3.rs
|
UTF-8
| 8,920 | 2.640625 | 3 |
[
"Apache-2.0",
"MIT",
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
//! Streaming SIMD Extensions 3 (SSE3)
use crate::{
core_arch::{simd::*, simd_llvm::simd_shuffle, x86::*},
mem::transmute,
};
#[cfg(test)]
use stdarch_test::assert_instr;
/// Alternatively add and subtract packed single-precision (32-bit)
/// floating-point elements in `a` to/from packed elements in `b`.
///
/// [Intel's documentation](https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_addsub_ps)
#[inline]
#[target_feature(enable = "sse3")]
#[cfg_attr(test, assert_instr(addsubps))]
#[stable(feature = "simd_x86", since = "1.27.0")]
pub unsafe fn _mm_addsub_ps(a: __m128, b: __m128) -> __m128 {
addsubps(a, b)
}
/// Alternatively add and subtract packed double-precision (64-bit)
/// floating-point elements in `a` to/from packed elements in `b`.
///
/// [Intel's documentation](https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_addsub_pd)
#[inline]
#[target_feature(enable = "sse3")]
#[cfg_attr(test, assert_instr(addsubpd))]
#[stable(feature = "simd_x86", since = "1.27.0")]
pub unsafe fn _mm_addsub_pd(a: __m128d, b: __m128d) -> __m128d {
addsubpd(a, b)
}
/// Horizontally adds adjacent pairs of double-precision (64-bit)
/// floating-point elements in `a` and `b`, and pack the results.
///
/// [Intel's documentation](https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_hadd_pd)
#[inline]
#[target_feature(enable = "sse3")]
#[cfg_attr(test, assert_instr(haddpd))]
#[stable(feature = "simd_x86", since = "1.27.0")]
pub unsafe fn _mm_hadd_pd(a: __m128d, b: __m128d) -> __m128d {
haddpd(a, b)
}
/// Horizontally adds adjacent pairs of single-precision (32-bit)
/// floating-point elements in `a` and `b`, and pack the results.
///
/// [Intel's documentation](https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_hadd_ps)
#[inline]
#[target_feature(enable = "sse3")]
#[cfg_attr(test, assert_instr(haddps))]
#[stable(feature = "simd_x86", since = "1.27.0")]
pub unsafe fn _mm_hadd_ps(a: __m128, b: __m128) -> __m128 {
haddps(a, b)
}
/// Horizontally subtract adjacent pairs of double-precision (64-bit)
/// floating-point elements in `a` and `b`, and pack the results.
///
/// [Intel's documentation](https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_hsub_pd)
#[inline]
#[target_feature(enable = "sse3")]
#[cfg_attr(test, assert_instr(hsubpd))]
#[stable(feature = "simd_x86", since = "1.27.0")]
pub unsafe fn _mm_hsub_pd(a: __m128d, b: __m128d) -> __m128d {
hsubpd(a, b)
}
/// Horizontally adds adjacent pairs of single-precision (32-bit)
/// floating-point elements in `a` and `b`, and pack the results.
///
/// [Intel's documentation](https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_hsub_ps)
#[inline]
#[target_feature(enable = "sse3")]
#[cfg_attr(test, assert_instr(hsubps))]
#[stable(feature = "simd_x86", since = "1.27.0")]
pub unsafe fn _mm_hsub_ps(a: __m128, b: __m128) -> __m128 {
hsubps(a, b)
}
/// Loads 128-bits of integer data from unaligned memory.
/// This intrinsic may perform better than `_mm_loadu_si128`
/// when the data crosses a cache line boundary.
///
/// [Intel's documentation](https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_lddqu_si128)
#[inline]
#[target_feature(enable = "sse3")]
#[cfg_attr(test, assert_instr(lddqu))]
#[stable(feature = "simd_x86", since = "1.27.0")]
pub unsafe fn _mm_lddqu_si128(mem_addr: *const __m128i) -> __m128i {
transmute(lddqu(mem_addr as *const _))
}
/// Duplicate the low double-precision (64-bit) floating-point element
/// from `a`.
///
/// [Intel's documentation](https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_movedup_pd)
#[inline]
#[target_feature(enable = "sse3")]
#[cfg_attr(test, assert_instr(movddup))]
#[stable(feature = "simd_x86", since = "1.27.0")]
pub unsafe fn _mm_movedup_pd(a: __m128d) -> __m128d {
simd_shuffle!(a, a, [0, 0])
}
/// Loads a double-precision (64-bit) floating-point element from memory
/// into both elements of return vector.
///
/// [Intel's documentation](https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_loaddup_pd)
#[inline]
#[target_feature(enable = "sse3")]
#[cfg_attr(test, assert_instr(movddup))]
#[stable(feature = "simd_x86", since = "1.27.0")]
pub unsafe fn _mm_loaddup_pd(mem_addr: *const f64) -> __m128d {
_mm_load1_pd(mem_addr)
}
/// Duplicate odd-indexed single-precision (32-bit) floating-point elements
/// from `a`.
///
/// [Intel's documentation](https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_movehdup_ps)
#[inline]
#[target_feature(enable = "sse3")]
#[cfg_attr(test, assert_instr(movshdup))]
#[stable(feature = "simd_x86", since = "1.27.0")]
pub unsafe fn _mm_movehdup_ps(a: __m128) -> __m128 {
simd_shuffle!(a, a, [1, 1, 3, 3])
}
/// Duplicate even-indexed single-precision (32-bit) floating-point elements
/// from `a`.
///
/// [Intel's documentation](https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_moveldup_ps)
#[inline]
#[target_feature(enable = "sse3")]
#[cfg_attr(test, assert_instr(movsldup))]
#[stable(feature = "simd_x86", since = "1.27.0")]
pub unsafe fn _mm_moveldup_ps(a: __m128) -> __m128 {
simd_shuffle!(a, a, [0, 0, 2, 2])
}
#[allow(improper_ctypes)]
extern "C" {
#[link_name = "llvm.x86.sse3.addsub.ps"]
fn addsubps(a: __m128, b: __m128) -> __m128;
#[link_name = "llvm.x86.sse3.addsub.pd"]
fn addsubpd(a: __m128d, b: __m128d) -> __m128d;
#[link_name = "llvm.x86.sse3.hadd.pd"]
fn haddpd(a: __m128d, b: __m128d) -> __m128d;
#[link_name = "llvm.x86.sse3.hadd.ps"]
fn haddps(a: __m128, b: __m128) -> __m128;
#[link_name = "llvm.x86.sse3.hsub.pd"]
fn hsubpd(a: __m128d, b: __m128d) -> __m128d;
#[link_name = "llvm.x86.sse3.hsub.ps"]
fn hsubps(a: __m128, b: __m128) -> __m128;
#[link_name = "llvm.x86.sse3.ldu.dq"]
fn lddqu(mem_addr: *const i8) -> i8x16;
}
#[cfg(test)]
mod tests {
use stdarch_test::simd_test;
use crate::core_arch::x86::*;
#[simd_test(enable = "sse3")]
unsafe fn test_mm_addsub_ps() {
let a = _mm_setr_ps(-1.0, 5.0, 0.0, -10.0);
let b = _mm_setr_ps(-100.0, 20.0, 0.0, -5.0);
let r = _mm_addsub_ps(a, b);
assert_eq_m128(r, _mm_setr_ps(99.0, 25.0, 0.0, -15.0));
}
#[simd_test(enable = "sse3")]
unsafe fn test_mm_addsub_pd() {
let a = _mm_setr_pd(-1.0, 5.0);
let b = _mm_setr_pd(-100.0, 20.0);
let r = _mm_addsub_pd(a, b);
assert_eq_m128d(r, _mm_setr_pd(99.0, 25.0));
}
#[simd_test(enable = "sse3")]
unsafe fn test_mm_hadd_pd() {
let a = _mm_setr_pd(-1.0, 5.0);
let b = _mm_setr_pd(-100.0, 20.0);
let r = _mm_hadd_pd(a, b);
assert_eq_m128d(r, _mm_setr_pd(4.0, -80.0));
}
#[simd_test(enable = "sse3")]
unsafe fn test_mm_hadd_ps() {
let a = _mm_setr_ps(-1.0, 5.0, 0.0, -10.0);
let b = _mm_setr_ps(-100.0, 20.0, 0.0, -5.0);
let r = _mm_hadd_ps(a, b);
assert_eq_m128(r, _mm_setr_ps(4.0, -10.0, -80.0, -5.0));
}
#[simd_test(enable = "sse3")]
unsafe fn test_mm_hsub_pd() {
let a = _mm_setr_pd(-1.0, 5.0);
let b = _mm_setr_pd(-100.0, 20.0);
let r = _mm_hsub_pd(a, b);
assert_eq_m128d(r, _mm_setr_pd(-6.0, -120.0));
}
#[simd_test(enable = "sse3")]
unsafe fn test_mm_hsub_ps() {
let a = _mm_setr_ps(-1.0, 5.0, 0.0, -10.0);
let b = _mm_setr_ps(-100.0, 20.0, 0.0, -5.0);
let r = _mm_hsub_ps(a, b);
assert_eq_m128(r, _mm_setr_ps(-6.0, 10.0, -120.0, 5.0));
}
#[simd_test(enable = "sse3")]
unsafe fn test_mm_lddqu_si128() {
#[rustfmt::skip]
let a = _mm_setr_epi8(
1, 2, 3, 4,
5, 6, 7, 8,
9, 10, 11, 12,
13, 14, 15, 16,
);
let r = _mm_lddqu_si128(&a);
assert_eq_m128i(a, r);
}
#[simd_test(enable = "sse3")]
unsafe fn test_mm_movedup_pd() {
let a = _mm_setr_pd(-1.0, 5.0);
let r = _mm_movedup_pd(a);
assert_eq_m128d(r, _mm_setr_pd(-1.0, -1.0));
}
#[simd_test(enable = "sse3")]
unsafe fn test_mm_movehdup_ps() {
let a = _mm_setr_ps(-1.0, 5.0, 0.0, -10.0);
let r = _mm_movehdup_ps(a);
assert_eq_m128(r, _mm_setr_ps(5.0, 5.0, -10.0, -10.0));
}
#[simd_test(enable = "sse3")]
unsafe fn test_mm_moveldup_ps() {
let a = _mm_setr_ps(-1.0, 5.0, 0.0, -10.0);
let r = _mm_moveldup_ps(a);
assert_eq_m128(r, _mm_setr_ps(-1.0, -1.0, 0.0, 0.0));
}
#[simd_test(enable = "sse3")]
unsafe fn test_mm_loaddup_pd() {
let d = -5.0;
let r = _mm_loaddup_pd(&d);
assert_eq_m128d(r, _mm_setr_pd(d, d));
}
}
| true |
58604f75d9ac049e81ae9336a2bf95906bd72603
|
Rust
|
mtsr/polyfuse
|
/xtask/src/main.rs
|
UTF-8
| 2,656 | 2.84375 | 3 |
[
"Apache-2.0",
"MIT"
] |
permissive
|
use std::{
ffi::OsString,
path::{Path, PathBuf},
};
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
enum Arg {
/// Install Git hooks
InstallHooks,
/// Run a script.
Script {
/// The script name
#[structopt(name = "command", parse(from_os_str))]
command: OsString,
/// The arguments passed to script
#[structopt(name = "args", parse(from_os_str))]
args: Vec<OsString>,
},
}
fn main() -> anyhow::Result<()> {
match Arg::from_args() {
Arg::InstallHooks => do_install_hooks(),
Arg::Script { command, args } => do_run(command, args),
}
}
fn do_install_hooks() -> anyhow::Result<()> {
let src_dir = project_root()?.join(".cargo/hooks").canonicalize()?;
anyhow::ensure!(src_dir.is_dir(), "Cargo hooks directory");
let dst_dir = project_root()?.join(".git/hooks").canonicalize()?;
anyhow::ensure!(dst_dir.is_dir(), "Git hooks directory");
install_hook(src_dir.join("pre-commit"), dst_dir.join("pre-commit"))?;
install_hook(src_dir.join("pre-push"), dst_dir.join("pre-push"))?;
Ok(())
}
fn install_hook(src: impl AsRef<Path>, dst: impl AsRef<Path>) -> anyhow::Result<()> {
let src = src.as_ref();
let dst = dst.as_ref();
if src.is_file() {
println!("install {:?} to {:?}", src, dst);
std::fs::create_dir_all(
dst.parent()
.ok_or_else(|| anyhow::anyhow!("missing dst parent"))?,
)?;
std::fs::remove_file(dst)?;
std::os::unix::fs::symlink(src, dst)?;
}
Ok(())
}
fn do_run(command: OsString, args: Vec<OsString>) -> anyhow::Result<()> {
let bin_dir = project_root()?.join("bin").canonicalize()?;
anyhow::ensure!(bin_dir.is_dir(), "bin/ is not a directory");
use std::process::{Command, Stdio};
let mut script = Command::new(command);
script.args(args);
script.stdin(Stdio::null());
script.stdout(Stdio::inherit());
script.stderr(Stdio::inherit());
if let Some(orig_path) = std::env::var_os("PATH") {
let paths: Vec<_> = Some(bin_dir)
.into_iter()
.chain(std::env::split_paths(&orig_path))
.collect();
let new_path = std::env::join_paths(paths)?;
script.env("PATH", new_path);
}
let status = script.status()?;
anyhow::ensure!(status.success(), format!("Script failed: {}", status));
Ok(())
}
fn project_root() -> anyhow::Result<PathBuf> {
Ok(std::path::Path::new(&env!("CARGO_MANIFEST_DIR"))
.ancestors()
.nth(1)
.ok_or_else(|| anyhow::anyhow!("missing ancestor"))?
.to_owned())
}
| true |
ca3897c3f4e892d119268974d31f89522e4689d2
|
Rust
|
pitdicker/small-rngs
|
/src/sfc.rs
|
UTF-8
| 5,443 | 2.890625 | 3 |
[] |
no_license
|
// Copyright 2017 Paul Dicker.
// See the COPYRIGHT file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! A Small Fast Counting RNG, version 4.
use rand_core::{Rng, SeedableRng, Error, impls, le};
use core::slice;
/// A Small Fast Counting RNG designed by Chris Doty-Humphrey (32-bit version).
///
/// - Author: Chris Doty-Humphrey
/// - License: Public domain
/// - Source: [PractRand](http://pracrand.sourceforge.net/)
/// - Period: avg ~ 2<sup>127</sup>, min >= 2<sup>32</sup>
/// - State: 128 bits
/// - Word size: 32 bits
/// - Seed size: 96 bits
/// - Passes BigCrush and PractRand
#[derive(Clone)]
pub struct Sfc32Rng {
a: u32,
b: u32,
c: u32,
counter: u32,
}
impl SeedableRng for Sfc32Rng {
type Seed = [u8; 12];
fn from_seed(seed: Self::Seed) -> Self {
let mut seed_u32 = [0u32; 3];
le::read_u32_into(&seed, &mut seed_u32);
let mut state = Self { a: seed_u32[0],
b: seed_u32[1],
c: seed_u32[2],
counter: 1};
// Skip the first 15 outputs, just in case we have a bad seed.
for _ in 0..15 {
state.next_u32();
}
state
}
fn from_rng<R: Rng>(mut rng: R) -> Result<Self, Error> {
// Custom `from_rng` function. Because we can assume the seed to be of
// good quality, it is not neccesary to discard the first couple of
// rounds.
let mut seed_u32 = [0u32; 3];
unsafe {
let ptr = seed_u32.as_mut_ptr() as *mut u8;
let slice = slice::from_raw_parts_mut(ptr, 4*3);
rng.try_fill(slice)?;
}
Ok(Self { a: seed_u32[0], b: seed_u32[1], c: seed_u32[2], counter: 1 })
}
}
impl Rng for Sfc32Rng {
#[inline]
fn next_u32(&mut self) -> u32 {
// good sets include {21,9,3} and {15,8,3}
const BARREL_SHIFT: u32 = 21;
const RSHIFT: u32 = 9;
const LSHIFT: u32 = 3;
let tmp = self.a.wrapping_add(self.b).wrapping_add(self.counter);
self.counter += 1;
self.a = self.b ^ (self.b >> RSHIFT);
self.b = self.c.wrapping_add(self.c << LSHIFT);
self.c = self.c.rotate_left(BARREL_SHIFT).wrapping_add(tmp);
tmp
}
#[inline]
fn next_u64(&mut self) -> u64 {
impls::next_u64_via_u32(self)
}
#[cfg(feature = "i128_support")]
fn next_u128(&mut self) -> u128 {
impls::next_u128_via_u64(self)
}
fn fill_bytes(&mut self, dest: &mut [u8]) {
impls::fill_bytes_via_u32(self, dest)
}
fn try_fill(&mut self, dest: &mut [u8]) -> Result<(), Error> {
Ok(self.fill_bytes(dest))
}
}
/// A Small Fast Counting RNG designed by Chris Doty-Humphrey (64-bit version).
///
/// - Author: Chris Doty-Humphrey
/// - License: Public domain
/// - Source: [PractRand](http://pracrand.sourceforge.net/)
/// - Period: avg ~ 2<sup>255</sup>, min >= 2<sup>64</sup>
/// - State: 256 bits
/// - Word size: 64 bits
/// - Seed size: 192 bits
/// - Passes BigCrush and PractRand
#[derive(Clone)]
pub struct Sfc64Rng {
a: u64,
b: u64,
c: u64,
counter: u64,
}
impl SeedableRng for Sfc64Rng {
type Seed = [u8; 24];
fn from_seed(seed: Self::Seed) -> Self {
let mut seed_u64 = [0u64; 3];
le::read_u64_into(&seed, &mut seed_u64);
let mut state = Self { a: seed_u64[0],
b: seed_u64[1],
c: seed_u64[2],
counter: 1};
// Skip the first 18 outputs, just in case we have a bad seed.
for _ in 0..18 {
state.next_u64();
}
state
}
fn from_rng<R: Rng>(mut rng: R) -> Result<Self, Error> {
// Custom `from_rng` function. Because we can assume the seed to be of
// good quality, it is not neccesary to discard the first couple of
// rounds.
let mut seed_u64 = [0u64; 3];
unsafe {
let ptr = seed_u64.as_mut_ptr() as *mut u8;
let slice = slice::from_raw_parts_mut(ptr, 8*3);
rng.try_fill(slice)?;
}
Ok(Self { a: seed_u64[0], b: seed_u64[1], c: seed_u64[2], counter: 1 })
}
}
impl Rng for Sfc64Rng {
#[inline]
fn next_u32(&mut self) -> u32 {
self.next_u64() as u32
}
#[inline]
fn next_u64(&mut self) -> u64 {
// good sets include {24,11,3} and {25,12,3}
const BARREL_SHIFT: u32 = 24;
const RSHIFT: u32 = 11;
const LSHIFT: u32 = 3;
let tmp = self.a.wrapping_add(self.b).wrapping_add(self.counter);
self.counter += 1;
self.a = self.b ^ (self.b >> RSHIFT);
self.b = self.c.wrapping_add(self.c << LSHIFT);
self.c = self.c.rotate_left(BARREL_SHIFT).wrapping_add(tmp);
tmp
}
#[cfg(feature = "i128_support")]
fn next_u128(&mut self) -> u128 {
impls::next_u128_via_u64(self)
}
fn fill_bytes(&mut self, dest: &mut [u8]) {
impls::fill_bytes_via_u64(self, dest)
}
fn try_fill(&mut self, dest: &mut [u8]) -> Result<(), Error> {
Ok(self.fill_bytes(dest))
}
}
| true |
9b39cef8ff8a412e3f9cd0a6ac155b61c00734a2
|
Rust
|
DmitriiKostrov/mazai
|
/rust/mazai/src/main.rs
|
UTF-8
| 3,986 | 2.9375 | 3 |
[] |
no_license
|
use tide::{Body, Request, Response};
use tide::prelude::*;
use tera::Tera;
use tide_tera::prelude::*;
use serde_json::{Number, Value};
#[derive(Debug, Deserialize, Serialize)]
struct Animal {
name: String,
legs: u16,
}
#[derive(Debug, Deserialize, Serialize)]
struct TripDay {
seats: u16,
guests: u16
}
#[derive(Debug, Deserialize, Serialize)]
struct Trip {
to: String,
from: String,
desc: String,
driver: String,
time: String,
delay: u16,
days: [TripDay;7]
}
struct State {
tera: Tera,
trips: Vec<Trip>
}
#[async_std::main]
async fn main() -> tide::Result<()> {
let mut ter = Tera::new("templates/**/*")?;
ter.autoescape_on(vec!["html"]);
//let mut state = State{tera: ter, trips: vec![]};
let mut app = tide::with_state(ter); // tide::new()
//app.at("/orders/shoes").post(order_shoes);
//app.at("/").get(info);
// app.at("/:name").get(|req: tide::Request<Tera>| async move {
// let tera = req.state();
// let name: String = req.param("name")?.to_owned();
// tera.render_response("index.html", &context! { "name" => name })
// });
app.at("/").get(|req: tide::Request<Tera>| async move {
let tera = req.state();
tera.render_response("index.html", &context! {})
});
app.at("/trips").get(|req: tide::Request<Tera>| async move {
let data = std::fs::read_to_string("trips.json").expect("Unable to read file");
let json: serde_json::Value = serde_json::from_str(&data).expect("JSON does not have correct format.");
/*let trips = [
Trip {
to: "1".into(), from: "2".into(), desc: "hoho".into(), driver: "me".into(),
time: "10:30".into(), delay: 10, days: [
TripDay{seats:5,guests:3}, TripDay{seats:5,guests:3}, TripDay{seats:5,guests:3},
TripDay{seats:5,guests:3}, TripDay{seats:0,guests:0}, TripDay{seats:0,guests:0},
TripDay{seats:0,guests:0}
]
}
];*/
//let mut res = tide::Response::new(200).set_body(Body::from_json(trip);
//res.set_body(Body::from_json(trip)?);
//.body_json(&cat).unwrap()
//let tera = req.state();
//tera.render_response("index.html", &context! {})
let mut res = tide::Response::new(200);
res.set_body(Body::from_json(&json)?);
Ok(res)
});
app.at("/trip/:id/edit").get( |req: tide::Request<Tera> | async move {
let tera = req.state();
let strId = req.param("id");
let id: i32 = strId.parse().expect("Can't parse int");
tera.render_response("trip.html", &context! {"id" => id})
});
app.at("/trip/:id").get( |req: tide::Request<Tera> | async move {
let trip =
Trip {
to: "1".into(), from: "2".into(), desc: "hoho".into(), driver: "me".into(),
time: "10:30".into(), delay: 10, days: [
TripDay{seats:5,guests:3}, TripDay{seats:5,guests:3}, TripDay{seats:5,guests:3},
TripDay{seats:5,guests:3}, TripDay{seats:0,guests:0}, TripDay{seats:0,guests:0},
TripDay{seats:0,guests:0}
]
};
let mut res = tide::Response::new(200);
res.set_body(Body::from_json(&trip)?);
Ok(res)
});
// Serve static files
app.at("/static").serve_dir("static/").expect("Invalid static file directory");
app.listen("127.0.0.1:8080").await?;
println!("Server is closed.");
Ok(())
}
async fn order_shoes(mut req: Request<()>) -> tide::Result {
let Animal { name, legs } = req.body_json().await?;
Ok(format!("Hello, {}! I've put in an order for {} shoes", name, legs).into())
}
async fn info(_req: Request<()>) -> tide::Result {
Ok(format!("Hello\n").into())
}
/*
async fn GetHomePage(_req: Request<()>) -> tide::Result {
http.ServeFile(w, r, "templates/index.html")
}
*/
| true |
b89bc50b74d917ba4e70e2a13ca9e86ae0a5131d
|
Rust
|
extraymond/phala-blockchain
|
/standalone/pruntime/enclave-api/src/crypto.rs
|
UTF-8
| 1,867 | 2.671875 | 3 |
[
"Apache-2.0"
] |
permissive
|
use alloc::vec::Vec;
use parity_scale_codec::{Decode, Encode};
use crate::prpc::{Signature, SignatureType};
pub use phala_crypto::{aead, ecdh, CryptoError};
#[derive(Clone, Encode, Decode, Debug)]
pub struct EncryptedData {
pub iv: aead::IV,
pub pubkey: ecdh::EcdhPublicKey,
pub data: Vec<u8>,
}
impl EncryptedData {
pub fn decrypt(&self, key: &ecdh::EcdhKey) -> Result<Vec<u8>, CryptoError> {
let sk = ecdh::agree(key, &self.pubkey)?;
let mut tmp_data = self.data.clone();
let msg = aead::decrypt(&self.iv, &sk, &mut tmp_data)?;
Ok(msg.to_vec())
}
pub fn encrypt(
key: &ecdh::EcdhKey,
remote_pubkey: &ecdh::EcdhPublicKey,
iv: aead::IV,
data: &[u8],
) -> Result<Self, CryptoError> {
let sk = ecdh::agree(&key, &remote_pubkey[..])?;
let mut data = data.to_vec();
aead::encrypt(&iv, &sk, &mut data)?;
Ok(Self {
iv,
pubkey: key.public(),
data,
})
}
}
impl Signature {
pub fn verify(&self, msg: &[u8]) -> bool {
let sig_type = match SignatureType::from_i32(self.signature_type) {
Some(val) => val,
None => {
return false;
}
};
match sig_type {
SignatureType::Ed25519 => {
verify::<sp_core::ed25519::Pair>(&self.origin, &self.signature, msg)
}
SignatureType::Sr25519 => {
verify::<sp_core::sr25519::Pair>(&self.origin, &self.signature, msg)
}
SignatureType::Ecdsa => {
verify::<sp_core::ecdsa::Pair>(&self.origin, &self.signature, msg)
}
}
}
}
fn verify<T>(pubkey: &[u8], sig: &[u8], msg: &[u8]) -> bool
where
T: sp_core::crypto::Pair,
{
T::verify_weak(sig, msg, pubkey)
}
| true |
2570361a8780b473b188b27ecbcc3a1f6f4e1a2a
|
Rust
|
mb64/stack_alloc
|
/src/bitmapped_stack.rs
|
UTF-8
| 9,318 | 3.484375 | 3 |
[] |
no_license
|
//! A stack allocator with a bitmap as well.
//!
//! This way it can actually de-allocate things.
use alloc::alloc::{self, AllocErr, Layout};
use core::ops;
use core::ptr::NonNull;
/// The size, in chunks, of each bitmapped stack
pub const STACK_SIZE: usize = 64;
/// Rounds the given number up to fit the alignment.
/// `alignment` must be a power of 2.
fn round_up_to_alignment(x: usize, alignment: usize) -> usize {
debug_assert_ne!(alignment, 0);
let alignment_mask = alignment - 1;
if x & alignment_mask != 0 {
(x + alignment) & (!alignment_mask)
} else {
x
}
}
/// An upwards-growing stack
#[derive(Debug)]
pub struct BitmappedStack {
/// The bottom of the stack
bottom: NonNull<u8>,
/// Measured in units of `chunk_size`
current_height: usize,
/// Measured in bytes
chunk_size: usize,
/// Each bit is one chunk
bitmap: u64,
}
impl BitmappedStack {
/// Returns a new `BitmappedStack`. Panics if total_size > 64
pub const fn new(pointer: NonNull<u8>, chunk_size: usize) -> Self {
BitmappedStack {
bottom: pointer,
current_height: 0,
chunk_size,
bitmap: 0x0000000000000000,
}
}
/// Returns whether or not this allocator owns this memory
pub fn owns(&self, pointer: *const u8) -> bool {
let addr = pointer as usize;
let min = self.chunk_to_ptr(0).as_ptr() as usize;
let max = self.chunk_to_ptr(STACK_SIZE - 1).as_ptr() as usize;
min <= addr && addr <= max
}
/// Returns the smallest allocation size of the stack
pub fn chunk_size(&self) -> usize {
self.chunk_size
}
/// Returns a pointer to the bottom of the stack
pub fn pointer(&self) -> NonNull<u8> {
self.bottom
}
/// Returns true iff there are no allocations on the stack
pub fn is_empty(&self) -> bool {
self.current_height == 0
}
/// Returns the number of chunks left in the stack
pub fn chunks_left(&self) -> usize {
debug_assert!(STACK_SIZE >= self.current_height);
STACK_SIZE - self.current_height
}
/// `debug_assert`s that the allocator is completely deallocated
pub fn debug_assert_empty(&self) {
debug_assert_eq!(self.bitmap, 0, "The mask is not zero :(");
debug_assert_eq!(self.current_height, 0, "The height is not zero :(");
}
/// Returns the number of chunks required for the given number of bytes
fn chunks_for(&self, bytes: usize) -> usize {
// Divide by chunk size, rounding up
let mut res = bytes / self.chunk_size;
if bytes % self.chunk_size != 0 {
res += 1;
}
res
}
/// Mark the chunks as allocated in the bitmap
unsafe fn bitmap_allocate(&mut self, chunk_range: ops::Range<usize>) {
debug_assert!(chunk_range.end <= STACK_SIZE);
let num_chunks = chunk_range.size_hint().0;
if num_chunks > 0 {
let mask = {
// Wrapping ops in case of (1 << 64) - 1 which overflows
let mask_base = 1_u64.wrapping_shl(num_chunks as u32).wrapping_sub(1);
mask_base << chunk_range.start
};
self.bitmap |= mask;
}
}
/// Mark the chunks as deallocated in the bitmap
unsafe fn bitmap_deallocate(&mut self, chunk_range: ops::Range<usize>) {
debug_assert!(chunk_range.end <= STACK_SIZE);
let num_chunks = chunk_range.size_hint().0;
if num_chunks > 0 {
let mask = {
// Wrapping ops in case of (1 << 64) - 1 which overflows
let mask_base = 1_u64.wrapping_shl(num_chunks as u32).wrapping_sub(1);
mask_base << chunk_range.start
};
self.bitmap &= !mask;
}
}
/// Returns `true` if all the chunks in the range are marked as deallocated in the bitmap
fn all_deallocated(&self, chunk_range: ops::Range<usize>) -> bool {
debug_assert!(chunk_range.end <= STACK_SIZE);
let mask = {
let num_chunks = chunk_range.size_hint().0;
let mask_base = (1 << num_chunks) - 1;
mask_base << chunk_range.start
};
self.bitmap & mask == 0
}
/// Returns the chunk number associated with the pointer.
///
/// It's unsafe because it assumes that the pointer is a valid pointer to a chunk.
unsafe fn ptr_to_chunk(&self, ptr: *mut u8) -> usize {
let offset = ptr.offset_from(self.bottom.as_ptr());
debug_assert!(offset >= 0);
offset as usize / self.chunk_size
}
/// Return a pointer to the chunk at that number.
fn chunk_to_ptr(&self, chunk: usize) -> NonNull<u8> {
// Might want to look at ptr for out-of-bounds chunks, too...?
//debug_assert!(chunk < STACK_SIZE, "chunk {} out of bounds", chunk);
unsafe {
let byte_offset = chunk * self.chunk_size;
NonNull::new_unchecked(self.bottom.as_ptr().add(byte_offset))
}
}
/// Lowers the height past as many deallocated chunks as possible
fn shrink_height(&mut self) {
self.current_height = 64 - self.bitmap.leading_zeros() as usize;
}
pub unsafe fn alloc(&mut self, layout: Layout) -> Result<NonNull<u8>, AllocErr> {
debug_log!(
"Allocing: align %zu, size %zu\n\0",
layout.align(),
layout.size()
);
let bottom_of_alloc = {
let stack_ptr = self.chunk_to_ptr(self.current_height);
let aligned_stack_ptr =
round_up_to_alignment(stack_ptr.as_ptr() as usize, layout.align());
self.ptr_to_chunk(aligned_stack_ptr as *mut u8)
};
if bottom_of_alloc * self.chunk_size + layout.size() > STACK_SIZE * self.chunk_size {
debug_log!("Exhausted BitmappedStack:\n chunk_size: %zu\n current_height: %zu\n bitmap: %#018zx\n\0",
self.chunk_size,
self.current_height,
self.bitmap
);
return Err(AllocErr);
}
let new_height = bottom_of_alloc + self.chunks_for(layout.size());
self.bitmap_allocate(bottom_of_alloc..new_height);
self.current_height = new_height;
debug_log!(" Bitmap is now %#018jx\n\0", self.bitmap);
Ok(self.chunk_to_ptr(bottom_of_alloc))
}
pub unsafe fn dealloc(&mut self, ptr: NonNull<u8>, layout: Layout) {
debug_log!(
"Freeing: align %zu, size %zu\n\0",
layout.align(),
layout.size()
);
debug_assert!(self.owns(ptr.as_ptr()));
let start_chunk = self.ptr_to_chunk(ptr.as_ptr());
let end_chunk = start_chunk + self.chunks_for(layout.size());
self.bitmap_deallocate(start_chunk..end_chunk);
if self.current_height == end_chunk {
self.current_height = start_chunk;
self.shrink_height();
}
debug_log!(" Bitmap is now %#018jx\n\0", self.bitmap);
}
pub unsafe fn shrink_in_place(&mut self, ptr: NonNull<u8>, layout: Layout, new_size: usize) {
debug_log!(
"Shrinking: align %zu, size %zu to %zu\n\0",
layout.align(),
layout.size(),
new_size
);
let new_chunks = self.chunks_for(new_size);
let old_chunks = self.chunks_for(layout.size());
let new_end = self.ptr_to_chunk(ptr.as_ptr()) + new_chunks;
let old_end = self.ptr_to_chunk(ptr.as_ptr()) + old_chunks;
self.bitmap_deallocate(new_end..old_end);
if self.current_height == old_end {
self.current_height = new_end;
if new_size == 0 {
self.shrink_height();
}
}
debug_log!(" Bitmap is now %#018jx\n\0", self.bitmap);
}
pub unsafe fn grow_in_place(
&mut self,
ptr: NonNull<u8>,
layout: Layout,
new_size: usize,
) -> Result<(), alloc::CannotReallocInPlace> {
debug_log!(
"Growing: align %zu, size %zu to %zu\n\0",
layout.align(),
layout.size(),
new_size
);
let new_chunks = self.chunks_for(new_size);
let old_chunks = self.chunks_for(layout.size());
let new_end = self.ptr_to_chunk(ptr.as_ptr()) + new_chunks;
let old_end = self.ptr_to_chunk(ptr.as_ptr()) + old_chunks;
if old_end == new_end {
debug_log!(" Bitmap is now %#018jx\n\0", self.bitmap);
return Ok(());
}
if new_end > STACK_SIZE {
return Err(alloc::CannotReallocInPlace);
}
debug_assert!(old_end < new_end);
if old_end == self.current_height {
self.current_height = new_end;
self.bitmap_allocate(old_end..new_end);
debug_log!(" Bitmap is now %#018jx\n\0", self.bitmap);
Ok(())
} else {
if self.all_deallocated(old_end..new_end) {
self.bitmap_allocate(old_end..new_end);
debug_log!(" Bitmap is now %#018jx\n\0", self.bitmap);
Ok(())
} else {
Err(alloc::CannotReallocInPlace)
}
}
}
}
| true |
e721fd25ffae22bb8c1509726d7555ea73726b64
|
Rust
|
matklad/fall
|
/fall/tree/src/edit.rs
|
UTF-8
| 2,711 | 3.015625 | 3 |
[
"MIT"
] |
permissive
|
use crate::{TextEdit, TextEditBuilder, Node, File, TextRange, TextEditOp, tu};
use crate::search::find_covering_node;
pub struct FileEdit<'f> {
file: &'f File,
inserted: Vec<(Node<'f>, String)>,
replaced: Vec<(Node<'f>, String)>,
deleted: Vec<Node<'f>>,
}
impl<'f> FileEdit<'f> {
pub fn new(file: &File) -> FileEdit {
FileEdit {
file,
inserted: Vec::new(),
replaced: Vec::new(),
deleted: Vec::new(),
}
}
pub fn replace(&mut self, node: Node<'f>, replacement: Node) {
self.replace_with_text(node, replacement.text().to_string())
}
pub fn replace_with_text(&mut self, node: Node<'f>, replacement: String) {
self.replaced.push((node, replacement))
}
pub fn replace_substring(&mut self, range: TextRange, replacement: String) {
let root = self.file.root();
assert!(range.is_subrange_of(root.range()));
let node = find_covering_node(root, range);
let file_text = self.file.text();
let prefix = file_text.slice(TextRange::from_to(node.range().start(), range.start()));
let suffix = file_text.slice(TextRange::from_to(range.end(), node.range().end()));
let new_text = prefix.to_string()
+ &replacement
+ &suffix.to_cow();
self.replace_with_text(node, new_text);
}
pub fn delete(&mut self, node: Node<'f>) {
self.deleted.push(node)
}
pub fn insert_text_after(&mut self, anchor: Node<'f>, text: String) {
self.inserted.push((anchor, text))
}
pub fn into_text_edit(self) -> TextEdit {
let mut edit_builder = TextEditBuilder::new(self.file.text());
self.text_edit_for_node(self.file.root(), &mut edit_builder);
// TODO: :(
let mut edit = edit_builder.build();
edit.ops.push(TextEditOp::Copy(TextRange::from_len(
self.file.text().len(),
tu(0),
)));
edit
}
fn text_edit_for_node(&self, node: Node<'f>, edit_builder: &mut TextEditBuilder) {
if self.deleted.iter().find(|&&n| n == node).is_some() {
edit_builder.delete(node.range());
return;
}
if let Some(&(_, ref replacement)) = self.replaced.iter().find(|&&(n, _)| n == node) {
edit_builder.replace(node.range(), replacement.as_ref());
return;
}
for child in node.children() {
self.text_edit_for_node(child, edit_builder);
}
if let Some(&(_, ref replacement)) = self.inserted.iter().find(|&&(n, _)| n == node) {
edit_builder.insert(node.range().end(), replacement.as_ref());
}
}
}
| true |
7941e832c59dbca8d7af0c5e7add9dea1541c0a5
|
Rust
|
Catorpilor/aoc2018
|
/day16a/src/main.rs
|
UTF-8
| 2,403 | 3.0625 | 3 |
[] |
no_license
|
use std::fs::File;
use std::io::{BufReader, BufRead};
use itertools::Itertools;
use self::OpCode::*;
#[macro_use]
extern crate text_io;
type Reg = usize;
#[derive(Copy, Clone, Debug)]
enum OpCode {
AddR,
AddI,
MulR,
MulI,
BanR,
BanI,
BorR,
BorI,
SetR,
SetI,
GtIR,
GtRI,
GtRR,
EqIR,
EqRI,
EqRR,
}
impl OpCode {
fn apply(self, registers: &mut [Reg], a: usize, b: usize, c: usize) {
registers[c] = match self {
AddR => registers[a] + registers[b],
AddI => registers[a] + b,
MulR => registers[a] * registers[b],
MulI => registers[a] * b,
BanR => registers[a] & registers[b],
BanI => registers[a] & b,
BorR => registers[a] | registers[b],
BorI => registers[a] | b,
SetR => registers[a],
SetI => a,
GtIR => (a > registers[b]).into(),
GtRI => (registers[a] > b).into(),
GtRR => (registers[a] > registers[b]).into(),
EqIR => (a == registers[b]).into(),
EqRI => (registers[a] == b).into(),
EqRR => (registers[a] == registers[b]).into(),
}
}
}
const ALL_OP_CODES: &[OpCode] = &[
AddR,
AddI,
MulR,
MulI,
BanR,
BanI,
BorR,
BorI,
SetR,
SetI,
GtIR,
GtRI,
GtRR,
EqIR,
EqRI,
EqRR,
];
fn main() {
let mut line_iter = BufReader::new(File::open("input.txt").unwrap())
.lines()
.map(Result::unwrap);
let result = line_iter.by_ref().scan(0, |state, line| {
if line.is_empty() { *state += 1; } else { *state = 0; }
if *state >= 2 { None } else { Some(line) }
}).tuples().filter(|(l1, l2, l3, _)| {
let (r0, r1, r2, r3): (Reg, Reg, Reg, Reg);
let (s0, s1, s2, s3): (Reg, Reg, Reg, Reg);
let (op, a, b, c): (usize, usize, usize, usize);
scan!(l1.bytes() => "Before: [{}, {}, {}, {}]", r0, r1, r2, r3);
scan!(l2.bytes() => "{} {} {} {}", op, a, b, c);
scan!(l3.bytes() => "After: [{}, {}, {}, {}]", s0, s1, s2, s3);
ALL_OP_CODES.iter().filter(|op_code| {
let mut registers = [r0, r1, r2, r3];
op_code.apply(&mut registers, a, b, c);
registers == [s0, s1, s2, s3]
}).count() >= 3
}).count();
println!("{}", result);
}
| true |
cc7c3fb0f7cca7ac1e8fdb43d11cde8e77f62583
|
Rust
|
numbaa/learn-plt
|
/freestyle/src/parser.rs
|
UTF-8
| 13,347 | 3.296875 | 3 |
[] |
no_license
|
use super::tokenizer::*;
use super::ast;
pub struct Parser {
tokenizer: Tokenizer
}
impl Parser {
fn function_call(&mut self, func: Token) -> Result<ast::AstNode, String> {
self.tokenizer.eat(1);
let mut func_node = ast::AstNode::new(ast::NodeType::FuncCall, func);
loop {
let arg = match self.tokenizer.look_ahead(1) {
Ok(token) => token,
Err(msg) => return Err(msg),
};
self.tokenizer.eat(1);
match arg.token_type {
TokenType::Symbol => (),
_ => return Err(format!("line:{}, column:{}, syntax error, expect argument, found '{}'",
arg.row, arg.col, arg.literal)),
}
func_node.add_node(ast::AstNode::new(ast::NodeType::Arg, arg));
let next_token = match self.tokenizer.look_ahead(1) {
Ok(token) => token,
Err(msg) => return Err(msg),
};
match next_token.token_type {
TokenType::Comma => (),
TokenType::RP => break,
_ => return Err(format!("line:{}, column:{}, syntax error, expect ',' or ')'), found '{}'",
next_token.row, next_token.col, next_token.literal)),
}
}
Ok(func_node)
}
fn expression_integer_or_name(&mut self) -> Result<ast::AstNode, String> {
let token = match self.tokenizer.look_ahead(1) {
Ok(token) => token,
Err(msg) => return Err(msg),
};
self.tokenizer.eat(1);
match token.token_type {
TokenType::Integer => return Ok(ast::AstNode::new(ast::NodeType::Integer, token)),
TokenType::Symbol => {
let next_token = match self.tokenizer.look_ahead(1) {
Ok(token) => token,
Err(msg) => return Err(msg),
};
match next_token.token_type {
TokenType::LP => return self.function_call(token),
_ => return Ok(ast::AstNode::new(ast::NodeType::Name, token))
}
},
_ => return Err(format!("line:{}, column:{}, syntax error, expect integer or variable or function",
token.row, token.col)),
}
}
fn expression_pow(&mut self) -> Result<ast::AstNode, String> {
let mut left = match self.expression_integer_or_name() {
Ok(node) => node,
Err(msg) => return Err(msg),
};
loop {
let op = match self.tokenizer.look_ahead(1) {
Ok(token) => token,
Err(msg) => return Err(msg),
};
match op.token_type {
TokenType::Pow => {
let mut pow_expr = ast::AstNode::new(ast::NodeType::Pow, op);
self.tokenizer.eat(1);
pow_expr.add_node(left);
pow_expr.add_node(match self.expression_integer_or_name() {
Ok(node) => node,
Err(msg) => return Err(msg),
});
left = pow_expr;
},
_ => return Ok(left),
}
}
}
fn expression_mul(&mut self) -> Result<ast::AstNode, String> {
let mut left = match self.expression_pow() {
Ok(node) => node,
Err(msg) => return Err(msg),
};
loop {
let op = match self.tokenizer.look_ahead(1) {
Ok(token) => token,
Err(msg) => return Err(msg),
};
match op.token_type {
TokenType::Mul | TokenType::Div => {
let mut mul_expr = ast::AstNode::new(ast::NodeType::Mul, op);
self.tokenizer.eat(1);
mul_expr.add_node(left);
mul_expr.add_node(match self.expression_pow() {
Ok(node) => node,
Err(msg) => return Err(msg),
});
left = mul_expr;
},
_ => return Ok(left),
}
}
}
fn expression_add(&mut self) -> Result<ast::AstNode, String> {
let mut left = match self.expression_mul() {
Ok(node) => node,
Err(msg) => return Err(msg),
};
loop {
let op = match self.tokenizer.look_ahead(1) {
Ok(token) => token,
Err(msg) => return Err(msg),
};
match op.token_type {
TokenType::Add | TokenType::Sub | TokenType::Mod => {
let mut add_expr = ast::AstNode::new(ast::NodeType::Add, op);
self.tokenizer.eat(1);
add_expr.add_node(left);
add_expr.add_node(match self.expression_mul() {
Ok(node) => node,
Err(msg) => return Err(msg),
});
left = add_expr;
},
_ => return Ok(left),
}
}
}
fn expression(&mut self) -> Result<ast::AstNode, String> {
return self.expression_add();
}
fn statement_print(&mut self, parent: &mut ast::AstNode) -> Result<(), String> {
let mut print_node = ast::AstNode::new(ast::NodeType::Print, match self.tokenizer.look_ahead(1) {
Ok(token) => token,
Err(msg) => return Err(msg),
});
self.tokenizer.eat(1);
print_node.add_node(match self.expression() {
Ok(node) => node,
Err(msg) => return Err(msg),
});
parent.add_node(print_node);
return Ok(())
}
fn statement_assign(&mut self, parent: &mut ast::AstNode) -> Result<(), String> {
let name = match self.tokenizer.look_ahead(1) {
Ok(token) => token,
Err(msg) => return Err(msg),
};
let assign = match self.tokenizer.look_ahead(2) {
Ok(token) => token,
Err(msg) => return Err(msg),
};
self.tokenizer.eat(2);
match assign.token_type {
TokenType::Assign => (),
_ => return Err(format!("line:{}, column:{}, syntax error, expect '=', found '{}'",
assign.row, assign.col, assign.literal)),
}
let mut assign_node = ast::AstNode::new(ast::NodeType::Assign, assign);
let name_node = ast::AstNode::new(ast::NodeType::Name, name);
assign_node.add_node(name_node);
assign_node.add_node(match self.expression() {
Ok(node) => node,
Err(msg) => return Err(msg),
});
parent.add_node(assign_node);
return Ok(())
}
fn parameters_node(&mut self) -> Result<ast::AstNode, String> {
let lp = match self.tokenizer.look_ahead(1) {
Ok(token) => token,
Err(msg) => return Err(msg),
};
self.tokenizer.eat(1);
match lp.token_type {
TokenType::LP => (),
_ => return Err(format!("line:{}, column:{}, syntax error, expect '('), found '{}'",
lp.row, lp.col, lp.literal)),
}
let mut param_node = ast::AstNode::new(ast::NodeType::ParamList, lp);
loop {
let param = match self.tokenizer.look_ahead(1) {
Ok(token) => token,
Err(msg) => return Err(msg),
};
self.tokenizer.eat(1);
match param.token_type {
TokenType::Symbol => (),
_ => return Err(format!("line:{}, column:{}, syntax error, expect parameter, found '{}'",
param.row, param.col, param.literal)),
}
param_node.add_node(ast::AstNode::new(ast::NodeType::Param, param));
let next_token = match self.tokenizer.look_ahead(1) {
Ok(token) => token,
Err(msg) => return Err(msg),
};
match next_token.token_type {
TokenType::Comma => (),
TokenType::RP => break,
_ => return Err(format!("line:{}, column:{}, syntax error, expect ',' or ')'), found '{}'",
next_token.row, next_token.col, next_token.literal)),
}
}
Ok(param_node)
}
fn function_body(&mut self) -> Result<ast::AstNode, String> {
let lbraceket = match self.tokenizer.look_ahead(1) {
Ok(token) => token,
Err(msg) => return Err(msg),
};
self.tokenizer.eat(1);
match lbraceket.token_type {
TokenType::LBraceket => (),
_ => return Err(format!("line:{}, column:{}, syntax error, expect '('), found '{}'",
lbraceket.row, lbraceket.col, lbraceket.literal)),
}
let mut body = ast::AstNode::new(ast::NodeType::FuncBody, lbraceket);
loop {
let token = match self.tokenizer.look_ahead(1) {
Ok(token) => token,
Err(msg) => return Err(msg),
} ;
match token.token_type {
TokenType::Print => {
let result = self.statement_print(&mut body);
if result.is_err() {
return Err(result.unwrap_err());
}
},
TokenType::Symbol => {
let result = self.statement_assign(&mut body);
if result.is_err() {
return Err(result.unwrap_err());
}
},
TokenType::Return => {
let mut ret = ast::AstNode::new(ast::NodeType::Return, token);
self.tokenizer.eat(1);
let expr = match self.expression() {
Ok(token) => token,
Err(msg) => return Err(msg),
};
ret.add_node(expr);
body.add_node(ret);
return Ok(body);
}
TokenType::Newline => { self.tokenizer.eat(1); continue; },
_ => return Err(format!("line:{}, column:{}, syntax error, expect 'print' or 'variable'",
token.row, token.col)),
}
}
}
fn statement_func_decl(&mut self, parent: &mut ast::AstNode) -> Result<(), String> {
let func_name = match self.tokenizer.look_ahead(2) {
Ok(token) => token,
Err(msg) => return Err(msg),
};
self.tokenizer.eat(2);
match func_name.token_type {
TokenType::Symbol => (),
_ => return Err(format!("line:{}, column:{}, syntax error, expect function name, found '{}'",
func_name.row, func_name.col, func_name.literal)),
}
let mut func_decl_node = ast::AstNode::new(ast::NodeType::FuncDecl, func_name);
let parameters_node = match self.parameters_node() {
Ok(node) => node,
Err(msg) => return Err(msg),
};
let func_body = match self.function_body() {
Ok(node) => node,
Err(msg) => return Err(msg),
};
func_decl_node.add_node(parameters_node);
func_decl_node.add_node(func_body);
parent.add_node(func_decl_node);
Ok(())
}
pub fn parse(&mut self) -> Result<ast::AstNode, String> {
let mut ast_root = ast::AstNode::new(ast::NodeType::Root, Token::new());
loop {
let token = match self.tokenizer.look_ahead(1) {
Ok(token) => token,
Err(msg) => return Err(msg),
};
match token.token_type {
TokenType::Print => {
let result = self.statement_print(&mut ast_root);
if result.is_err() {
return Err(result.unwrap_err());
}
},
TokenType::Symbol => {
let result = self.statement_assign(&mut ast_root);
if result.is_err() {
return Err(result.unwrap_err());
}
},
TokenType::FuncDecl => {
let result = self.statement_func_decl(&mut ast_root);
if result.is_err() {
return Err(result.unwrap_err());
}
},
TokenType::Newline => { self.tokenizer.eat(1); continue; },
TokenType::EOF => return Ok(ast_root),
_ => return Err(format!("line:{}, column:{}, syntax error, expect 'print' or 'variable'",
token.row, token.col)),
}
}
}
pub fn new(tokenizer: Tokenizer) -> Parser {
return Parser {
tokenizer: tokenizer
}
}
}
| true |
f2b4d674337f61bebf897d6c6954123ace424a46
|
Rust
|
RoccoDev/mcp-converter
|
/src/ffi/mod.rs
|
UTF-8
| 1,558 | 2.53125 | 3 |
[] |
no_license
|
use parser;
use std::ffi::{CStr, CString};
use std::str;
use libc::c_char;
/* Utility functions */
fn str_to_ptr(input: &str) -> *const c_char {
let c_str = CString::new(input).unwrap();
let c_ptr = c_str.as_ptr();
std::mem::forget(c_str);
c_ptr
}
fn str_from_ptr<'a>(input: *const c_char) -> &'a str {
let res = unsafe { CStr::from_ptr(input) };
let out = res.to_str().unwrap();
out
}
/* Extern functions */
#[no_mangle]
pub extern "C" fn class_mcp_from_notchian(notchian: *const c_char) -> *const c_char {
let result = parser::srg::find_class_notchian(str_from_ptr(notchian)).unwrap().mcp_name;
return str_to_ptr(result.as_str());
}
#[no_mangle]
pub extern "C" fn class_notchian_from_mcp(mcp: *const c_char) -> *const c_char {
let result = parser::srg::find_class(str_from_ptr(mcp)).unwrap().notchian_name;
return str_to_ptr(result.as_str());
}
#[no_mangle]
pub extern "C" fn field_notchian_from_mcp(mcp: *const c_char, class_mcp: *const c_char) -> *const c_char {
let result = parser::srg::find_field(str_from_ptr(mcp), parser::srg::find_class(str_from_ptr(class_mcp)).unwrap()).unwrap().notchian_name;
return str_to_ptr(result.as_str());
}
#[no_mangle]
pub extern "C" fn field_mcp_from_notchian(notchian: *const c_char, class_notchian: *const c_char) -> *const c_char {
let result = parser::srg::find_field_notchian(str_from_ptr(notchian), parser::srg::find_class_notchian(str_from_ptr(class_notchian)).unwrap()).unwrap().mcp_name;
return str_to_ptr(result.as_str());
}
| true |
c71f5966ce73d11f5696c3691726f539ef013729
|
Rust
|
harpsword/tex-rs
|
/src/tex_the_program/section_1008_to_1011.rs
|
UTF-8
| 4,323 | 2.65625 | 3 |
[
"Apache-2.0",
"MIT"
] |
permissive
|
//! @ @<Append an insertion to the current page and |goto contribute|@>=
//! begin if page_contents=empty then freeze_page_specs(inserts_only);
//! n:=subtype(p); r:=page_ins_head;
//! while n>=subtype(link(r)) do r:=link(r);
//! n:=qo(n);
//! if subtype(r)<>qi(n) then
//! @<Create a page insertion node with |subtype(r)=qi(n)|, and
//! include the glue correction for box |n| in the
//! current page state@>;
//! if type(r)=split_up then insert_penalties:=insert_penalties+float_cost(p)
//! else begin last_ins_ptr(r):=p;
//! delta:=page_goal-page_total-page_depth+page_shrink;
//! {this much room is left if we shrink the maximum}
//! if count(n)=1000 then h:=height(p)
//! else h:=x_over_n(height(p),1000)*count(n); {this much room is needed}
//! if ((h<=0)or(h<=delta))and(height(p)+height(r)<=dimen(n)) then
//! begin page_goal:=page_goal-h; height(r):=height(r)+height(p);
//! end
//! else @<Find the best way to split the insertion, and change
//! |type(r)| to |split_up|@>;
//! end;
//! goto contribute;
//! end
//!
//! @ We take note of the value of \.{\\skip} |n| and the height plus depth
//! of \.{\\box}~|n| only when the first \.{\\insert}~|n| node is
//! encountered for a new page. A user who changes the contents of \.{\\box}~|n|
//! after that first \.{\\insert}~|n| had better be either extremely careful
//! or extremely lucky, or both.
//!
//! @<Create a page insertion node...@>=
//! begin q:=get_node(page_ins_node_size); link(q):=link(r); link(r):=q; r:=q;
//! subtype(r):=qi(n); type(r):=inserting; ensure_vbox(n);
//! if box(n)=null then height(r):=0
//! else height(r):=height(box(n))+depth(box(n));
//! best_ins_ptr(r):=null;@/
//! q:=skip(n);
//! if count(n)=1000 then h:=height(r)
//! else h:=x_over_n(height(r),1000)*count(n);
//! page_goal:=page_goal-h-width(q);@/
//! page_so_far[2+stretch_order(q)]:=@|page_so_far[2+stretch_order(q)]+stretch(q);@/
//! page_shrink:=page_shrink+shrink(q);
//! if (shrink_order(q)<>normal)and(shrink(q)<>0) then
//! begin print_err("Infinite glue shrinkage inserted from "); print_esc("skip");
//! @.Infinite glue shrinkage...@>
//! print_int(n);
//! help3("The correction glue for page breaking with insertions")@/
//! ("must have finite shrinkability. But you may proceed,")@/
//! ("since the offensive shrinkability has been made finite.");
//! error;
//! end;
//! end
//!
//! @ Here is the code that will split a long footnote between pages, in an
//! emergency. The current situation deserves to be recapitulated: Node |p|
//! is an insertion into box |n|; the insertion will not fit, in its entirety,
//! either because it would make the total contents of box |n| greater than
//! \.{\\dimen} |n|, or because it would make the incremental amount of growth
//! |h| greater than the available space |delta|, or both. (This amount |h| has
//! been weighted by the insertion scaling factor, i.e., by \.{\\count} |n|
//! over 1000.) Now we will choose the best way to break the vlist of the
//! insertion, using the same criteria as in the \.{\\vsplit} operation.
//!
//! @<Find the best way to split the insertion...@>=
//! begin if count(n)<=0 then w:=max_dimen
//! else begin w:=page_goal-page_total-page_depth;
//! if count(n)<>1000 then w:=x_over_n(w,count(n))*1000;
//! end;
//! if w>dimen(n)-height(r) then w:=dimen(n)-height(r);
//! q:=vert_break(ins_ptr(p),w,depth(p));
//! height(r):=height(r)+best_height_plus_depth;
//! @!stat if tracing_pages>0 then @<Display the insertion split cost@>;@+tats@;@/
//! if count(n)<>1000 then
//! best_height_plus_depth:=x_over_n(best_height_plus_depth,1000)*count(n);
//! page_goal:=page_goal-best_height_plus_depth;
//! type(r):=split_up; broken_ptr(r):=q; broken_ins(r):=p;
//! if q=null then insert_penalties:=insert_penalties+eject_penalty
//! else if type(q)=penalty_node then insert_penalties:=insert_penalties+penalty(q);
//! end
//!
//! @ @<Display the insertion split cost@>=
//! begin begin_diagnostic; print_nl("% split"); print_int(n);
//! @.split@>
//! print(" to "); print_scaled(w);
//! print_char(","); print_scaled(best_height_plus_depth);@/
//! print(" p=");
//! if q=null then print_int(eject_penalty)
//! else if type(q)=penalty_node then print_int(penalty(q))
//! else print_char("0");
//! end_diagnostic(false);
//! end
//!
| true |
a693d0e3666cf9daa07fdb5f6c5531bfbf165647
|
Rust
|
curiousTauseef/tako
|
/src/symbol_table_builder.rs
|
UTF-8
| 6,266 | 2.8125 | 3 |
[
"MIT"
] |
permissive
|
use super::ast::*;
use super::database::Compiler;
use super::errors::TError;
use super::tree::{to_hash_root, HashTree};
// Walks the AST interpreting it.
#[derive(Default)]
pub struct SymbolTableBuilder {}
// TODO: Return nodes.
type Res = Result<Node, TError>;
#[derive(Debug, Clone)]
pub struct State {
pub table: Table,
pub path: Vec<Symbol>,
}
impl Table {
pub fn new() -> Table {
// TODO: This smells a bit?
to_hash_root(Entry::default())
}
pub fn find<'a>(self: &'a Table, path: &[Symbol]) -> Option<&'a Table> {
// eprintln!("find in {:?}", self.value);
if path.is_empty() {
return Some(self);
}
if let Some(child) = self.children.get(&path[0]) {
child.find(&path[1..])
} else {
None
}
}
pub fn find_mut<'a>(self: &'a mut Table, path: &[Symbol]) -> Option<&'a mut Table> {
// eprintln!("find in {:?}", self.value);
if path.is_empty() {
return Some(self);
}
if let Some(child) = self.children.get_mut(&path[0]) {
child.find_mut(&path[1..])
} else {
None
}
}
fn get_child_mut<'a>(self: &'a mut Table, find: &Symbol) -> &'a mut HashTree<Symbol, Entry> {
self.children.entry(find.clone()).or_insert_with(Table::new)
}
pub fn get_mut<'a>(self: &'a mut Table, path: &[Symbol]) -> &'a mut HashTree<Symbol, Entry> {
if path.is_empty() {
return self;
}
self.get_child_mut(&path[0]).get_mut(&path[1..])
}
}
impl Visitor<State, Node, Root, Path> for SymbolTableBuilder {
fn visit_root(&mut self, db: &dyn Compiler, module: &Path) -> Result<Root, TError> {
let expr = &db.parse_file(module.clone())?;
if db.debug() > 0 {
eprintln!("building symbol table for file... {:?}", &module);
}
let mut table = Table::new();
let mut main_at = module.clone();
main_at.push(Symbol::new("main".to_string()));
let main_symb = table.get_mut(&main_at);
main_symb.value.uses.insert(module.clone());
// Add in the globals here!
// TODO: Inject needs for bootstrapping here (e.g. import function).
let globals: Vec<Path> = ["print", "argc", "argv"]
.iter()
.map(|x| vec![Symbol::new(x.to_string())])
.collect();
for global in globals {
table.get_mut(&global);
}
let mut state = State {
table,
path: module.clone(),
};
if db.debug() > 0 {
eprintln!("table: {:?}", state.table);
}
Ok(Root {
ast: self.visit(db, &mut state, &expr)?,
table: state.table,
})
}
fn visit_sym(&mut self, _db: &dyn Compiler, _state: &mut State, expr: &Sym) -> Res {
Ok(expr.clone().to_node())
}
fn visit_prim(&mut self, _db: &dyn Compiler, _state: &mut State, expr: &Prim) -> Res {
Ok(expr.clone().to_node())
}
fn visit_apply(&mut self, db: &dyn Compiler, state: &mut State, expr: &Apply) -> Res {
let arg_scope_name = Symbol::Anon();
state.path.push(arg_scope_name);
let mut args = Vec::new();
for arg in expr.args.iter() {
args.push(match self.visit_let(db, state, arg)? {
Node::LetNode(let_node) => Ok(let_node),
node => Err(TError::InternalError(
"Symbol table builder converted let into non let".to_owned(),
node,
)),
}?);
}
let inner = Box::new(self.visit(db, state, &*expr.inner)?);
state.path.pop();
Ok(Apply {
inner,
args,
info: expr.get_info(),
}
.to_node())
}
fn visit_let(&mut self, db: &dyn Compiler, state: &mut State, expr: &Let) -> Res {
let let_name = Symbol::new(expr.name.clone());
if db.debug() > 1 {
eprintln!("visiting {:?} {}", state.path.clone(), &let_name);
}
// Visit definition.
let mut info = expr.get_info();
state.path.push(let_name);
info.defined_at = Some(state.path.clone());
state.table.get_mut(&state.path);
// Consider the function arguments defined in this scope.
let args = if let Some(e_args) = &expr.args {
let mut args = vec![];
for arg in e_args.iter() {
let mut arg_path = state.path.clone();
arg_path.push(Symbol::new(arg.name.clone()));
state.table.get_mut(&arg_path);
let mut sym = arg.clone();
if db.debug() > 1 {
eprintln!(
"visiting let arg {:?} {}",
arg_path.clone(),
&sym.name.clone()
);
}
sym.info.defined_at = Some(arg_path);
args.push(sym);
}
Some(args)
} else {
None
};
let value = Box::new(self.visit(db, state, &expr.value)?);
state.path.pop();
Ok(Let {
name: expr.name.clone(),
value,
args,
info,
}
.to_node())
}
fn visit_un_op(&mut self, db: &dyn Compiler, state: &mut State, expr: &UnOp) -> Res {
let inner = Box::new(self.visit(db, state, &expr.inner)?);
Ok(UnOp {
name: expr.name.clone(),
inner,
info: expr.get_info(),
}
.to_node())
}
fn visit_bin_op(&mut self, db: &dyn Compiler, state: &mut State, expr: &BinOp) -> Res {
let left = Box::new(self.visit(db, state, &expr.left)?);
let right = Box::new(self.visit(db, state, &expr.right)?);
Ok(BinOp {
name: expr.name.clone(),
left,
right,
info: expr.get_info(),
}
.to_node())
}
fn handle_error(&mut self, _db: &dyn Compiler, _state: &mut State, expr: &Err) -> Res {
Err(TError::FailedParse(expr.msg.to_string(), expr.get_info()))
}
}
#[cfg(test)]
mod tests {}
| true |
9fae24cbafecd9239c14c53601fc058d829421e4
|
Rust
|
gaswelder/che
|
/src/format_che.rs
|
UTF-8
| 6,412 | 3.234375 | 3 |
[
"MIT"
] |
permissive
|
use crate::nodes::*;
use crate::parser;
pub fn format_expression(expr: &Expression) -> String {
match expr {
Expression::FieldAccess {
op,
target,
field_name,
} => {
return format!("{}{}{}", format_expression(target), op, field_name.name);
}
Expression::Cast { type_name, operand } => {
return format!(
"({})({})",
format_anonymous_typeform(&type_name),
format_expression(&operand)
);
}
Expression::NsName(n) => format!("{}.{}", &n.namespace, &n.name),
Expression::FunctionCall {
function,
arguments,
} => {
let mut s1 = String::from("(");
for (i, argument) in arguments.iter().enumerate() {
if i > 0 {
s1 += ", ";
}
s1 += &format_expression(&argument);
}
s1 += ")";
return format!("{}{}", format_expression(&function), s1);
}
Expression::Literal(x) => format_literal(x),
Expression::Identifier(x) => x.name.clone(),
Expression::CompositeLiteral(CompositeLiteral { entries }) => {
if entries.len() == 0 {
// Print {0} to avoid "ISO C forbids empty initializers".
return String::from("{0}");
}
let mut s = String::from("{\n");
for (i, e) in entries.iter().enumerate() {
if i > 0 {
s += ",\n";
}
s += "\t";
let v = format_expression(&e.value);
match &e.key {
Some(expr) => {
let k = format_expression(expr);
if e.is_index {
s += &format!("[{}] = {}", k, v)
} else {
s += &format!(".{} = {}", k, v)
}
}
None => s += &v,
}
}
s += "\n}";
return s;
}
Expression::Sizeof { argument } => {
let arg = match &**argument {
SizeofArgument::Typename(x) => format_type(&x),
SizeofArgument::Expression(x) => format_expression(&x),
};
return format!("sizeof({})", arg);
}
Expression::BinaryOp { op, a, b } => format_binary_op(op, a, b),
Expression::PrefixOperator { operator, operand } => {
let expr = &**operand;
match is_binary_op(expr) {
Some(op) => {
if parser::operator_strength("prefix") > parser::operator_strength(op) {
return format!("{}({})", operator, format_expression(expr));
}
return format!("{}{}", operator, format_expression(expr));
}
None => {}
}
return match expr {
Expression::BinaryOp { op, a, b } => {
format!("{}({})", operator, format_binary_op(&op, &a, &b))
}
Expression::Cast { type_name, operand } => format!(
"{}{}",
operator,
format!(
"({})({})",
format_anonymous_typeform(&type_name),
format_expression(&operand)
)
),
_ => format!("{}{}", operator, format_expression(&operand)),
};
}
Expression::PostfixOperator { operator, operand } => {
return format_expression(&operand) + &operator;
}
Expression::ArrayIndex { array, index } => {
return format!("{}[{}]", format_expression(array), format_expression(index));
}
}
}
pub fn format_type(t: &Typename) -> String {
let name = if t.name.namespace != "" {
format!("{}.{}", t.name.namespace, t.name.name)
} else {
t.name.name.clone()
};
return format!("{}{}", if t.is_const { "const " } else { "" }, name);
}
pub fn format_form(node: &Form) -> String {
let mut s = String::new();
for _ in 0..node.hops {
s += "*";
}
s += &node.name;
for expr in &node.indexes {
match expr {
Some(e) => s += &format!("[{}]", format_expression(&e)),
None => s += "[]",
}
}
return s;
}
fn format_anonymous_typeform(node: &AnonymousTypeform) -> String {
let mut s = format_type(&node.type_name);
for op in &node.ops {
s += &op;
}
return s;
}
fn format_binary_op(op: &String, a: &Expression, b: &Expression) -> String {
// If a is an op weaker than op, wrap it
let af = match is_op(a) {
Some(k) => {
if parser::operator_strength(&k) < parser::operator_strength(op) {
format!("({})", format_expression(a))
} else {
format_expression(a)
}
}
None => format_expression(a),
};
// If b is an op weaker than op, wrap it
let bf = match is_op(b) {
Some(k) => {
if parser::operator_strength(&k) < parser::operator_strength(op) {
format!("({})", format_expression(b))
} else {
format_expression(b)
}
}
None => format_expression(b),
};
let parts = vec![af, op.clone(), bf];
let glue = if op == "." || op == "->" { "" } else { " " };
return parts.join(glue);
}
fn is_op(e: &Expression) -> Option<String> {
match e {
Expression::BinaryOp { op, .. } => Some(String::from(op)),
Expression::PostfixOperator { .. } => Some(String::from("prefix")),
Expression::PrefixOperator { .. } => Some(String::from("prefix")),
_ => None,
}
}
fn is_binary_op(a: &Expression) -> Option<&String> {
match a {
Expression::BinaryOp { op, .. } => Some(op),
_ => None,
}
}
fn format_literal(node: &Literal) -> String {
match node {
Literal::Char(val) => format!("\'{}\'", val),
Literal::String(val) => format!("\"{}\"", val),
Literal::Number(val) => format!("{}", val),
Literal::Null => String::from("NULL"),
}
}
| true |
6e1f4aa39a6b8ae951742c708e91ad2d6d42bba1
|
Rust
|
bnjjj/fixme_report
|
/src/config.rs
|
UTF-8
| 1,404 | 2.90625 | 3 |
[
"MIT"
] |
permissive
|
use crate::error::Error;
use crate::issue_tracker::IssueTracker;
use crate::Result;
use config_rs::Config as ConfigRs;
impl From<String> for IssueTracker {
fn from(issue_tracker: String) -> Self {
match &issue_tracker.to_lowercase()[..] {
"github" => IssueTracker::Github,
"bitbucketcloud" => IssueTracker::BitbucketCloud,
"bitbucketserver" => IssueTracker::BitbucketServer,
// "jira" => IssueTracker::Jira,
_ => unimplemented!(),
}
}
}
#[derive(Deserialize)]
pub struct Config {
pub r#type: String,
pub url: String,
pub repository: String,
pub username: String,
pub token: String,
}
impl Config {
fn is_valid(&self) -> Result<()> {
match &self.r#type.to_lowercase()[..] {
"github" | "bitbucketcloud" | "bitbucketserver" => Ok(()),
unknown_type => Err(Error::UnknownConfigType(unknown_type.to_owned())),
}
}
}
pub fn load(path: Option<&str>) -> Result<Config> {
let mut settings = ConfigRs::default();
if let Some(path) = path {
settings.merge(config::File::with_name(path))?;
} else {
settings.merge(config::File::with_name("fixme_settings"))?;
}
settings.merge(config::Environment::with_prefix("FIXME"))?;
let cfg: Config = settings.try_into().map_err(Error::from)?;
cfg.is_valid()?;
Ok(cfg)
}
| true |
add6a16c5bd5484939a782abb6188d76dcbbc348
|
Rust
|
y3ll0wlife/rust-programming-book
|
/variables/src/main.rs
|
UTF-8
| 170 | 2.9375 | 3 |
[
"MIT"
] |
permissive
|
// Print the lyrics to the Christmas carol “The Twelve Days of Christmas,” taking advantage of the repetition in the song.
fn main() {
println!("Hello World")
}
| true |
0b8366c81aa8384276d8ee66014def5bb7f0171c
|
Rust
|
mtthw-meyer/misra-rust
|
/tests/compile-fail/Rule_13_5.rs
|
UTF-8
| 270 | 3.484375 | 3 |
[
"MIT"
] |
permissive
|
/// This function has a side effect.
fn not(x: &mut bool) -> &mut bool {
*x = !*x;
x
}
fn main() {
let mut x: bool = true;
if *not(&mut x) || *not(&mut x) {
//~^ ERROR Non-compliant - right hand operand contains persistent side-effects
}
}
| true |
b5098cbbf9ddfdc986124835006bd3c2329d595e
|
Rust
|
AlexShkor/deip-polkadot
|
/pallets/deip_toolkit/src/storage_ops.rs
|
UTF-8
| 1,062 | 3.171875 | 3 |
[
"Apache-2.0"
] |
permissive
|
//! Module contains abstractions over storage operations
//!
//!
use sp_std::collections::vec_deque::VecDeque;
/// Storage operation
pub trait StorageOp {
fn exec(self);
}
/// Fifo-queue for storage operations
pub struct StorageOpsQueue<T>(VecDeque<T>);
impl<T> StorageOpsQueue<T> {
/// Add storage operation
pub fn push_op(&mut self, op: T) -> &mut Self {
self.0.push_back(op);
self
}
fn pop_op(&mut self) -> Option<T> { self.0.pop_front() }
}
/// Multi-ops storage transaction
pub struct StorageOpsTransaction<Op>(StorageOpsQueue<Op>);
impl<Op: StorageOp> StorageOpsTransaction<Op> {
/// New storage transaction
pub fn new() -> Self { Self(StorageOpsQueue(VecDeque::new())) }
/// Execute callable then perform storage operations provided via ops-queue
pub fn commit<R>(mut self, transactional: impl FnOnce(&mut StorageOpsQueue<Op>) -> R) -> R {
let result = transactional(&mut self.0);
while let Some(op) = self.0.pop_op() {
op.exec();
}
result
}
}
| true |
26208c2d607ab7c59633b4b82f8718a42e65ddc8
|
Rust
|
hrlmartins/advent-of-code-2019
|
/day_10/p1/src/main.rs
|
UTF-8
| 3,019 | 3.375 | 3 |
[] |
no_license
|
extern crate num_rational;
use std::io::{self, BufReader, Read, BufRead};
use num_rational::Ratio;
use std::collections::HashSet;
#[derive(Debug, PartialEq, Eq)]
struct Point {
x: i32,
y: i32
}
impl Point {
fn new(x: i32, y: i32) -> Point {
Point {
x,
y
}
}
}
#[derive(Debug, PartialEq, Eq, Hash)]
struct Line {
m: num_rational::Rational,
b: num_rational::Rational,
up: bool // up... but in fact i'll use it for horizontal lines as well
}
impl Line {
fn new(p1: &Point, p2: &Point) -> Line {
if p1.x == p2.x {
// It's vertical... gonna create standard value..
Line {
m: num_rational::Rational::from(Ratio::new(0, 1)),
b: num_rational::Rational::from(Ratio::new(0, 1)),
up: p2.y > p1.y
}
} else {
let m = num_rational::Rational::from(Ratio::new((p2.y - p1.y) as isize, (p2.x - p1.x) as isize));
Line {
m,
b: Line::find_b(&p1, &m),
up: if p1.y == p2.y {
p2.x > p1.x // going right if true, left if false
} else {
p2.y > p1.y // this one actually says if we're going up or down... well sorta
}
}
}
}
fn find_b(p: &Point, m: &num_rational::Rational) -> num_rational::Rational {
// slope function is from type y=mx+b. Substitute and solve for b.
// y - mx = b
let y = num_rational::Ratio::from_integer(p.y as isize);
let x = num_rational::Ratio::from_integer(p.x as isize);
num_rational::Rational::from(y - (m * x))
}
}
fn main() {
read_and_compute_by_line(io::stdin());
}
fn read_and_compute_by_line<T: Read>(reader: T) -> io::Result<()> {
let buffer = BufReader::new(reader);
let asteroids = store_asteroids(buffer).unwrap();
let mut max_count = 0;
for asteroid in asteroids.iter() {
max_count = max_count.max(count_lines(asteroid, &asteroids));
}
println!("Max possible sights is: {}", max_count);
// Point x: 29, y: 28
Ok(())
}
fn count_lines(asteroid: &Point, asteroids: &Vec<Point>) -> i32 {
let mut lines = HashSet::new();
for other_asteroid in asteroids {
if other_asteroid != asteroid {
lines.insert(Line::new(asteroid, other_asteroid));
}
}
lines.len() as i32
}
fn store_asteroids<T: Read>(buffer: BufReader<T>) -> io::Result<Vec<Point>> {
let mut curr_x = 0;
let mut curr_y = 0;
let mut points: Vec<Point> = Vec::new();
for line in buffer.lines() {
line?.chars().for_each(|c| {
print!("{}", c);
match c {
'#' => {
points.push(Point::new(curr_x, curr_y))
},
_ => {}
};
curr_x += 1;
});
curr_y += 1;
curr_x = 0;
println!();
}
Ok(points)
}
| true |
3b3a662a0eefc9f4a46a5ae6ebd6575562ac05b0
|
Rust
|
ExPixel/miniaudio-rs
|
/miniaudio/examples/simple-enumeration.rs
|
UTF-8
| 1,485 | 2.859375 | 3 |
[
"MIT"
] |
permissive
|
use miniaudio::{Context, DeviceId, DeviceType, ShareMode};
pub fn main() {
let context = Context::new(&[], None).expect("failed to create context");
context
.with_devices(|playback_devices, capture_devices| {
println!("Playback Devices:");
for (idx, device) in playback_devices.iter().enumerate() {
println!("\t{}: {}", idx, device.name());
print_device_info(&context, DeviceType::Playback, device.id());
}
println!("Capture Devices:");
for (idx, device) in capture_devices.iter().enumerate() {
println!("\t{}: {}", idx, device.name());
print_device_info(&context, DeviceType::Capture, device.id());
}
})
.expect("failed to get devices");
}
pub fn print_device_info(context: &Context, device_type: DeviceType, device_id: &DeviceId) {
// This can fail, so we have to check the result.
let info = match context.get_device_info(device_type, device_id, ShareMode::Shared) {
Ok(info) => info,
Err(err) => {
eprintln!("\t\tfailed to get device info: {}", err);
return;
}
};
println!(
"\t\tSample Rate: {}-{}Hz",
info.min_sample_rate(),
info.max_sample_rate()
);
println!(
"\t\tChannels: {}-{}",
info.min_channels(),
info.max_channels()
);
println!("\t\tFormats: {:?}", info.formats());
}
| true |
c744fc0b856e89a6104a328c30bfbb96381d544e
|
Rust
|
orionz/wasm-skiplist
|
/neon/native/src/lib.rs
|
UTF-8
| 7,118 | 3 | 3 |
[] |
no_license
|
#[macro_use]
extern crate neon;
extern crate skip_list;
use skip_list::{TreeMap,ListMap};
use neon::prelude::*;
fn hello(mut cx: FunctionContext) -> JsResult<JsString> {
Ok(cx.string("hello node"))
}
pub struct Skip {
data: TreeMap<String,String>
}
declare_types! {
pub class MyClass for Skip {
init(mut _cx) {
Ok(Skip {
data: TreeMap::new()
})
}
/*
fn index_of(&self, key: &K) -> Option<usize>;
fn insert(&mut self, index: usize, key: K, val: V);
fn remove(&mut self, index: usize) -> Option<K>;
fn get_key(&self, index: usize) -> Option<&K>;
fn get_value(&self, index: usize) -> Option<&V>;
fn set(&mut self, key: &K, val: V) -> bool;
fn insert_after(&mut self, node: &K, key: K, val: V)
fn get(&self, key: &K) -> Option<&V>
*/
// string -> int
method indexOf(mut cx) {
let key: Handle<JsString> = cx.argument::<JsString>(0)?;
let i = {
let this = cx.this();
let guard = cx.lock();
let skip = this.borrow(&guard);
skip.data.index_of(&key.value()).map(|n| n as f64).unwrap_or(-1.0)
};
Ok(cx.number(i).upcast())
}
method _insertAfter(mut cx) {
let mut copy = cx.argument::<MyClass>(0)?;
let after = cx.argument::<JsValue>(1)?;
let key: Handle<JsString> = cx.argument::<JsString>(2)?;
let val: Handle<JsString> = cx.argument::<JsString>(3)?;
/*
let args: Vec<Handle<JsValue>> = vec![];
let n = MyClass::new(&mut cx, args);
// vs
let args: Vec<Handle<JsValue>> = vec![];
let mut copy : Handle<MyClass> = MyClass::constructor(&mut cx)?.construct(&mut cx, args)?;
*/
{
let this = cx.this();
let guard1 = cx.lock();
let guard2 = cx.lock();
let oldskip = this.borrow(&guard1);
let mut newskip = copy.borrow_mut(&guard2);
let data = oldskip.data.clone();
newskip.data = data;
if let Ok(s) = after.downcast::<JsString>() {
newskip.data.insert_after(&s.value(),key.value(),val.value());
} else {
newskip.data.insert(0,key.value(),val.value());
}
};
Ok(copy.upcast())
}
// string -> ()
method _removeKey(mut cx) {
let mut copy = cx.argument::<MyClass>(0)?;
let key: Handle<JsString> = cx.argument::<JsString>(1)?;
{
let this = cx.this();
let guard1 = cx.lock();
let guard2 = cx.lock();
let oldskip = this.borrow(&guard1);
let mut newskip = copy.borrow_mut(&guard2);
let i = oldskip.data.index_of(&key.value()).unwrap(); // throw if no key
newskip.data = oldskip.data.clone();
newskip.data.remove(i);
}
Ok(copy.upcast())
}
// int -> string
method keyOf(mut cx) {
let index_handle: Handle<JsNumber> = cx.argument::<JsNumber>(0)?;
let result = {
let index = index_handle.value() as isize;
let this = cx.this();
let guard = cx.lock();
let skip = this.borrow(&guard);
if index == -1 {
skip.data.get_key(skip.data.len() - 1).cloned()
} else {
skip.data.get_key(index as usize).cloned()
}
};
if let Some(string) = result {
Ok(cx.string(string).upcast())
} else {
Ok(cx.null().upcast())
}
}
// int -> jsval
method valueOf(mut cx) {
let index_handle: Handle<JsNumber> = cx.argument::<JsNumber>(0)?;
let result = {
let index = index_handle.value() as isize;
let this = cx.this();
let guard = cx.lock();
let skip = this.borrow(&guard);
if index == -1 {
skip.data.get_value(skip.data.len() - 1).cloned()
} else {
skip.data.get_value(index as usize).cloned()
}
};
if let Some(string) = result {
Ok(cx.string(string).upcast())
} else {
Ok(cx.null().upcast())
}
}
// string -> value
method getValue(mut cx) {
let key: Handle<JsString> = cx.argument::<JsString>(0)?;
let result = {
let this = cx.this();
let guard = cx.lock();
let skip = this.borrow(&guard);
skip.data.get(&key.value()).cloned()
};
if let Some(string) = result {
Ok(cx.string(string).upcast())
} else {
Ok(cx.undefined().upcast())
}
}
// string, value -> ()
method _setValue(mut cx) {
let mut copy: Handle<MyClass> = cx.argument::<MyClass>(0)?;
let key: Handle<JsString> = cx.argument::<JsString>(1)?;
let val: Handle<JsString> = cx.argument::<JsString>(2)?;
let data = {
let this = cx.this();
let guard = cx.lock();
let skip = this.borrow(&guard);
skip.data.clone()
};
let ok = {
let guard = cx.lock();
let mut skip = copy.borrow_mut(&guard);
skip.data = data;
skip.data.set(&key.value(),val.value())
};
if ok {
Ok(copy.upcast())
} else {
cx.throw_error("referenced key does not exist")
}
}
// int, string, value -> ()
method _insertIndex(mut cx) {
let mut copy: Handle<MyClass> = cx.argument::<MyClass>(0)?;
let index = cx.argument::<JsNumber>(1)?.value() as usize;
let key: Handle<JsString> = cx.argument::<JsString>(2)?;
let val: Handle<JsString> = cx.argument::<JsString>(3)?;
let data = {
let this = cx.this();
let guard = cx.lock();
let skip = this.borrow(&guard);
skip.data.clone()
};
// let mut this = cx.this().clone();
{
let guard = cx.lock();
let mut skip = copy.borrow_mut(&guard);
skip.data = data;
skip.data.insert(index,key.value(),val.value());
}
Ok(copy.upcast())
}
// int -> ()
method _removeIndex(mut cx) {
let mut copy: Handle<MyClass> = cx.argument::<MyClass>(0)?;
let index: Handle<JsNumber> = cx.argument::<JsNumber>(1)?;
let data = {
let this = cx.this();
let guard = cx.lock();
let skip = this.borrow(&guard);
skip.data.clone()
};
// let mut this = cx.this().clone();
let ok = {
let guard = cx.lock();
let mut skip = copy.borrow_mut(&guard);
skip.data = data;
skip.data.remove(index.value() as usize)
};
if ok.is_some() {
Ok(copy.upcast())
} else {
cx.throw_error("key cannot be removed")
}
}
method get(mut cx) {
let attr: String = cx.argument::<JsString>(0)?.value();
let this = cx.this();
match &attr[..] {
"length" => {
let length = {
let guard = cx.lock();
let user = this.borrow(&guard);
user.data.len()
};
Ok(cx.number(length as f64).upcast())
},
_ => cx.throw_type_error("property does not exist")
}
}
}
}
register_module!(mut cx, {
cx.export_function("hello", hello)?;
cx.export_class::<MyClass>("SkipList")?;
Ok(())
});
| true |
c29a3808000620a8c6a28511b90e0f8a391dcef8
|
Rust
|
vandomej/Crogue
|
/src/game/actors/player.rs
|
UTF-8
| 2,649 | 3.125 | 3 |
[
"MIT"
] |
permissive
|
use tcod::input::Key;
use tcod::console::*;
use tcod::colors;
use std::io;
use game::map::tile::Tile;
use game::actors::health::Health;
use game::actors::game_object::GameObject;
#[derive(Debug, Clone)]
pub struct Player {
pub x: i32,
pub y: i32,
head: i32,
arms: Vec<i32>,
torso: i32,
legs: Vec<i32>,
symbol: char
}
impl Player {
pub fn new(x: i32, y: i32) -> Player {
return Player {
x,
y,
head: 100,
arms: vec![100, 100],
torso: 100,
legs: vec![100, 100],
symbol: '@',
};
}
pub fn update(&mut self, key: Option<Key>, tiles: &Vec<Box<Tile>>) -> bool {
return if key.is_some() && key.unwrap().pressed {
self.handle_key(key, tiles)
} else {
false
}
}
fn handle_key(&mut self, key: Option<Key>, tiles: &Vec<Box<Tile>>) -> bool {
use tcod::input::KeyCode::*;
let mut proposed_x = 0;
let mut proposed_y = 0;
match key {
Some(Key { code: Up, .. }) => proposed_y -= 1,
Some(Key { code: Down, .. }) => proposed_y += 1,
Some(Key { code: Left, .. }) => proposed_x -= 1,
Some(Key { code: Right, .. }) => proposed_x += 1,
_ => {},
}
let x = self.x;
let y = self.y;
GameObject::move_object(self, tiles, x + proposed_x, y + proposed_y).unwrap()
}
pub fn draw_hud(&self, window: &Root) {
self.draw_health(self.head, "H ", 0, window);
self.draw_health(self.arms[0], "AL", 1, window);
self.draw_health(self.arms[1], "AR", 2, window);
self.draw_health(self.torso, "T ", 3, window);
self.draw_health(self.legs[0], "LL", 4, window);
self.draw_health(self.legs[1], "LR", 5, window);
}
fn draw_health(&self, health: i32, label: &str, row: i32, mut window: &Root) {
let line = format!("{:2} {: >4} ", label, health);
let foreground_color =
if health <= 33 {
colors::DARK_RED
}
else if health >= 66 {
colors::DARK_GREEN
}
else {
colors::WHITE
};
let background_color = window.get_default_background();
for (i, c) in line.chars().enumerate() {
window.put_char_ex(i as i32, row, c, foreground_color, background_color)
}
}
pub fn clear(&self, mut window: &Root) {
window.put_char(self.x, self.y, ' ', BackgroundFlag::Set);
}
}
implement_health!(Player);
implement_gameobject!(Player);
| true |
8650da35c50b54269c60030bec2d2c21858d260d
|
Rust
|
cooljohnny3/numerical-methods
|
/src/lib.rs
|
UTF-8
| 12,633 | 3.359375 | 3 |
[] |
no_license
|
use std::{f64::{INFINITY}};
pub fn add(x: &Vec<isize>, y: &Vec<isize>) -> Vec<isize> {
let mut result: Vec<isize>;
let length: usize = usize::min(x.len(), y.len());
if x.len() > y.len() {
result = x.clone();
} else {
result = y.clone();
}
for i in 0..length {
let temp = &x[i] + &y[i];
result[i] = temp;
}
result
}
pub fn subtract(x: &Vec<isize>, y: &Vec<isize>) -> Vec<isize> {
let mut result: Vec<isize>;
let length: usize = usize::min(x.len(), y.len());
if x.len() > y.len() {
result = x.clone();
} else {
result = negate(&y);
}
for i in 0..length {
let temp = &x[i] - &y[i];
result[i] = temp;
}
result
}
pub fn negate(x: &Vec<isize>) -> Vec<isize> {
x.into_iter().map(|x| -x).collect()
}
pub fn magnitude(x: &Vec<isize>) -> f64 {
let mut sum = 0;
for element in x {
sum = sum + element.pow(2);
}
(sum as f64).sqrt()
}
pub fn newton<T, N>(n: isize, x: f64, f: T, fprime: N, print: bool) -> Result<f64, &'static str>
where T: Fn(f64) -> f64,
N: Fn(f64) -> f64,
{
if fprime(x) == INFINITY {
return Err("ERROR: Divide by zero.")
}
if n < 0 {
return Ok(x)
}
let new_x = x - (f(x)/fprime(x));
if print {
println!("{:.52}", new_x);
}
newton(n-1, new_x, f, fprime, print)
}
pub fn secant<T>(n: isize, x1: f64, x2: f64, f: T, print: bool) -> Result<f64, &'static str>
where T: Fn(f64) -> f64,
{
if n < 0 || x1 == x2 {
return Ok(x1)
}
let new_x1 = ((x2*f(x1))-(x1*f(x2)))/(f(x1)-f(x2));
if print {
println!("{:.52}", new_x1);
}
secant(n-1, new_x1, x1, f, print)
}
pub fn dot(a: &Vec<isize>, b: &Vec<isize>) -> Result<isize, String> {
if a.len() != b.len() {
return Err(String::from("Vectors are not equal lengths."));
} else if a.len() == 0 {
return Err(String::from("Vectors are empty."));
} else {
let mut sum = 0;
for i in 0..a.len() {
sum = sum + a[i] * b[i];
}
Ok(sum)
}
}
pub fn cross(a: &Vec<isize>, b: &Vec<isize>) -> Result<Vec<isize>, String> {
if a.len() == 0 || b.len() == 0 {
return Err(String::from("One or more vectors are empty"));
} else if a.len() != 3 || b.len() != 3 {
return Err(String::from("One or more vectors are not 3d"));
} else {
let s1: isize = a[1]*b[2] - a[2]*b[1];
let s2: isize = a[2]*b[0] - a[0]*b[2];
let s3: isize = a[0]*b[1] - a[1]*b[0];
Ok(vec![s1, s2, s3])
}
}
#[cfg(test)]
mod add_tests {
use super::add;
#[test]
fn test_simple1() {
let vec1: Vec<isize> = vec![1,2,3,4];
let vec2: Vec<isize> = vec![2,4,6,8];
assert_eq!(add(&vec1, &vec2), [3,6,9,12]);
}
#[test]
fn test_simple2() {
let vec1: Vec<isize> = vec![4,1,7,5,2];
let vec2: Vec<isize> = vec![324,90,32,54,9];
assert_eq!(add(&vec1, &vec2), [328,91,39,59,11]);
}
#[test]
fn test_different_sizes1() {
let vec1: Vec<isize> = vec![1,2,3,4];
let vec2: Vec<isize> = vec![2,4];
assert_eq!(add(&vec1, &vec2), [3,6,3,4]);
}
#[test]
fn test_different_sizes2() {
let vec1: Vec<isize> = vec![1,2];
let vec2: Vec<isize> = vec![2,4,6,8];
assert_eq!(add(&vec1, &vec2), [3,6,6,8]);
}
}
#[cfg(test)]
mod subtract_tests {
use super::subtract;
#[test]
fn test_simple1() {
let vec1: Vec<isize> = vec![1,2,3,4];
let vec2: Vec<isize> = vec![2,4,6,8];
assert_eq!(subtract(&vec1, &vec2), [-1,-2,-3,-4]);
}
#[test]
fn test_simple2() {
let vec1: Vec<isize> = vec![324,90,32,54,9];
let vec2: Vec<isize> = vec![4,1,7,5,2];
assert_eq!(subtract(&vec1, &vec2), [320,89,25,49,7]);
}
#[test]
fn test_different_sizes1() {
let vec1: Vec<isize> = vec![1,2,3,4];
let vec2: Vec<isize> = vec![2,4];
assert_eq!(subtract(&vec1, &vec2), [-1,-2,3,4]);
}
#[test]
fn test_different_sizes2() {
let vec1: Vec<isize> = vec![1,2];
let vec2: Vec<isize> = vec![2,4,6,8];
assert_eq!(subtract(&vec1, &vec2), [-1,-2,-6,-8]);
}
}
#[cfg(test)]
mod negate_tests {
use super::negate;
#[test]
fn test_simple1() {
let vec1: Vec<isize> = vec![1,2,3,4];
assert_eq!(negate(&vec1), [-1,-2,-3,-4]);
}
#[test]
fn test_simple2() {
let vec1: Vec<isize> = vec![324,90,32,54,9];
assert_eq!(negate(&vec1), [-324,-90,-32,-54,-9]);
}
}
#[cfg(test)]
mod magnitude_tests {
use super::magnitude;
#[test]
fn test_simple1() {
let vec1: Vec<isize> = vec![3,4];
assert_eq!(magnitude(&vec1), 5.0);
}
#[test]
fn test_simple2() {
let vec1: Vec<isize> = vec![9,12];
assert_eq!(magnitude(&vec1), 15.0);
}
}
#[cfg(test)]
mod newton_tests {
use super::newton;
#[test]
fn test_prime_equals_zero() {
let f= |x| -> f64 { (x*x) - 2.0 };
let fprime = |x| -> f64 { 2.0*x };
let guess: f64 = 0.0;
assert_eq!(newton(100, guess, f, fprime, false), Err("ERROR: Divide by zero."));
}
#[test]
fn test_simple_case_positive_guess() {
let f= |x| -> f64 { x - 2.0 };
let fprime = |_x| -> f64 { 1.0 };
let guess: f64 = 5.0;
assert_eq!(newton(100, guess, f, fprime, false), Ok(2.0));
}
#[test]
fn test_simple_case_negative_guess() {
let f= |x| -> f64 { x - 2.0 };
let fprime = |_x| -> f64 { 1.0 };
let guess: f64 = -5.0;
assert_eq!(newton(100, guess, f, fprime, false), Ok(2.0));
}
}
#[cfg(test)]
mod secant_tests {
use super::secant;
#[test]
fn test_simple_case_positive_guess() {
let f= |x| -> f64 { x - 2.0 };
let guess1: f64 = 5.0;
let guess2: f64 = 2.0;
assert_eq!(secant(100, guess1, guess2, f, false), Ok(2.0));
}
#[test]
fn test_simple_case_negative_guess() {
let f= |x| -> f64 { x - 2.0 };
let guess1: f64 = -5.0;
let guess2: f64 = 2.0;
assert_eq!(secant(100, guess1, guess2, f, false), Ok(2.0));
}
}
#[cfg(test)]
mod dot_tests {
use std::vec;
use super::{add, dot};
#[test]
fn test_simple1() {
let a: Vec<isize> = vec![1,2,3,4];
let b: Vec<isize> = vec![4,3,2,1];
assert_eq!(dot(&b, &a).unwrap(), 20);
}
#[test]
fn test_simple2() {
let a: Vec<isize> = vec![1,2];
let b: Vec<isize> = vec![4,3];
assert_eq!(dot(&b, &a).unwrap(), 10);
}
#[test]
fn test_simple3() {
let a: Vec<isize> = vec![245, 647];
let b: Vec<isize> = vec![876, 123];
assert_eq!(dot(&b, &a).unwrap(), 294201);
}
#[test]
fn test_simple_with_negatives1() {
let a: Vec<isize> = vec![1,-2,3,4];
let b: Vec<isize> = vec![4,3,2,-1];
assert_eq!(dot(&b, &a).unwrap(), 0);
}
#[test]
fn test_simple_with_negatives2() {
let a: Vec<isize> = vec![1,-2];
let b: Vec<isize> = vec![4,3];
assert_eq!(dot(&b, &a).unwrap(), -2);
}
#[test]
fn test_simple_with_negatives3() {
let a: Vec<isize> = vec![245, 647];
let b: Vec<isize> = vec![-876, 123];
assert_eq!(dot(&b, &a).unwrap(), -135039);
}
#[test]
fn test_one_empty_vec1() {
let a: Vec<isize> = vec![1,2,3,4];
let b: Vec<isize> = vec![];
assert_eq!(dot(&b, &a).unwrap_err(), "Vectors are not equal lengths.");
}
#[test]
fn test_one_empty_vec2() {
let a: Vec<isize> = vec![];
let b: Vec<isize> = vec![1,2,3,4];
assert_eq!(dot(&b, &a).unwrap_err(), "Vectors are not equal lengths.");
}
#[test]
fn test_two_empty_vec() {
let a: Vec<isize> = vec![];
let b: Vec<isize> = vec![];
assert_eq!(dot(&b, &a).unwrap_err(), "Vectors are empty.");
}
#[test]
fn test_different_length_vecs1() {
let a: Vec<isize> = vec![1,2,3,4];
let b: Vec<isize> = vec![];
assert_eq!(dot(&b, &a).unwrap_err(), "Vectors are not equal lengths.")
}
#[test]
fn test_different_length_vecs2() {
let a: Vec<isize> = vec![];
let b: Vec<isize> = vec![1,2,3,4];
assert_eq!(dot(&b, &a).unwrap_err(), "Vectors are not equal lengths.")
}
#[test]
fn test_commutative() {
let a: Vec<isize> = vec![1,2,3,4];
let b: Vec<isize> = vec![4,3,2,1];
assert_eq!(dot(&a, &b), dot(&b, &a))
}
#[test]
fn test_distributive() {
let a: Vec<isize> = vec![1,2,3,4];
let b: Vec<isize> = vec![4,3,2,1];
let c: Vec<isize> = vec![5,6,7,8];
let d: Vec<isize> = add(&b, &c);
assert_eq!(dot(&a, &d).unwrap(), dot(&a, &b).unwrap() + dot(&a, &c).unwrap())
}
#[test]
fn test_bilinear() {
}
#[test]
fn test_scalar_multiplication() {
}
#[test]
fn test_not_associative() {
}
#[test]
fn test_orthogonal() {
}
#[test]
fn test_not_cancellation() {
}
#[test]
fn test_product_rule() {
}
}
#[cfg(test)]
mod cross_tests {
use std::vec;
use super::{add, cross};
#[test]
fn test_one_not_3d1() {
let a: Vec<isize> = vec![1,2,3];
let b: Vec<isize> = vec![1,2];
assert_eq!(cross(&a, &b).unwrap_err(), "One or more vectors are not 3d");
}
#[test]
fn test_one_not_3d2() {
let a: Vec<isize> = vec![1,2];
let b: Vec<isize> = vec![1,2,3];
assert_eq!(cross(&a, &b).unwrap_err(), "One or more vectors are not 3d");
}
#[test]
fn test_one_empty1() {
let a: Vec<isize> = vec![1,2,3];
let b: Vec<isize> = vec![];
assert_eq!(cross(&a, &b).unwrap_err(), "One or more vectors are empty");
}
#[test]
fn test_one_empty2() {
let a: Vec<isize> = vec![];
let b: Vec<isize> = vec![1,2,3];
assert_eq!(cross(&a, &b).unwrap_err(), "One or more vectors are empty");
}
#[test]
fn test_both_empty() {
let a: Vec<isize> = vec![];
let b: Vec<isize> = vec![];
assert_eq!(cross(&a, &b).unwrap_err(), "One or more vectors are empty");
}
#[test]
fn test_same_vectors() {
// a X a = 0
let a: Vec<isize> = vec![1,2,3];
let b: Vec<isize> = vec![1,2,3];
assert_eq!(cross(&a, &b).unwrap(), vec![0,0,0]);
}
#[test]
fn test_anticommutative() {
// a X b = -(b X a)
let a: Vec<isize> = vec![1,2,3];
let b: Vec<isize> = vec![3,2,3];
let negative_ans: Vec<isize> = cross(&b, &a).unwrap().into_iter().map(|x| -x).collect();
assert_eq!(cross(&a, &b).unwrap(), negative_ans);
}
#[test]
fn test_distributive_over_addition() {
// a X (b + c) = (a X b) + (a X c)
let a: Vec<isize> = vec![1,2,3];
let b: Vec<isize> = vec![3,2,3];
let c: Vec<isize> = vec![3,2,3];
let d: Vec<isize> = add(&b, &c); // b + c
assert_eq!(cross(&a, &d).unwrap(), add(&cross(&a, &b).unwrap(), &cross(&a, &c).unwrap()));
}
#[test]
fn test_scalar_multiplication() {
// (ra) X b = a X (rb) = r(a X b)
// r = 2
let a: Vec<isize> = vec![1,2,3];
let ra: Vec<isize> = vec![2,4,6];
let b: Vec<isize> = vec![3,2,3];
let rb: Vec<isize> = vec![6,4,6];
let first: Vec<isize> = cross(&ra, &b).unwrap();
let second: Vec<isize> = cross(&a, &rb).unwrap();
let third: Vec<isize> = cross(&a, &b).unwrap().into_iter().map(|x| x*2).collect();
assert_eq!(first, second);
assert_eq!(second, third);
assert_eq!(first, third);
}
#[test]
fn test_not_associative_but_satisfies_jacobi_iden() {
// a X (b X c) +
// b X (c X a) +
// c X (a X b)
// = 0
let a: Vec<isize> = vec![1,2,3];
let b: Vec<isize> = vec![3,2,3];
let c: Vec<isize> = vec![3,2,4];
let first: Vec<isize> = cross(&a, &cross(&b, &c).unwrap()).unwrap();
let second: Vec<isize> = cross(&b, &cross(&c, &a).unwrap()).unwrap();
let third: Vec<isize> = cross(&c, &cross(&a, &b).unwrap()).unwrap();
assert_eq!(add(&add(&first, &second), &third), vec![0,0,0]);
}
}
| true |
e0f5332f463a423ed50748441c0dc1247e8831e3
|
Rust
|
BenoitZugmeyer/RustyAdventOfCode
|
/2015/src/bin/day16.rs
|
UTF-8
| 3,378 | 3.203125 | 3 |
[] |
no_license
|
#[macro_use]
extern crate lazy_static;
extern crate regex;
use regex::Regex;
use std::borrow::Borrow;
use std::collections::HashMap;
use std::io;
use std::io::BufRead;
#[derive(Debug)]
struct Things {
name: String,
data: HashMap<String, u8>,
}
impl Things {
fn new(name: &str) -> Self {
Things {
name: name.to_string(),
data: HashMap::new(),
}
}
fn new_from_line(line: &str) -> Option<Self> {
lazy_static! {
static ref RE: Regex = Regex::new(r"([a-z]+): (\d+)").unwrap();
}
line.find(':').map(|pos| {
let (name, things) = line.split_at(pos);
let mut result = Self::new(name);
for capture in RE.captures_iter(things) {
result.set(
capture.at(1).unwrap(),
capture.at(2).unwrap().parse().unwrap(),
);
}
result
})
}
fn set(&mut self, key: &str, value: u8) {
self.data.insert(key.to_string(), value);
}
fn _matches<F: Fn(&str, &u8, &u8) -> bool>(&self, expectations: &Self, cmp: F) -> bool {
self.data.iter().all(|(key, value)| {
expectations.data.get(key).map_or(false, |expected_value| {
cmp(key.borrow(), value, expected_value)
})
})
}
fn matches(&self, expectations: &Self) -> bool {
self._matches(expectations, |_, value, expected_value| {
value == expected_value
})
}
fn adjusted_matches(&self, expectations: &Self) -> bool {
self._matches(expectations, |key, value, expected_value| match key {
"cats" | "trees" => value > expected_value,
"pomeranians" | "goldfish" => value < expected_value,
_ => value == expected_value,
})
}
}
fn print_aunt_sue_name_found(which: &str, name_found: Option<String>) {
if let Some(name) = name_found {
println!("{} Aunt Sue found: {}", which, name);
} else {
println!("{} Aunt Sue not found :(", which);
}
}
fn main() {
let stdin = io::stdin();
let mut expectations = Things::new("Expectations");
expectations.set("children", 3);
expectations.set("cats", 7);
expectations.set("samoyeds", 2);
expectations.set("pomeranians", 3);
expectations.set("akitas", 0);
expectations.set("vizslas", 0);
expectations.set("goldfish", 5);
expectations.set("trees", 3);
expectations.set("cars", 2);
expectations.set("perfumes", 1);
let aunt_sues = stdin
.lock()
.lines()
.filter_map(|l| l.ok())
.filter_map(|ref line| Things::new_from_line(line));
let mut unadjusted_aunt_sue: Option<String> = None;
let mut real_aunt_sue: Option<String> = None;
for aunt_sue in aunt_sues {
if unadjusted_aunt_sue.is_none() && aunt_sue.matches(&expectations) {
unadjusted_aunt_sue = Some(aunt_sue.name.clone());
}
if real_aunt_sue.is_none() && aunt_sue.adjusted_matches(&expectations) {
real_aunt_sue = Some(aunt_sue.name.clone());
}
if unadjusted_aunt_sue.is_some() && real_aunt_sue.is_some() {
break;
}
}
print_aunt_sue_name_found("Unadjusted", unadjusted_aunt_sue);
print_aunt_sue_name_found("Real", real_aunt_sue);
}
| true |
483dfb64facd570bf5e0e0c1eaa99feb9e26de72
|
Rust
|
tiagosr/cachoeira
|
/cachoeira_core/src/console.rs
|
UTF-8
| 1,455 | 3.015625 | 3 |
[
"MIT"
] |
permissive
|
use std::collections::HashMap;
use std::sync::mpsc;
use std::result;
use std::cell::RefCell;
use std::ops::Deref;
use std::borrow::Borrow;
pub type ConsoleVarResult = Result<Option<String>, String>;
pub trait ConsoleVar {
fn set(&mut self, String) -> ConsoleVarResult;
fn get(&self) -> String;
}
#[derive(Debug)]
pub struct ConsoleVarString {
value: String,
}
impl ConsoleVar for ConsoleVarString {
fn set(&mut self, value: String) -> ConsoleVarResult {
self.value = value;
Ok(None)
}
fn get(&self) -> String {
self.value.clone()
}
}
type ConsoleContextHashmap = HashMap<String, RefCell<Box<ConsoleVar>>>;
pub struct ConsoleContext {
vars: ConsoleContextHashmap,
}
impl ConsoleContext {
fn query_var(&self, key: &str) -> Option<String> {
match self.vars.get(key) {
None => None,
Some(val) => Some((*val.borrow().deref()).get()),
}
}
fn write_var(&mut self, key: &str, val: &str) -> Option<ConsoleVarResult> {
match self.vars.get(key) {
None => None,
Some(result) => Some(result.borrow_mut().set(val.to_string())),
}
}
fn add_var(&mut self, key: &str, var: RefCell<Box<ConsoleVar>>) -> &mut Self {
self.vars.insert(key.to_string(), var);
self
}
}
impl Default for ConsoleContext {
fn default() -> Self {
Self { vars: ConsoleContextHashmap::new(), }
}
}
| true |
4c57a719885d2ddd839f71668ba325230dbed7ad
|
Rust
|
logtopus/logtopus
|
/src/cfg.rs
|
UTF-8
| 3,701 | 3.03125 | 3 |
[
"Apache-2.0"
] |
permissive
|
use config;
use config::ConfigError;
use std::path::Path;
pub fn read_config<S: AsRef<str>>(
maybe_filename: &Option<S>,
) -> Result<config::Config, config::ConfigError> {
let mut settings = config::Config::new();
let defaults = include_bytes!("default_config.yml");
settings.merge(config::File::from_str(
String::from_utf8_lossy(defaults).as_ref(),
config::FileFormat::Yaml,
))?;
match maybe_filename {
Some(filename_ref) => {
let filename = filename_ref.as_ref();
if !Path::new(filename).exists() {
return Err(ConfigError::Message(format!(
"Configuration file {} does not exist",
filename
)));
} else {
settings.merge(config::File::with_name(&filename))?
}
}
None => &settings,
};
settings.merge(config::Environment::with_prefix("app"))?;
Ok(settings)
}
#[cfg(test)]
mod tests {
use crate::cfg;
use crate::tentacle::*;
#[test]
fn test_read_config() {
let settings = cfg::read_config(&Some("tests/test.yml")).unwrap();
assert_eq!(28081, settings.get_int("http.bind.port").unwrap());
assert_eq!("127.0.0.1", settings.get_str("http.bind.ip").unwrap());
let tentacles: Vec<TentacleInfo> = settings
.get_array("tentacles")
.unwrap()
.into_iter()
.map(|v| TentacleClient::parse_tentacle(v).unwrap())
.collect();
assert_eq!(
vec![
TentacleInfo {
name: String::from("tentacle_1"),
host: String::from("localhost"),
port: 18080,
protocol: String::from("http")
},
TentacleInfo {
name: String::from("tentacle_2"),
host: String::from("localhost"),
port: 18081,
protocol: String::from("http")
}
],
tentacles
);
}
#[test]
fn test_read_config_no_alias() {
let settings = cfg::read_config(&Some("tests/test_no_alias.yml")).unwrap();
assert_eq!(28081, settings.get_int("http.bind.port").unwrap());
assert_eq!("127.0.0.1", settings.get_str("http.bind.ip").unwrap());
let tentacles: Vec<TentacleInfo> = settings
.get_array("tentacles")
.unwrap()
.into_iter()
.map(|v| TentacleClient::parse_tentacle(v).unwrap())
.collect();
assert_eq!(
vec![
TentacleInfo {
name: String::from("localhost"),
host: String::from("localhost"),
port: 18080,
protocol: String::from("http")
},
TentacleInfo {
name: String::from("tentacle_2"),
host: String::from("localhost"),
port: 18081,
protocol: String::from("http")
}
],
tentacles
);
}
#[test]
fn test_read_default_config() {
let settings = cfg::read_config::<String>(&None).unwrap();
assert_eq!(8081, settings.get_int("http.bind.port").unwrap());
assert_eq!("127.0.0.1", settings.get_str("http.bind.ip").unwrap());
let tentacles: Vec<String> = settings
.get_array("tentacles")
.unwrap()
.into_iter()
.map(|v| v.into_str().unwrap())
.collect();
assert!(tentacles.is_empty());
}
}
| true |
f54d1bce14efc53d08f321dad3a8a5c4708bd7b4
|
Rust
|
japaric/embedded2020
|
/host/cmsis-dap/src/hid.rs
|
UTF-8
| 2,847 | 3.296875 | 3 |
[
"MIT",
"Apache-2.0"
] |
permissive
|
//! USB-HID operations
use std::time::Instant;
use log::trace;
pub(crate) const REPORT_ID: u8 = 0x00;
impl crate::Dap {
/// Pushes the data into the HID buffer
pub(crate) fn hid_push(&mut self, data: impl AsLeBytes) {
data.as_le_bytes(|bytes| {
let n = bytes.len();
let cursor = usize::from(self.cursor);
self.buffer[cursor..cursor + n].copy_from_slice(bytes);
self.cursor += n as u16;
});
}
/// Rewrites a byte in the HID buffer
pub(crate) fn hid_rewrite(&mut self, i: u16, val: u8) {
assert!(
i < self.cursor,
"attempt to modify unused part of the HID buffer"
);
self.buffer[usize::from(i)] = val;
}
/// Writes the contents of the HID buffer to the HID device
pub(crate) fn hid_flush(&mut self) -> Result<(), anyhow::Error> {
debug_assert_eq!(self.buffer[0], REPORT_ID, "first byte must be `REPORT_ID`");
let bytes = &self.buffer[..self.cursor.into()];
let start = Instant::now();
self.device.write(bytes)?;
let end = Instant::now();
trace!("HID <- <{} bytes> in {:?}", bytes.len(), end - start);
self.cursor = 1;
Ok(())
}
/// Reads `len` bytes from the HID device
///
/// # Panics
///
/// This function panics if
///
/// - `hid_push` has been used but the HID buffer has not been drained
/// - `len` exceeds the packet size supported by the target
pub(crate) fn hid_read(&mut self, len: u16) -> Result<&[u8], anyhow::Error> {
assert_eq!(self.cursor, 1, "HID buffer must be flushed before a read");
assert!(
len <= self.packet_size,
"requested HID exceeds the target's packet size"
);
let buf = &mut self.buffer[1..];
let start = Instant::now();
let n = self.device.read(&mut buf[..usize::from(len)])?;
assert_eq!(n, usize::from(len), "read less bytes than requested");
let bytes = &buf[..n];
let end = Instant::now();
trace!("HID -> <{} bytes> in {:?}", bytes.len(), end - start);
Ok(bytes)
}
}
pub(crate) trait AsLeBytes {
fn as_le_bytes(&self, f: impl FnOnce(&[u8]));
}
impl<T> AsLeBytes for &'_ T
where
T: AsLeBytes + ?Sized,
{
fn as_le_bytes(&self, f: impl FnOnce(&[u8])) {
T::as_le_bytes(self, f)
}
}
impl AsLeBytes for [u8] {
fn as_le_bytes(&self, f: impl FnOnce(&[u8])) {
f(self)
}
}
impl AsLeBytes for u8 {
fn as_le_bytes(&self, f: impl FnOnce(&[u8])) {
f(&[*self])
}
}
impl AsLeBytes for u16 {
fn as_le_bytes(&self, f: impl FnOnce(&[u8])) {
f(&self.to_le_bytes())
}
}
impl AsLeBytes for u32 {
fn as_le_bytes(&self, f: impl FnOnce(&[u8])) {
f(&self.to_le_bytes())
}
}
| true |
65268825db551df453dc3c3db9d3ef8d8585be6b
|
Rust
|
steveklabnik/rust-git-fs
|
/src/root.rs
|
UTF-8
| 2,184 | 2.625 | 3 |
[
"Apache-2.0",
"MIT"
] |
permissive
|
// Copyright (C) 2014 Josh Stone
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use git2;
use libc;
use libc::consts::os::posix88;
use std::io;
use inode;
/// The root of the filesystem, currently just revealing HEAD and refs/
pub struct Root<'a> {
head: Option<git2::Reference<'a>>,
refs: inode::Id,
}
impl<'a> Root<'a> {
pub fn new(repo: &git2::Repository, refs: inode::Id) -> Box<inode::Inode> {
box Root {
head: repo.head().ok(),
refs: refs,
}
}
}
impl<'a> inode::Inode for Root<'a> {
fn lookup(&mut self, _repo: &git2::Repository, name: &PosixPath
) -> Result<inode::Id, libc::c_int> {
if name.as_vec() == b"HEAD" {
self.head.as_ref()
.and_then(|head| head.target())
.map(|oid| inode::Oid(oid))
}
else if name.as_vec() == b"refs" {
Some(self.refs)
}
else { None }.ok_or(posix88::ENOENT)
}
fn getattr(&mut self, _repo: &git2::Repository, attr: inode::FileAttr
) -> Result<inode::FileAttr, libc::c_int> {
let size = 1; // just HEAD
Ok(inode::FileAttr {
size: size,
blocks: inode::st_blocks(size),
kind: io::TypeDirectory,
perm: io::USER_DIR,
..attr
})
}
fn readdir(&mut self, _repo: &git2::Repository, offset: u64,
add: |inode::Id, io::FileType, &PosixPath| -> bool
) -> Result<(), libc::c_int> {
if offset == 0 {
add(self.refs, io::TypeUnknown, &PosixPath::new("refs"));
}
if offset <= 1 {
match self.head.as_ref().and_then(|head| head.target()) {
Some(oid) => {
add(inode::Oid(oid), io::TypeUnknown, &PosixPath::new("HEAD"));
},
None => (),
}
}
Ok(())
}
}
| true |
8500a787bfcea551762f96ef76959087b8733d6e
|
Rust
|
crawlis/keeper
|
/src/nats.rs
|
UTF-8
| 527 | 2.578125 | 3 |
[
"Apache-2.0"
] |
permissive
|
pub struct NatsSubscriber {
conn: nats::Connection,
sub: nats::Subscription,
}
impl NatsSubscriber {
pub fn new(uri: &str, subject: &str) -> std::io::Result<NatsSubscriber> {
let conn = nats::connect(uri)?;
let sub = format!("{}.*", subject);
let sub = conn.queue_subscribe(&sub, "keeper")?;
Ok(NatsSubscriber { conn, sub })
}
pub fn get_next_message(&self) -> Option<nats::Message> {
self.sub.next()
}
pub fn close(self) {
self.conn.close()
}
}
| true |
11b9fb78d53d092dcbb778b8dc53268a55b7728e
|
Rust
|
zzeroo/programmieren-in-rust-notes
|
/aufgaben/sheet06/sol3/swagger.rs
|
UTF-8
| 573 | 3.3125 | 3 |
[] |
no_license
|
use std::fmt;
use std::env;
struct Swagger<T>(pub T);
impl<T: fmt::Display> fmt::Display for Swagger<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "yolo {} swag", self.0)
}
}
trait SwaggerExt: Sized {
fn with_swag(self) -> Swagger<Self>;
}
impl<T> SwaggerExt for T {
fn with_swag(self) -> Swagger<Self> {
Swagger(self)
}
}
fn main() {
for arg in env::args().skip(1) {
let swag = Swagger(arg);
println!("{}", swag);
}
println!("{}", 3.with_swag()); // prints: "yolo 3 swag"
}
| true |
30c51b2048d99a295e2e5ab4ad0afb501a764d5d
|
Rust
|
likr/atcoder
|
/typical90/src/bin/009.rs
|
UTF-8
| 1,524 | 2.765625 | 3 |
[] |
no_license
|
use ordered_float::OrderedFloat;
use proconio::input;
#[allow(unused_imports)]
use proconio::marker::*;
#[allow(unused_imports)]
use std::cmp::*;
#[allow(unused_imports)]
use std::collections::*;
#[allow(unused_imports)]
use std::f64::consts::*;
#[allow(unused)]
const INF: usize = std::usize::MAX / 4;
#[allow(unused)]
const M: usize = 1000000007;
#[allow(unused_macros)]
macro_rules! debug {
($($a:expr),* $(,)*) => {
#[cfg(debug_assertions)]
eprintln!(concat!($("| ", stringify!($a), "={:?} "),*, "|"), $(&$a),*);
};
}
fn main() {
input! {
n: usize,
xy: [(f64, f64); n],
}
let mut result = 0.;
let mut angles = vec![];
for i in 0..n {
let (xi, yi) = xy[i];
angles.clear();
for j in 0..n {
if i != j {
let (xj, yj) = xy[j];
let t = (yj - yi).atan2(xj - xi);
if t >= 0. {
angles.push(t);
angles.push(t + 2. * PI);
} else {
angles.push(t + 2. * PI);
angles.push(t + 4. * PI);
}
}
}
angles.sort_by_key(|&v| OrderedFloat(v));
let mut k = 0;
for j in 0..n - 1 {
while angles[k + 1] - angles[j] <= PI {
k += 1;
}
let t = angles[k] - angles[j];
if t > result {
result = t;
}
}
}
println!("{}", result.to_degrees());
}
| true |
58f06125b8a970c38b2efdb540b213b0c9945183
|
Rust
|
winksaville/fuchsia
|
/third_party/rust_crates/vendor/tokio-executor/src/typed.rs
|
UTF-8
| 5,321 | 3.765625 | 4 |
[
"MIT",
"BSD-3-Clause"
] |
permissive
|
use SpawnError;
/// A value that spawns futures of a specific type.
///
/// The trait is generic over `T`: the type of future that can be spawened. This
/// is useful for implementing an executor that is only able to spawn a specific
/// type of future.
///
/// The [`spawn`] function is used to submit the future to the executor. Once
/// submitted, the executor takes ownership of the future and becomes
/// responsible for driving the future to completion.
///
/// This trait is useful as a bound for applications and libraries in order to
/// be generic over futures that are `Send` vs. `!Send`.
///
/// # Examples
///
/// Consider a function that provides an API for draining a `Stream` in the
/// background. To do this, a task must be spawned to perform the draining. As
/// such, the function takes a stream and an executor on which the background
/// task is spawned.
///
/// ```rust
/// #[macro_use]
/// extern crate futures;
/// extern crate tokio;
///
/// use futures::{Future, Stream, Poll};
/// use tokio::executor::TypedExecutor;
/// use tokio::sync::oneshot;
///
/// pub fn drain<T, E>(stream: T, executor: &mut E)
/// -> impl Future<Item = (), Error = ()>
/// where
/// T: Stream,
/// E: TypedExecutor<Drain<T>>
/// {
/// let (tx, rx) = oneshot::channel();
///
/// executor.spawn(Drain {
/// stream,
/// tx: Some(tx),
/// }).unwrap();
///
/// rx.map_err(|_| ())
/// }
///
/// // The background task
/// pub struct Drain<T: Stream> {
/// stream: T,
/// tx: Option<oneshot::Sender<()>>,
/// }
///
/// impl<T: Stream> Future for Drain<T> {
/// type Item = ();
/// type Error = ();
///
/// fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
/// loop {
/// let item = try_ready!(
/// self.stream.poll()
/// .map_err(|_| ())
/// );
///
/// if item.is_none() { break; }
/// }
///
/// self.tx.take().unwrap().send(()).map_err(|_| ());
/// Ok(().into())
/// }
/// }
/// # pub fn main() {}
/// ```
///
/// By doing this, the `drain` fn can accept a stream that is `!Send` as long as
/// the supplied executor is able to spawn `!Send` types.
pub trait TypedExecutor<T> {
/// Spawns a future to run on this executor.
///
/// `future` is passed to the executor, which will begin running it. The
/// executor takes ownership of the future and becomes responsible for
/// driving the future to completion.
///
/// # Panics
///
/// Implementations are encouraged to avoid panics. However, panics are
/// permitted and the caller should check the implementation specific
/// documentation for more details on possible panics.
///
/// # Examples
///
/// ```rust
/// # extern crate futures;
/// # extern crate tokio_executor;
/// # use tokio_executor::TypedExecutor;
/// # use futures::{Future, Poll};
/// fn example<T>(my_executor: &mut T)
/// where
/// T: TypedExecutor<MyFuture>,
/// {
/// my_executor.spawn(MyFuture).unwrap();
/// }
///
/// struct MyFuture;
///
/// impl Future for MyFuture {
/// type Item = ();
/// type Error = ();
///
/// fn poll(&mut self) -> Poll<(), ()> {
/// println!("running on the executor");
/// Ok(().into())
/// }
/// }
/// # fn main() {}
/// ```
fn spawn(&mut self, future: T) -> Result<(), SpawnError>;
/// Provides a best effort **hint** to whether or not `spawn` will succeed.
///
/// This function may return both false positives **and** false negatives.
/// If `status` returns `Ok`, then a call to `spawn` will *probably*
/// succeed, but may fail. If `status` returns `Err`, a call to `spawn` will
/// *probably* fail, but may succeed.
///
/// This allows a caller to avoid creating the task if the call to `spawn`
/// has a high likelihood of failing.
///
/// # Panics
///
/// This function must not panic. Implementers must ensure that panics do
/// not happen.
///
/// # Examples
///
/// ```rust
/// # extern crate futures;
/// # extern crate tokio_executor;
/// # use tokio_executor::TypedExecutor;
/// # use futures::{Future, Poll};
/// fn example<T>(my_executor: &mut T)
/// where
/// T: TypedExecutor<MyFuture>,
/// {
/// if my_executor.status().is_ok() {
/// my_executor.spawn(MyFuture).unwrap();
/// } else {
/// println!("the executor is not in a good state");
/// }
/// }
///
/// struct MyFuture;
///
/// impl Future for MyFuture {
/// type Item = ();
/// type Error = ();
///
/// fn poll(&mut self) -> Poll<(), ()> {
/// println!("running on the executor");
/// Ok(().into())
/// }
/// }
/// # fn main() {}
/// ```
fn status(&self) -> Result<(), SpawnError> {
Ok(())
}
}
impl<E, T> TypedExecutor<T> for Box<E>
where
E: TypedExecutor<T>,
{
fn spawn(&mut self, future: T) -> Result<(), SpawnError> {
(**self).spawn(future)
}
fn status(&self) -> Result<(), SpawnError> {
(**self).status()
}
}
| true |
bf9603e89fac84f5c958f407b1388773b38dfd92
|
Rust
|
SimonCarlson/exercism
|
/rust/clock/src/lib.rs
|
UTF-8
| 2,987 | 3.65625 | 4 |
[] |
no_license
|
use std::cmp;
use std::fmt;
pub struct Clock {
hours: i32,
minutes: i32,
}
impl Clock {
pub fn new(hours: i32, minutes: i32) -> Self {
let mut deducted_hours = 0;
let mut wrapped_hours;
let mut wrapped_minutes;
let mut extra_hours = 0;
if minutes < 0 {
wrapped_minutes = minutes % 60;
wrapped_minutes = 60 - wrapped_minutes.abs();
deducted_hours = (minutes / 60).abs() + 1;
} else {
wrapped_minutes = minutes % 60;
extra_hours = minutes / 60;
}
if hours < 0 {
wrapped_hours = hours % 24;
wrapped_hours = 24 - wrapped_hours.abs();
} else {
wrapped_hours = hours % 24
}
wrapped_hours = wrapped_hours + extra_hours - deducted_hours.abs();
if wrapped_hours < 0 {
wrapped_hours = 24 - (wrapped_hours % 24).abs();
}
wrapped_hours = wrapped_hours % 24;
Clock {
hours: wrapped_hours,
minutes: wrapped_minutes,
}
}
pub fn add_minutes(mut self, minutes: i32) -> Self {
let mut deduct_hours = 0;
self.minutes += minutes;
if self.minutes < 0 {
self.minutes = self.minutes % 60;
self.minutes = 60 - self.minutes.abs();
deduct_hours += 1;
if minutes.abs() / 60 > 24 {
deduct_hours -= 1;
}
if minutes.abs() / 60 > 0 {
deduct_hours += minutes.abs() / 60;
}
println!("minutes: {}, deduct hours: {}", minutes, deduct_hours);
self.hours -= deduct_hours;
self.hours = self.hours % 24;
if self.hours < 0 {
self.hours = 24 - self.hours.abs();
}
return self;
}
let roll_hours = self.minutes / 60;
let extra_minutes = self.minutes % 60;
self.hours += roll_hours;
self.hours = self.hours % 24;
self.minutes = extra_minutes;
self
}
pub fn to_string(self) -> String {
let mut string = String::new();
let mut hour_string = self.hours.to_string();
let mut minutes_string = self.minutes.to_string();
if self.hours < 10 {
hour_string.insert_str(0, "0")
}
string.push_str(&hour_string);
string.push_str(":");
if self.minutes < 10 {
minutes_string.insert_str(0, "0")
}
string.push_str(&minutes_string);
string
}
}
impl fmt::Debug for Clock {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}:{}", self.hours, self.minutes)
}
}
impl cmp::PartialEq for Clock {
fn eq(&self, clock: &Clock) -> bool {
if self.minutes == clock.minutes && self.hours == clock.hours {
return true
} else {
return false
}
}
}
| true |
fd6a366c514325a8155945fcc0c9d2949fda9cae
|
Rust
|
rchaser53/rust-monkey-ir
|
/src/parser/expressions.rs
|
UTF-8
| 6,307 | 3.484375 | 3 |
[] |
no_license
|
use std::fmt;
use parser::infix::*;
use parser::prefix::*;
use parser::statements::*;
#[derive(PartialEq, Clone, Debug)]
pub struct Identifier(pub String);
#[derive(PartialEq, Clone, Debug)]
pub enum Expression {
Identifier(Identifier, Location),
IntegerLiteral(u64, Location),
StringLiteral(String, Location),
Boolean(bool, Location),
Array(LLVMExpressionType, Vec<Expression>),
ArrayElement(Identifier, Box<Expression>, Location),
Prefix(Prefix, Box<Expression>, Location),
Infix(Infix, Box<Expression>, Box<Expression>, Location),
If {
conditions: Vec<Expression>,
bodies: Vec<BlockStatement>,
location: Location,
},
Function {
parameters: Vec<Identifier>,
parameter_types: Vec<LLVMExpressionType>,
body: BlockStatement,
return_type: LLVMExpressionType,
location: Location,
},
Call(Call),
}
#[derive(PartialEq, Clone, Debug)]
pub struct Call {
pub function: Box<Expression>,
pub arguments: Vec<Expression>,
pub location: Location,
}
#[derive(PartialEq, Clone, Debug)]
pub struct Location {
pub row: usize,
}
impl Location {
pub fn new(row: usize) -> Self {
Location { row: row }
}
}
#[derive(PartialEq, Clone, Debug)]
pub enum LLVMExpressionType {
Integer,
String(u32),
Boolean,
Null,
Array(Box<LLVMExpressionType>, u32),
Function,
Call,
}
impl fmt::Display for LLVMExpressionType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
LLVMExpressionType::Integer => write!(f, "{}", "int"),
LLVMExpressionType::String(_) => write!(f, "{}", "string"),
LLVMExpressionType::Boolean => write!(f, "{}", "boolean"),
LLVMExpressionType::Null => write!(f, "{}", "null"),
LLVMExpressionType::Array(_, _) => write!(f, "{}", "array"),
LLVMExpressionType::Function => write!(f, "{}", "function"),
LLVMExpressionType::Call => write!(f, "{}", "call"),
}
}
}
impl Expression {
pub fn string(&self) -> String {
match self {
Expression::Identifier(ident, _location) => ident.0.to_string(),
Expression::IntegerLiteral(int, _location) => int.to_string(),
Expression::StringLiteral(literal, _location) => {
format!(r#""{}""#, literal.to_string())
}
Expression::Boolean(boolean, _location) => boolean.to_string(),
Expression::Array(_, elements) => {
let elements_string = elements
.iter()
.fold(Vec::new(), |mut stack, element| {
stack.push(element.string());
stack
})
.join(", ");
format!("[{}]", elements_string)
}
Expression::ArrayElement(ident, index_expression, _) => {
format!("{}[{}]", ident.0.to_string(), index_expression.string())
}
Expression::Prefix(prefix, expr, _location) => format!("({}{})", prefix, expr.string()),
Expression::Infix(infix, left, right, _location) => {
format!("({} {} {})", left.string(), infix, right.string())
}
Expression::If {
conditions,
bodies,
location: _,
} => {
let mut condition_strings =
conditions.iter().map(|s| s.string()).collect::<Vec<_>>();
let body_strings = bodies.iter().fold(Vec::new(), |mut stack, body| {
let body_string = body
.iter()
.map(|s| s.string())
.collect::<Vec<_>>()
.join("\n");
stack.push(body_string);
stack
});
let mut ret_string = String::new();
for (index, condition_string) in condition_strings.iter().enumerate() {
if index == 0 {
ret_string.push_str(&format!(
"if({}) {{ {} }} ",
condition_string, body_strings[index]
));
} else {
ret_string.push_str(&format!(
"elseif({}) {{ {} }}",
condition_string, body_strings[index]
));
}
}
format!("{}", ret_string)
}
Expression::Function {
parameters,
body,
parameter_types,
return_type,
location: _,
} => {
let mut param_string = String::new();
for (index, Identifier(ref string)) in parameters.iter().enumerate() {
if index == 0 {
param_string.push_str(&format!("{}: {}", string, parameter_types[index]));
} else {
param_string.push_str(&format!(", {}: {}", string, parameter_types[index]));
}
}
let mut ret_string = String::new();
for (index, statement) in body.iter().enumerate() {
if index == 0 {
ret_string.push_str(&format!("{}", statement.string()));
} else {
ret_string.push_str(&format!(" {}", statement.string()));
}
}
format!("fn({}): {} {{ {} }}", param_string, return_type, ret_string)
}
Expression::Call(call) => {
let mut ret_string = String::new();
for (index, parameter) in call.arguments.iter().enumerate() {
if index == 0 {
ret_string.push_str(&format!("{}", ¶meter.string()));
} else {
ret_string.push_str(&format!(", {}", ¶meter.string()));
}
}
format!("{}({})", call.function.string(), ret_string)
}
}
}
}
| true |
f07646603bd1661d9a614ebedada36aee7476143
|
Rust
|
darwins-challenge/genoculars
|
/src/dirlist.rs
|
UTF-8
| 2,502 | 2.96875 | 3 |
[
"MIT"
] |
permissive
|
use glob;
use std::path::{Path,PathBuf};
use std::error::Error;
use std::fs::File;
use std::ffi::OsStr;
use std::io::Read;
use iron::middleware::Handler;
use iron::prelude::*;
use iron::status;
use rustc_serialize::json;
pub struct DirectoryLister {
pub directory: String
}
fn name_from_path(pb: PathBuf) -> Option<String> {
pb.file_name()
.and_then(|x| x.to_str())
.map(|y| y.to_owned())
}
pub fn list_dir(pattern: String) -> Result<Vec<String>, Box<Error>> {
Ok(try!(glob::glob(&pattern))
.filter_map(Result::ok)
.filter_map(name_from_path)
.filter(|n| !n.starts_with("."))
.collect())
}
pub type FileType = &'static str;
fn file_type<S: AsRef<OsStr>>(name: S) -> FileType {
if Path::new(&name).is_dir() {
"dir"
} else if name.as_ref().to_str().map(|s| s.ends_with(".json")).unwrap_or(false) {
"trace"
} else {
"file"
}
}
pub fn list_json_files(dir: &str) -> Result<Vec<(FileType, String)>, Box<Error>> {
list_dir(dir.to_owned() + "/*").map(|xs| xs
.into_iter()
.map(|name| (file_type(dir.to_owned() + "/" + &name), name))
.filter(|t| t.0 == "dir" || t.0 == "trace")
.collect())
}
impl DirectoryLister {
fn list(&self, path_parts: &[String]) -> Result<String, Box<Error>> {
let full_path = self.directory.clone() + "/" + &path_parts.join("/");
let files = try!(list_json_files(&full_path));
Ok(try!(json::encode(&files)))
}
fn load(&self, path_parts: &[String]) -> Result<String, Box<Error>> {
let full_path = self.directory.clone() + "/" + &path_parts.join("/");
let mut f = try!(File::open(full_path));
let mut ret = String::new();
try!(f.read_to_string(&mut ret));
Ok(ret)
}
}
impl Handler for DirectoryLister {
fn handle(&self, req: &mut Request) -> IronResult<Response> {
match req.url.path[0].as_ref() {
"list" => Ok(make_response(self.list(&req.url.path[1..]))),
"get" => Ok(make_response(self.load(&req.url.path[1..]))),
_ => Ok(Response::with((status::BadRequest, "Unrecognized command")))
}
}
}
fn make_response(r: Result<String, Box<Error>>) -> Response {
match r {
Ok(s) => Response::with((status::Ok, s)),
Err(e) => {
println!("{:?}", e);
Response::with((status::InternalServerError, e.description()))
}
}
}
| true |
21a14470cf2bf8d8e4eb579fdf6017dd4e42a179
|
Rust
|
Mutestock/mini-project-loner-edition
|
/grpc/src/client.rs
|
UTF-8
| 1,915 | 2.53125 | 3 |
[] |
no_license
|
// For manual testing in this project
#[macro_use]
extern crate lazy_static;
mod entities;
mod utils;
use entities::student::student_client::StudentClient;
use entities::student::{CreateStudentRequest, ReadStudentRequest};
use tonic::transport::Channel;
use utils::config::{is_production_mode, CONFIG};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut client = match is_production_mode() {
true => {
StudentClient::connect(format!("http://[::1]:{}", CONFIG.production.server.port))
.await?
}
false => {
StudentClient::connect(format!("http://[::1]:{}", 10030))
.await?
}
};
let request = tonic::Request::new(CreateStudentRequest {
first_name: "firstnamefromtonic".to_owned(),
last_name: "lastnamefromtonic".to_owned(),
phone_number: "phonenumberfromtonic".to_owned(),
email: "emailfromtonic".to_owned(),
});
let request02 = tonic::Request::new(ReadStudentRequest{
id: 2,
});
let response = client
.create_student(request)
.await
.expect("create_student failed in client");
println!("RESPONSE={:?}", response);
let response02 = client.read_student(request02).await.expect("Something was wrong with read student");
println!("resp= {:?}",response02);
Ok(())
}
async fn create_student(mut client: StudentClient<Channel>) {
let request = tonic::Request::new(CreateStudentRequest {
first_name: "first_name_from_tonic".to_owned(),
last_name: "last_name_from_tonic".to_owned(),
phone_number: "phone_number_from_tonic".to_owned(),
email: "email_from_tonic".to_owned(),
});
let response = client
.create_student(request)
.await
.expect("create_student failed in client");
println!("RESPONSE={:?}", response);
}
| true |
d10659c6c8dc32f029d3cd1d8495ffc1d6b64138
|
Rust
|
dorayakikun/alfred_jira_workflow
|
/src/item.rs
|
UTF-8
| 908 | 3.34375 | 3 |
[
"MIT"
] |
permissive
|
#[derive(Debug, Serialize, Deserialize)]
pub struct Item {
pub title: String,
pub arg: String,
}
#[derive(Debug)]
pub struct ItemBuilder<TitleType, ArgType> {
pub title: TitleType,
pub arg: ArgType,
}
impl ItemBuilder<(), ()> {
pub fn new() -> Self {
ItemBuilder { title: (), arg: () }
}
}
impl ItemBuilder<String, String> {
pub fn build(self) -> Item {
Item {
title: self.title,
arg: self.arg,
}
}
}
impl<TitleType, ArgType> ItemBuilder<TitleType, ArgType> {
pub fn title<S: Into<String>>(self, title: S) -> ItemBuilder<String, ArgType> {
ItemBuilder {
title: title.into(),
arg: self.arg,
}
}
pub fn arg<S: Into<String>>(self, arg: S) -> ItemBuilder<TitleType, String> {
ItemBuilder {
title: self.title,
arg: arg.into(),
}
}
}
| true |
eeeb93cedcde08d53dded9cc785f0b09bf582927
|
Rust
|
raymondnumbergenerator/spire_rogue
|
/src/components/creature.rs
|
UTF-8
| 4,042 | 2.515625 | 3 |
[] |
no_license
|
use specs::prelude::*;
use specs::saveload::{Marker, ConvertSaveload};
use specs::error::NoError;
use specs_derive::{Component, ConvertSaveload};
use serde::{Serialize, Deserialize};
use super::super::{monsters};
use rltk::RandomNumberGenerator;
#[derive(Component, Debug, Serialize, Deserialize, Clone)]
pub struct Creature {}
#[derive(Component, Debug, ConvertSaveload, Clone)]
pub struct Player {
pub max_energy: i32,
pub energy: i32,
}
#[derive(Component, Debug, Serialize, Deserialize, Clone)]
pub struct Monster {}
#[derive(Component, Debug, ConvertSaveload, Clone)]
pub struct CombatStats {
pub max_hp: i32,
pub hp: i32,
pub block: i32,
pub base_strength: i32,
pub strength: i32,
pub base_dexterity: i32,
pub dexterity: i32,
}
#[derive(Component, Debug, Serialize, Deserialize, Clone)]
pub struct BlocksTile {}
#[derive(Component, ConvertSaveload, Clone)]
pub struct Viewshed {
pub visible_tiles : Vec<rltk::Point>,
pub range: i32,
pub dirty: bool,
}
#[derive(Component, Debug, ConvertSaveload, Clone)]
pub struct SufferDamage {
pub amount: Vec<i32>
}
impl SufferDamage {
pub fn new_damage(store: &mut WriteStorage<SufferDamage>, victim: Entity, amount: i32) {
if let Some(suffering) = store.get_mut(victim) {
suffering.amount.push(amount);
} else {
let dmg = SufferDamage{ amount: vec![amount] };
store.insert(victim, dmg).expect("Unable to insert damage");
}
}
}
#[derive(Component, Debug, ConvertSaveload)]
pub struct PerformAction {
pub action: Entity,
pub target: Option<rltk::Point>,
}
#[derive(Component, Debug, ConvertSaveload)]
pub struct PickupItem {
pub collected_by: Entity,
pub item: Entity,
}
#[derive(Component, Debug, Serialize, Deserialize, Clone)]
pub struct Attack{}
#[derive(Component, ConvertSaveload, Clone)]
pub struct Intent {
pub intent: Entity,
pub used: bool,
}
#[derive(Component, ConvertSaveload, Clone)]
pub struct AttackCycle {
pub attacks: Vec<monsters::Attacks>,
pub cycle: usize,
weights: Option<Vec<i32>>,
total_weight: i32,
}
impl AttackCycle {
pub fn new_sequential() -> AttackCycle {
AttackCycle {
attacks: Vec::new(),
cycle: 0,
weights: None,
total_weight: 0,
}
}
pub fn new_weighted() -> AttackCycle {
AttackCycle {
attacks: Vec::new(),
cycle: 0,
weights: Some(Vec::new()),
total_weight: 0,
}
}
pub fn add_weighted(mut self, attack: monsters::Attacks, weight: i32) -> AttackCycle {
if let None = self.weights { panic!("Attempted to add weighted attacks to sequential attack cycle.") }
self.attacks.push(attack);
let mut new_weights = self.weights.unwrap();
new_weights.push(weight);
self.total_weight += weight;
self.weights = Some(new_weights);
self
}
pub fn add_sequential(mut self, attack: monsters::Attacks) -> AttackCycle {
if let Some(_) = self.weights { panic!("Attempted to add sequential attacks to weighted attack cycle.") }
self.attacks.push(attack);
self
}
pub fn next_attack(&mut self, rng: &mut RandomNumberGenerator) {
match &self.weights {
Some(w) => {
let mut roll = rng.roll_dice(1, self.total_weight) - 1;
let mut next_cycle = 0;
while roll >= 0 {
if roll < w[next_cycle] {
self.cycle = next_cycle;
return;
}
roll -= w[next_cycle];
next_cycle += 1;
}
}
None => {
self.cycle = (self.cycle + 1) % self.attacks.len();
}
}
}
}
| true |
eda2a3c2073c1b7cbdda4c51795fc68e6c380814
|
Rust
|
Schwenger/RustTak
|
/src/player/command_line_human/cli_parser.rs
|
UTF-8
| 5,646 | 3.46875 | 3 |
[
"MIT"
] |
permissive
|
use crate::actions::Action;
use crate::board::Position;
use crate::board::piece::PieceKind;
use crate::board::Direction;
use regex::Regex;
pub(crate) struct CLIParser {}
pub(crate) type Result<T> = std::result::Result<T, CLIParserError<T>>;
impl CLIParser {
pub(crate) fn action(s: &str) -> Result<Action> {
let s = s.trim().to_lowercase();
let tokens: Vec<&str> = s.split_whitespace().collect();
if tokens.is_empty() {
Err(CLIParserError::new("You didn't say anything...", None))
} else {
match tokens[0] {
"place" | "set" => Self::place(&tokens[1..]),
"move" | "slide" => Self::slide(&tokens[1..]),
_ => Err(CLIParserError::new("Unknown command word. Try `place`, `slide`, or `move`.", None)),
}
}
}
fn slide(tokens: &[&str]) -> Result<Action> {
Self::exact_slide(tokens)
}
fn exact_slide(tokens: &[&str]) -> Result<Action> {
// lazy_static! {
// static ref regex: Regex = Regex::new(
// r#"(stone | flat | standing\s*stone | wall | cap\s*stone)\s*(to | at | on)?\s*\(\s*(\d+)\s*,\s*(\d+)\s*\)"#
// ).unwrap();
// }
let regex = Regex::new(
r#"(?:from)?\s*\(\s*(\d+)\s*,\s*(\d+)\s*\)\s*((north|east|west|south)\s*(?:taking|moving)*\s*((\d*\s*,?\s*)*))?"#
).unwrap();
// Capture groups:
// 0: full match
// 1: row
// 2: col
// 3: direction
// 4: optional; full match for optional drops
// 5: optional; list of carries
regex
.captures_iter(&tokens.join(""))
.map(|cap| {
let row = cap[1].parse::<usize>().unwrap();
let col = cap[2].parse::<usize>().unwrap();
let pos = Position::new(row, col);
let dir = Self::direction(&cap[3]);
if cap.len() > 4 {
let carries = Self::number_list(&cap[5]);
Action::Slide(pos, dir, Some(carries))
} else {
Action::Slide(pos, dir, None)
}
})
.next()
.map(Ok)
.unwrap_or_else(|| Err(CLIParserError::new("I don't understand...", None)))
}
fn number_list(s: &str) -> Vec<usize> {
let regex = Regex::new(r#"\d*"#).unwrap();
regex.find_iter(s).map(|m| m.as_str().parse::<usize>().unwrap()).collect()
}
fn direction(s: &str) -> Direction {
match s {
"north" => Direction::North,
"south" => Direction::South,
"east" => Direction::East,
"west" => Direction::West,
_ => unreachable!(),
}
}
fn place(tokens: &[&str]) -> Result<Action> {
if let Some(action) = Self::exact_place(tokens) {
Ok(action)
} else {
unimplemented!()
}
}
fn exact_place(tokens: &[&str]) -> Option<Action> {
lazy_static! {
static ref regex: Regex = Regex::new(
r#"(stone | flat | standing\s*stone | wall | cap\s*stone)\s*(to | at | on)?\s*\(\s*(\d+)\s*,\s*(\d+)\s*\)"#
).unwrap();
}
regex
.captures_iter(&tokens.join(""))
.map(|cap| {
// cap[0] is the full match.
let kind = Self::piece_kind(&cap[1]);
// cap[2] is the optional connective.
let row = cap[3].parse::<usize>().unwrap();
let col = cap[4].parse::<usize>().unwrap();
let pos = Position::new(row, col);
Action::Place(pos, kind)
})
.next()
}
fn piece_kind(s: &str) -> PieceKind {
match s {
"wall" => PieceKind::StandingStone,
"stone" | "flat" => PieceKind::Stone,
s if s.starts_with("cap") => PieceKind::CapStone,
s if s.starts_with("standing") => PieceKind::StandingStone,
_ => unreachable!(),
}
}
pub(crate) fn position(s: &str) -> Result<Position> {
if let Some(pos) = Self::exact_position(s) {
return Ok(pos);
}
let s = s.trim().to_lowercase();
let numbers = Self::extract_numbers(&s);
if numbers.len() == 2 {
let best_guess = Some(Position::new(numbers[0], numbers[1]));
Err(CLIParserError::new("I'm not sure I understood that correctly.", best_guess))
} else {
Err(CLIParserError::new("I have no idea what you're talking about.", None))
}
}
fn exact_position(s: &str) -> Option<Position> {
lazy_static! {
static ref regex: Regex = Regex::new(r#"\(\s*\d+\s*,\s*\d+\s*\)"#).expect("Meh");
}
regex
.captures_iter(s)
.map(|cap| Position::new(cap[1].parse::<usize>().unwrap(), cap[2].parse::<usize>().unwrap()))
.next()
}
fn extract_numbers(s: &str) -> Vec<usize> {
lazy_static! {
static ref regex: Regex = Regex::new(r#"\d*"#).unwrap();
}
regex
.find_iter(s)
.map(|m| m.as_str().parse::<usize>().expect("This transformation should always work."))
.collect()
}
}
pub(crate) struct CLIParserError<T> {
pub(crate) help: String,
pub(crate) best_guess: Option<T>,
}
impl<T> CLIParserError<T> {
fn new(help: &str, best_guess: Option<T>) -> CLIParserError<T> {
CLIParserError { help: String::from(help), best_guess }
}
}
| true |
5cd483cbf2897ef66b5aaed9042c7dff842086c2
|
Rust
|
RobertWHurst/Delta
|
/src/worker.rs
|
UTF-8
| 2,144 | 2.8125 | 3 |
[] |
no_license
|
use std::thread::{spawn, JoinHandle};
use std::sync::{Arc, Mutex, RwLock};
use scene::Scene;
use controller::ControllerApi;
pub struct Worker {
end_worker_thread: Arc<Mutex<bool>>,
join_handle: Option<JoinHandle<()>>,
}
impl Worker {
pub fn new(worker_index: usize, scene_mx: Arc<RwLock<Option<Scene>>>) -> Self {
let end_worker_thread = Arc::new(Mutex::new(false));
Self {
end_worker_thread: end_worker_thread.clone(),
join_handle: Some(spawn(move || {
WorkerController::new(worker_index, end_worker_thread, scene_mx).start()
})),
}
}
pub fn end(&mut self) {
*self.end_worker_thread.lock().unwrap() = true;
self.join_handle.take().unwrap().join().unwrap();
}
}
struct WorkerController {
worker_index: usize,
end_worker_thread: Arc<Mutex<bool>>,
scene_mx: Arc<RwLock<Option<Scene>>>,
}
impl WorkerController {
fn new(
worker_index: usize,
end_worker_thread: Arc<Mutex<bool>>,
scene_mx: Arc<RwLock<Option<Scene>>>,
) -> Self {
Self {
worker_index,
end_worker_thread,
scene_mx,
}
}
fn should_exit(&self) -> bool {
*self.end_worker_thread.lock().unwrap()
}
fn start(&self) {
loop {
if self.should_exit() {
break;
}
let scene_grd = self.scene_mx.read().unwrap();
let scene = match *scene_grd {
Some(ref s) => s,
None => continue,
};
let elements_mx = scene.elements();
let elements = elements_mx.read().unwrap();
for element_mx in elements.values() {
let mut element = match element_mx.try_lock() {
Ok(e) => e,
Err(_) => continue,
};
let id = element.id();
element.tick(ControllerApi::new(
self.worker_index,
id,
elements_mx.clone(),
));
}
}
}
}
| true |
74b2036e5e0ea2294d74e5bc47ae55831d24d406
|
Rust
|
Dstate/clex
|
/src/token.rs
|
UTF-8
| 2,036 | 3.515625 | 4 |
[] |
no_license
|
use std::fmt;
use std::ops::Range;
pub use ConstKind::*;
pub use ErrorKind::*;
pub use TokenKind::*;
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum TokenKind {
/* tokens */
Keyword,
Ident,
Const(ConstKind),
StrLit,
Punct,
/* compiler internal tokens */
Comment,
Whitespace,
Error(ErrorKind),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum ConstKind {
Float,
Integer,
Char,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum ErrorKind {
UnclosedBlockComment,
UnterminatedString,
UnterminatedChar,
UnknownPunctuator,
UnexpectedCharacter,
InvalidIntegerSuffix,
InvalidFloatingSuffix,
NoHexadecimalDigits,
#[allow(unused)]
Unknown,
}
/// Instead of storing the actual token content, `Token` stores
/// the text range of it and maintains a reference to the source str.
///
/// By doing so, we can avoid additional heap allocations.
///
/// Note that we have two ranges: one is byte-based, corresponding to
/// the original UTF-8 byte sequence; the other is char-based, mainly
/// for human-readable text ranges.
#[derive(Clone, PartialEq, Eq)]
pub struct Token<'a> {
pub kind: TokenKind,
pub byte_range: Range<usize>,
pub char_range: Range<usize>,
pub src: &'a str,
}
impl fmt::Debug for Token<'_> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "[{:?}@{:?}]", self.kind, self.byte_range)
}
}
impl fmt::Display for Token<'_> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"[{:?}: {:?}]",
self.kind,
&self.src[self.byte_range.clone()],
)
}
}
impl<'a> Token<'a> {
pub fn new(
kind: TokenKind,
byte_range: Range<usize>,
char_range: Range<usize>,
src: &'a str,
) -> Self {
Token {
kind,
byte_range,
char_range,
src,
}
}
}
| true |
764dcd52232fa9b8497289ee00c2801a469d7964
|
Rust
|
JakubGrobelny/University
|
/2019-2020/zima/Rust/lista1/square_area_to_circle.rs
|
UTF-8
| 700 | 3.765625 | 4 |
[] |
no_license
|
fn square_area_to_circle(area: f64) -> f64 {
let radius: f64 = area.sqrt() / 2.0;
radius * radius * std::f64::consts::PI
}
fn assert_close(a:f64, b:f64, epsilon:f64) {
assert!( (a-b).abs() < epsilon, format!("Expected: {}, got: {}",b,a) );
}
#[test]
fn test0() {
assert_close(square_area_to_circle(0.0), 0.0, 1e-8)
}
#[test]
fn test1() {
assert_close(square_area_to_circle(4.0), 3.141592654, 1e-4)
}
#[test]
fn test2() {
assert_close(square_area_to_circle(9.0), 7.068583470577, 1e-4)
}
#[test]
fn test3() {
assert_close(square_area_to_circle(12.5), 9.817477042468, 1e-4)
}
#[test]
fn test4() {
assert_close(square_area_to_circle(1.25), 0.98174770424, 1e-8)
}
| true |
625f6f1ec4f083fbef19cc7e30846cb0a1e46bd6
|
Rust
|
ManishVerma16/Rust_Learning
|
/rust_basics/src/impl_keyword.rs
|
UTF-8
| 710 | 4.1875 | 4 |
[] |
no_license
|
// impl keyword is used to add method to a structs to make it more useful
struct Rectangle {
width: u32,
length: u32
}
impl Rectangle {
fn print_description(&self){ //adding description method
println!("Rectangle: {} x {}", self.width, self.length);
}
fn area(&self){ // adding area method
println!("Area: {}", self.width*self.length);
}
fn is_square(&self) -> bool{ // adding method to check whether rectangle is square or not
self.width == self.length
}
}
fn main(){
let mut rect = Rectangle{ width: 10, length: 5};
rect.print_description();
rect.area();
rect.width = 5;
println!("Rectange is square: {}", rect.is_square());
}
| true |
68836e22086cd06dc4f9fba24e1645955a008169
|
Rust
|
nabor/azurita
|
/src/azurita/ast/ast.rs
|
UTF-8
| 2,606 | 3.21875 | 3 |
[
"MIT"
] |
permissive
|
use azurita::Token;
use azurita::Expresion;
use azurita::expresions::{AzInteger, AzOperator};
pub fn generate(tokens: Vec<Token>) -> Result<(), &'static str>{
let debug = false;
let mut stack = Vec::<Expresion>::new();
for token in tokens {
match token {
Token::Number(number) => {
if debug { println!("Number: {}", number) }
match stack.pop() {
Some(mut e) => {
match e {
Expresion::Operation{ operator: _, left: ref l, right: ref mut r } => {
match **l {
Expresion::Number(_) => {
*r = Box::new(Expresion::Number(AzInteger::new(number)));
},
_ => return Err("Invalid Syntax"),
}
},
_ => return Err("Invalid Syntax"),
}
stack.push(e);
},
None => { stack.push(Expresion::Number(AzInteger::new(number))) },
}
},
Token::Separator(separator) => {
if debug { println!("Separator: {}", separator) }
},
Token::Symbol(symbol) => {
if debug { println!("Symbol: {}", symbol) }
match stack.pop() {
Some(e) => {
match e {
Expresion::Number(_) => {
stack.push(Expresion::Operation{
operator: AzOperator::new(symbol).expect("Invalid operator"),
left: Box::new(e),
right: Box::new(Expresion::Void)
});
},
_ => return Err("Invalid Syntax"),
}
},
None => return Err("Invalid Syntax"),
}
},
Token::Text(text) => {
if debug { println!("Text: \"{}\"", text) }
},
Token::Word(word) => {
if debug { println!("Word: {}", word) }
},
}
}
match stack.pop() {
Some(e) => {
let r = try!(e.eval());
println!("{}", r);
return Ok(());
},
None => return Err("Invalix Syntax")
}
}
| true |
3f1527f9ed9f3448222ca64134a240916c63ab71
|
Rust
|
oysterpack/oysterpack-smart-near
|
/near/oysterpack-smart-staking-pool/src/domain/unstaked_balances.rs
|
UTF-8
| 12,134 | 2.71875 | 3 |
[
"MIT"
] |
permissive
|
use crate::components::staking_pool::State;
use oysterpack_smart_near::asserts::ERR_INSUFFICIENT_FUNDS;
use oysterpack_smart_near::domain::{EpochHeight, YoctoNear};
use oysterpack_smart_near::near_sdk::{
borsh::{self, BorshDeserialize, BorshSerialize},
env,
};
use std::cmp::Ordering;
use std::collections::BTreeMap;
/// unstaked NEAR is locked for 4 epochs before being able to be withdrawn
/// https://github.com/near/nearcore/blob/037954e087fd5c8a65598ede502495530c73f835/chain/epoch_manager/src/lib.rs#L815
const EPOCHS_LOCKED: usize = 4;
#[derive(BorshDeserialize, BorshSerialize, Debug, Clone, Copy, PartialEq, Default)]
pub struct UnstakedBalances {
available: YoctoNear,
locked: [(EpochHeight, YoctoNear); EPOCHS_LOCKED],
}
impl UnstakedBalances {
pub fn total(&self) -> YoctoNear {
self.available + self.locked_balance()
}
pub fn available(&self) -> YoctoNear {
self.available
}
pub fn locked_balance(&self) -> YoctoNear {
self.locked
.iter()
.fold(YoctoNear::ZERO, |total, (_, amount)| total + *amount)
}
pub fn locked(&self) -> Option<BTreeMap<EpochHeight, YoctoNear>> {
let result: BTreeMap<EpochHeight, YoctoNear> =
self.locked
.iter()
.fold(BTreeMap::new(), |mut result, (epoch, amount)| {
if *amount > YoctoNear::ZERO {
result.insert(*epoch, *amount);
}
result
});
if result.is_empty() {
None
} else {
Some(result)
}
}
pub(crate) fn unlock(&mut self) {
let current_epoch: EpochHeight = env::epoch_height().into();
for i in 0..EPOCHS_LOCKED {
let (epoch, balance) = self.locked[i];
if balance > YoctoNear::ZERO {
if epoch <= current_epoch {
self.available += balance;
self.locked[i] = Default::default();
}
}
}
}
/// If there are locked balances then try to use liquidity to unlock the funds for withdrawal.
///
/// returns the amount of liquidity that was applied
pub(crate) fn apply_liquidity(&mut self) -> YoctoNear {
self.unlock();
let locked_balance = self.locked_balance();
if locked_balance == YoctoNear::ZERO {
return YoctoNear::ZERO;
}
let liquidity = State::liquidity();
if liquidity == YoctoNear::ZERO {
return YoctoNear::ZERO;
}
if liquidity >= locked_balance {
self.available = self.total();
for i in 0..EPOCHS_LOCKED {
self.locked[i] = Default::default();
}
return locked_balance;
}
self.available += liquidity;
self.debit_from_locked(liquidity);
liquidity
}
/// adds the unstaked balance and locks it up for 4 epochs
pub(crate) fn credit_unstaked(&mut self, amount: YoctoNear) {
self.unlock();
let available_on: EpochHeight = (env::epoch_height() + EPOCHS_LOCKED as u64).into();
for i in 0..EPOCHS_LOCKED {
let (epoch, balance) = self.locked[i];
if balance > YoctoNear::ZERO {
if epoch == available_on {
self.locked[i] = (epoch, balance + amount);
return;
}
}
}
for i in 0..EPOCHS_LOCKED {
if self.locked[i].1 == YoctoNear::ZERO {
self.locked[i] = (available_on, amount);
return;
}
}
unreachable!()
}
fn sort_locked(&mut self) {
self.locked.sort_by(|left, right| {
if left.1 == YoctoNear::ZERO && right.1 == YoctoNear::ZERO {
return Ordering::Equal;
}
if left.1 > YoctoNear::ZERO && right.1 == YoctoNear::ZERO {
return Ordering::Less;
}
if left.1 == YoctoNear::ZERO && right.1 > YoctoNear::ZERO {
return Ordering::Greater;
}
left.0.cmp(&right.0)
});
}
/// tries to debit the specified amount from the available balance.
///
/// ## NOTES
/// - locked balances are checked if they have become available
///
/// ## Panics
/// if there are insufficient funds
pub(crate) fn debit_available_balance(&mut self, amount: YoctoNear) {
self.unlock();
ERR_INSUFFICIENT_FUNDS.assert(|| self.available >= amount);
self.available -= amount;
}
pub(crate) fn debit_for_restaking(&mut self, amount: YoctoNear) {
let total = self.total();
ERR_INSUFFICIENT_FUNDS.assert(|| total >= amount);
if total == self.available {
self.available -= amount;
return;
}
let remainder = self.debit_from_locked(amount);
self.available -= remainder;
}
fn debit_from_locked(&mut self, mut amount: YoctoNear) -> YoctoNear {
self.sort_locked();
// take from the most recent unstaked balances
for i in (0..EPOCHS_LOCKED).rev() {
let (available_on, unstaked) = self.locked[i];
if unstaked > YoctoNear::ZERO {
if unstaked <= amount {
amount -= unstaked;
self.locked[i] = Default::default();
} else {
self.locked[i] = (available_on, unstaked - amount);
return YoctoNear::ZERO;
}
if amount == YoctoNear::ZERO {
return YoctoNear::ZERO;
}
}
}
return amount;
}
}
#[cfg(test)]
mod tests {
use super::*;
use oysterpack_smart_near::domain::YoctoNear;
use oysterpack_smart_near::YOCTO;
use oysterpack_smart_near_test::*;
#[test]
fn unlock() {
let mut ctx = new_context("bob");
ctx.epoch_height = 100;
testing_env!(ctx.clone());
let mut unstaked_balances = UnstakedBalances::default();
unstaked_balances.credit_unstaked(YOCTO.into());
unstaked_balances.credit_unstaked(YOCTO.into());
assert_eq!(unstaked_balances.available, YoctoNear::ZERO);
let expected_available_on: EpochHeight = (ctx.epoch_height + EPOCHS_LOCKED as u64).into();
assert_eq!(
*unstaked_balances
.locked()
.unwrap()
.get(&expected_available_on)
.unwrap(),
YoctoNear(2 * YOCTO)
);
assert_eq!(*unstaked_balances.total(), 2 * YOCTO);
ctx.epoch_height = 101;
testing_env!(ctx.clone());
unstaked_balances.credit_unstaked(YOCTO.into());
assert_eq!(unstaked_balances.available, YoctoNear::ZERO);
assert_eq!(
*unstaked_balances
.locked()
.unwrap()
.get(&expected_available_on)
.unwrap(),
YoctoNear(2 * YOCTO)
);
let expected_available_on: EpochHeight = (ctx.epoch_height + EPOCHS_LOCKED as u64).into();
assert_eq!(
*unstaked_balances
.locked()
.unwrap()
.get(&expected_available_on)
.unwrap(),
YoctoNear(YOCTO)
);
assert_eq!(*unstaked_balances.total(), 3 * YOCTO);
ctx.epoch_height = 104;
testing_env!(ctx.clone());
unstaked_balances.unlock();
assert_eq!(*unstaked_balances.total(), 3 * YOCTO);
assert_eq!(*unstaked_balances.available(), 2 * YOCTO);
ctx.epoch_height = 105;
testing_env!(ctx.clone());
unstaked_balances.unlock();
assert_eq!(*unstaked_balances.total(), 3 * YOCTO);
assert_eq!(*unstaked_balances.available(), 3 * YOCTO);
println!("{:?}", unstaked_balances);
}
#[test]
fn debit_for_restaking() {
let mut ctx = new_context("bob");
ctx.epoch_height = 100;
testing_env!(ctx.clone());
let mut unstaked_balances = UnstakedBalances::default();
unstaked_balances.credit_unstaked(YOCTO.into());
ctx.epoch_height = 101;
testing_env!(ctx.clone());
unstaked_balances.credit_unstaked(YOCTO.into());
ctx.epoch_height = 103;
testing_env!(ctx.clone());
unstaked_balances.credit_unstaked(YOCTO.into());
ctx.epoch_height = 104;
testing_env!(ctx.clone());
unstaked_balances.credit_unstaked(YOCTO.into());
ctx.epoch_height = 106;
testing_env!(ctx.clone());
unstaked_balances.credit_unstaked(YOCTO.into());
unstaked_balances.sort_locked();
assert_eq!(
unstaked_balances,
UnstakedBalances {
available: (2 * YOCTO).into(),
locked: [
(107.into(), YOCTO.into()),
(108.into(), YOCTO.into()),
(110.into(), YOCTO.into()),
Default::default()
]
}
);
unstaked_balances.debit_for_restaking(1000.into());
assert_eq!(
unstaked_balances,
UnstakedBalances {
available: (2 * YOCTO).into(),
locked: [
(107.into(), YOCTO.into()),
(108.into(), YOCTO.into()),
(110.into(), (YOCTO - 1000).into()),
Default::default()
]
}
);
unstaked_balances.debit_for_restaking(YOCTO.into());
assert_eq!(
unstaked_balances,
UnstakedBalances {
available: (2 * YOCTO).into(),
locked: [
(107.into(), YOCTO.into()),
(108.into(), (YOCTO - 1000).into()),
Default::default(),
Default::default()
]
}
);
unstaked_balances.debit_for_restaking((2 * YOCTO).into());
assert_eq!(
unstaked_balances,
UnstakedBalances {
available: ((2 * YOCTO) - 1000).into(),
locked: Default::default()
}
);
unstaked_balances.debit_for_restaking(YOCTO.into());
assert_eq!(
unstaked_balances,
UnstakedBalances {
available: (YOCTO - 1000).into(),
locked: Default::default()
}
);
}
#[test]
#[should_panic(expected = "[ERR] [INSUFFICIENT_FUNDS]")]
fn debit_for_restaking_with_insufficient_funds() {
let mut ctx = new_context("bob");
ctx.epoch_height = 100;
testing_env!(ctx.clone());
let mut unstaked_balances = UnstakedBalances::default();
unstaked_balances.credit_unstaked(YOCTO.into());
unstaked_balances.debit_for_restaking((2 * YOCTO).into());
}
#[test]
fn debit_available_balance() {
let mut ctx = new_context("bob");
ctx.epoch_height = 100;
testing_env!(ctx.clone());
let mut unstaked_balances = UnstakedBalances::default();
unstaked_balances.credit_unstaked(YOCTO.into());
assert_eq!(unstaked_balances.total(), YOCTO.into());
ctx.epoch_height = 104;
testing_env!(ctx.clone());
unstaked_balances.debit_available_balance(YOCTO.into());
assert_eq!(unstaked_balances.total(), YoctoNear::ZERO);
}
#[test]
#[should_panic(expected = "[ERR] [INSUFFICIENT_FUNDS]")]
fn debit_available_balance_insufficient_funds() {
let mut ctx = new_context("bob");
ctx.epoch_height = 100;
testing_env!(ctx.clone());
let mut unstaked_balances = UnstakedBalances::default();
unstaked_balances.credit_unstaked(YOCTO.into());
assert_eq!(unstaked_balances.total(), YOCTO.into());
unstaked_balances.debit_available_balance(YOCTO.into());
}
}
| true |
5cfc17d9951375e96094376d1d732ce97183b793
|
Rust
|
uwe-app/bracket
|
/tests/lines.rs
|
UTF-8
| 2,934 | 3.09375 | 3 |
[] |
no_license
|
use bracket::{
parser::ast::{CallTarget, Lines, Node},
Registry, Result,
};
const NAME: &str = "lines.rs";
#[test]
fn lines_text() -> Result<()> {
let registry = Registry::new();
let value = r"This is some text
that spans multiple lines
so we can check the line range.";
let template = registry.parse(NAME, value)?;
let node = template.node().into_iter().next().unwrap();
if let Node::Text(text) = node {
assert_eq!(0..3, text.lines().clone());
}
Ok(())
}
#[test]
fn lines_comment() -> Result<()> {
let registry = Registry::new();
let value = r"{{!
This is a comment that spans multiple lines.
}}";
let template = registry.parse(NAME, value)?;
let node = template.node().into_iter().next().unwrap();
if let Node::Comment(text) = node {
assert_eq!(0..3, text.lines().clone());
}
Ok(())
}
#[test]
fn lines_raw_comment() -> Result<()> {
let registry = Registry::new();
let value = r"{{!--
This is a raw comment that spans multiple lines.
--}}";
let template = registry.parse(NAME, value)?;
let node = template.node().into_iter().next().unwrap();
if let Node::RawComment(text) = node {
assert_eq!(0..3, text.lines().clone());
}
Ok(())
}
#[test]
fn lines_call_single() -> Result<()> {
let registry = Registry::new();
let value = r"{{
foo.bar.qux
}}";
let template = registry.parse(NAME, value)?;
let node = template.node().into_iter().next().unwrap();
if let Node::Statement(call) = node {
assert_eq!(0..3, call.lines().clone());
let target = call.target();
assert_eq!(1..2, target.lines().clone());
if let CallTarget::Path(ref path) = target {
assert_eq!(1..2, path.lines().clone());
}
}
Ok(())
}
#[test]
fn lines_call_multi() -> Result<()> {
let registry = Registry::new();
let value = r#"{{
foo
"message"
true
}}"#;
let template = registry.parse(NAME, value)?;
let node = template.node().into_iter().next().unwrap();
if let Node::Statement(call) = node {
assert_eq!(0..5, call.lines().clone());
}
Ok(())
}
#[test]
fn lines_raw_block() -> Result<()> {
let registry = Registry::new();
let value = r"{{{{raw}}}}
This is some text in a raw block.
{{{{/raw}}}}";
let template = registry.parse(NAME, value)?;
let node = template.node().into_iter().next().unwrap();
if let Node::Block(block) = node {
assert_eq!(0..3, block.lines().clone());
}
Ok(())
}
#[test]
fn lines_block() -> Result<()> {
let registry = Registry::new();
let value = r"{{#block}}
This is some text in a block statement.
If can have other {{foo}} statements.
{{/block}}";
let template = registry.parse(NAME, value)?;
let node = template.node().into_iter().next().unwrap();
if let Node::Block(block) = node {
assert_eq!(0..5, block.lines().clone());
}
Ok(())
}
| true |
a4892213502fc5a24fbe6fbfeea78c23d2377725
|
Rust
|
Thaddeus19/rust-programming
|
/snippets/src/fmt_arguments.rs
|
UTF-8
| 519 | 3.171875 | 3 |
[] |
no_license
|
#![allow(unused_macros)]
#[allow(dead_code)]
fn format_message(entry: std::fmt::Arguments) -> String {
use std::fmt::Write;
let mut message = String::new();
message.write_fmt(entry);
message
}
macro_rules! log {
($format:tt, $($arg:expr), *) => {
format_message(format_args!($format, $($arg), *));
};
}
#[test]
fn fmt_arguments_test() {
let msg = log!("The message is {:?}", "secret message");
assert_eq!(msg, "The message is \"secret message\"");
println!("{}", msg);
}
| true |
fcfdf3792431041a6014fd2f53381d81c662a2b7
|
Rust
|
everynote/dropbox-api-content-hasher
|
/rust/src/run_tests.rs
|
UTF-8
| 2,410 | 2.953125 | 3 |
[
"Apache-2.0"
] |
permissive
|
//! A command-line tool that runs the `DropboxContentHasher` tests.
extern crate digest;
extern crate rand;
extern crate dropbox_content_hasher;
extern crate sha2;
use digest::Digest;
use std::io::Write as io_Write;
use rand::Rng;
use dropbox_content_hasher::{DropboxContentHasher, BLOCK_SIZE};
fn main() {
let mut args = std::env::args();
args.next().unwrap(); // Remove name of binary.
if args.len() != 0 {
writeln!(&mut std::io::stderr(), "No arguments expected; got {}.", args.len()).unwrap();
std::process::exit(1);
}
let b = BLOCK_SIZE;
let tests: &[&[usize]] = &[
&[0],
&[100],
&[100, 10],
&[b-1],
&[b],
&[b+1],
&[b-2, 1],
&[b-2, 2],
&[b-2, 3],
&[b-2, b+1],
&[b-2, b+2],
&[b-2, b+3],
&[5, 5, 5],
&[5, 5, 5, b],
&[5, 5, 5, 3*b],
&[5, 5, 5, 3*b, 5, 5, 5, 3*b],
];
let longest_length = tests.iter().fold(0, |m, x| std::cmp::max(m, x.iter().sum()));
println!("generating random data");
let mut data: Box<[u8]> = vec![0; longest_length].into_boxed_slice();
rand::ChaChaRng::new_unseeded().fill_bytes(data.as_mut());
for &test in tests {
let passed = check(data.as_ref(), test);
if !passed {
std::process::exit(2);
}
}
println!("all passed");
}
fn reference_hasher(data: &[u8]) -> String {
let mut overall_hasher = sha2::Sha256::new();
for chunk in data.chunks(BLOCK_SIZE) {
let mut block_hasher = sha2::Sha256::new();
block_hasher.input(chunk);
overall_hasher.input(block_hasher.result().as_slice());
}
return format!("{:x}", overall_hasher.result());
}
fn check(data: &[u8], chunk_sizes: &[usize]) -> bool {
println!("checking {:?}", chunk_sizes);
let mut hasher = DropboxContentHasher::new();
let mut input = data;
let mut total_length = 0;
for chunk_size in chunk_sizes.iter().cloned() {
let (chunk, rest) = input.split_at(chunk_size);
input = rest;
hasher.input(chunk);
total_length += chunk_size;
}
let result = format!("{:x}", hasher.result());
let reference = reference_hasher(data.split_at(total_length).0);
let passed = result == reference;
if !passed {
println!("- FAILED: {:?}, {:?}", reference, result)
}
passed
}
| true |
12e56e66c697b5e459dad562a3b0fb81b25ed870
|
Rust
|
hzkazmi/Batch6_34_Quarter1
|
/may_17_2020_imran/chap5/src/main.rs
|
UTF-8
| 1,522 | 3.390625 | 3 |
[] |
no_license
|
#[derive(Debug)]
struct Food {
resturant: String, //field
food_item:String,
size:u8,
price:u16,
availablilty:bool
} //blue print
fn main() {
let pizza = Food {
resturant: String::from("Pizza Hut"),
food_item:String::from("Chicken Fajita"),
availablilty:true,
price:1500,
size:16,
};
let karahi = Food {
resturant: String::from("BBQ tonight"),
food_item:String::from("Chicken Ginger"),
size:1,
price:1500,
availablilty:true
};
println!("Pizza price {}",pizza.price);
println!("Pizza {:#?}",pizza);
println!("Karahi {:#?}",karahi);
pizza.billing("Habib Ullah".to_string());
Food::eid_fitr(1_000);
// printing(pizza);
// let mytea=pc();
// println!("My Tea {:#?}",mytea);
// println!("geting from pc {:#?}",pc());
}
fn printing(data:Food){
println!("We are in printing function");
println!("Pizza price {}",data.price);
println!("Pizza {:#?}",data);
}
impl Food {
fn billing(&self,rider:String){
println!("We are in billing Method rider id {}",rider);
println!("Food price {}",self.price);
println!("Food {:#?}",self);
}
fn eid_fitr(eidi:u16){
for mybalance in 0..eidi {
println!("My eidi Balance {}",mybalance);
}
}
}
fn pc()->Food {
let chai = Food {
resturant: String::from("Pathan"),
food_item:String::from("Mix Tea"),
size:2,
price:100,
availablilty:true
};
chai
}
| true |
5a86ffc73f0eaddfeefe204f665d8da53db65c23
|
Rust
|
Schenk75/Learn-Rust
|
/exercism/etl/src/lib.rs
|
UTF-8
| 364 | 2.84375 | 3 |
[] |
no_license
|
use std::collections::BTreeMap;
pub fn transform(h: &BTreeMap<i32, Vec<char>>) -> BTreeMap<char, i32> {
let mut map: BTreeMap<char, i32> = BTreeMap::new();
for (point, char_list) in h.iter() {
for ch in char_list {
let count = map.entry(ch.to_ascii_lowercase()).or_insert(0);
*count += point;
}
}
map
}
| true |
bd9d205c23048cc078189118ef8aed32009c39b5
|
Rust
|
mnts26/aws-sdk-rust
|
/sdk/ssmcontacts/src/client.rs
|
UTF-8
| 88,911 | 2.53125 | 3 |
[
"Apache-2.0"
] |
permissive
|
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT.
#[derive(Debug)]
pub(crate) struct Handle<
C = smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = smithy_client::retry::Standard,
> {
client: smithy_client::Client<C, M, R>,
conf: crate::Config,
}
/// An ergonomic service client for `SSMContacts`.
///
/// This client allows ergonomic access to a `SSMContacts`-shaped service.
/// Each method corresponds to an endpoint defined in the service's Smithy model,
/// and the request and response shapes are auto-generated from that same model.
///
/// # Using a Client
///
/// Once you have a client set up, you can access the service's endpoints
/// by calling the appropriate method on [`Client`]. Each such method
/// returns a request builder for that endpoint, with methods for setting
/// the various fields of the request. Once your request is complete, use
/// the `send` method to send the request. `send` returns a future, which
/// you then have to `.await` to get the service's response.
///
/// [builder pattern]: https://rust-lang.github.io/api-guidelines/type-safety.html#c-builder
/// [SigV4-signed requests]: https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html
#[derive(std::fmt::Debug)]
pub struct Client<
C = smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = smithy_client::retry::Standard,
> {
handle: std::sync::Arc<Handle<C, M, R>>,
}
impl<C, M, R> std::clone::Clone for Client<C, M, R> {
fn clone(&self) -> Self {
Self {
handle: self.handle.clone(),
}
}
}
#[doc(inline)]
pub use smithy_client::Builder;
impl<C, M, R> From<smithy_client::Client<C, M, R>> for Client<C, M, R> {
fn from(client: smithy_client::Client<C, M, R>) -> Self {
Self::with_config(client, crate::Config::builder().build())
}
}
impl<C, M, R> Client<C, M, R> {
pub fn with_config(client: smithy_client::Client<C, M, R>, conf: crate::Config) -> Self {
Self {
handle: std::sync::Arc::new(Handle { client, conf }),
}
}
pub fn conf(&self) -> &crate::Config {
&self.handle.conf
}
}
impl<C, M, R> Client<C, M, R>
where
C: smithy_client::bounds::SmithyConnector,
M: smithy_client::bounds::SmithyMiddleware<C>,
R: smithy_client::retry::NewRequestPolicy,
{
pub fn accept_page(&self) -> fluent_builders::AcceptPage<C, M, R> {
fluent_builders::AcceptPage::new(self.handle.clone())
}
pub fn activate_contact_channel(&self) -> fluent_builders::ActivateContactChannel<C, M, R> {
fluent_builders::ActivateContactChannel::new(self.handle.clone())
}
pub fn create_contact(&self) -> fluent_builders::CreateContact<C, M, R> {
fluent_builders::CreateContact::new(self.handle.clone())
}
pub fn create_contact_channel(&self) -> fluent_builders::CreateContactChannel<C, M, R> {
fluent_builders::CreateContactChannel::new(self.handle.clone())
}
pub fn deactivate_contact_channel(&self) -> fluent_builders::DeactivateContactChannel<C, M, R> {
fluent_builders::DeactivateContactChannel::new(self.handle.clone())
}
pub fn delete_contact(&self) -> fluent_builders::DeleteContact<C, M, R> {
fluent_builders::DeleteContact::new(self.handle.clone())
}
pub fn delete_contact_channel(&self) -> fluent_builders::DeleteContactChannel<C, M, R> {
fluent_builders::DeleteContactChannel::new(self.handle.clone())
}
pub fn describe_engagement(&self) -> fluent_builders::DescribeEngagement<C, M, R> {
fluent_builders::DescribeEngagement::new(self.handle.clone())
}
pub fn describe_page(&self) -> fluent_builders::DescribePage<C, M, R> {
fluent_builders::DescribePage::new(self.handle.clone())
}
pub fn get_contact(&self) -> fluent_builders::GetContact<C, M, R> {
fluent_builders::GetContact::new(self.handle.clone())
}
pub fn get_contact_channel(&self) -> fluent_builders::GetContactChannel<C, M, R> {
fluent_builders::GetContactChannel::new(self.handle.clone())
}
pub fn get_contact_policy(&self) -> fluent_builders::GetContactPolicy<C, M, R> {
fluent_builders::GetContactPolicy::new(self.handle.clone())
}
pub fn list_contact_channels(&self) -> fluent_builders::ListContactChannels<C, M, R> {
fluent_builders::ListContactChannels::new(self.handle.clone())
}
pub fn list_contacts(&self) -> fluent_builders::ListContacts<C, M, R> {
fluent_builders::ListContacts::new(self.handle.clone())
}
pub fn list_engagements(&self) -> fluent_builders::ListEngagements<C, M, R> {
fluent_builders::ListEngagements::new(self.handle.clone())
}
pub fn list_page_receipts(&self) -> fluent_builders::ListPageReceipts<C, M, R> {
fluent_builders::ListPageReceipts::new(self.handle.clone())
}
pub fn list_pages_by_contact(&self) -> fluent_builders::ListPagesByContact<C, M, R> {
fluent_builders::ListPagesByContact::new(self.handle.clone())
}
pub fn list_pages_by_engagement(&self) -> fluent_builders::ListPagesByEngagement<C, M, R> {
fluent_builders::ListPagesByEngagement::new(self.handle.clone())
}
pub fn list_tags_for_resource(&self) -> fluent_builders::ListTagsForResource<C, M, R> {
fluent_builders::ListTagsForResource::new(self.handle.clone())
}
pub fn put_contact_policy(&self) -> fluent_builders::PutContactPolicy<C, M, R> {
fluent_builders::PutContactPolicy::new(self.handle.clone())
}
pub fn send_activation_code(&self) -> fluent_builders::SendActivationCode<C, M, R> {
fluent_builders::SendActivationCode::new(self.handle.clone())
}
pub fn start_engagement(&self) -> fluent_builders::StartEngagement<C, M, R> {
fluent_builders::StartEngagement::new(self.handle.clone())
}
pub fn stop_engagement(&self) -> fluent_builders::StopEngagement<C, M, R> {
fluent_builders::StopEngagement::new(self.handle.clone())
}
pub fn tag_resource(&self) -> fluent_builders::TagResource<C, M, R> {
fluent_builders::TagResource::new(self.handle.clone())
}
pub fn untag_resource(&self) -> fluent_builders::UntagResource<C, M, R> {
fluent_builders::UntagResource::new(self.handle.clone())
}
pub fn update_contact(&self) -> fluent_builders::UpdateContact<C, M, R> {
fluent_builders::UpdateContact::new(self.handle.clone())
}
pub fn update_contact_channel(&self) -> fluent_builders::UpdateContactChannel<C, M, R> {
fluent_builders::UpdateContactChannel::new(self.handle.clone())
}
}
pub mod fluent_builders {
#[derive(std::fmt::Debug)]
pub struct AcceptPage<
C = smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::accept_page_input::Builder,
}
impl<C, M, R> AcceptPage<C, M, R>
where
C: smithy_client::bounds::SmithyConnector,
M: smithy_client::bounds::SmithyMiddleware<C>,
R: smithy_client::retry::NewRequestPolicy,
{
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> std::result::Result<
crate::output::AcceptPageOutput,
smithy_http::result::SdkError<crate::error::AcceptPageError>,
>
where
R::Policy: smithy_client::bounds::SmithyRetryPolicy<
crate::input::AcceptPageInputOperationOutputAlias,
crate::output::AcceptPageOutput,
crate::error::AcceptPageError,
crate::input::AcceptPageInputOperationRetryAlias,
>,
{
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The Amazon Resource Name (ARN) of the engagement to a contact channel.</p>
pub fn page_id(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.page_id(inp);
self
}
pub fn set_page_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_page_id(input);
self
}
/// <p>The ARN of the contact channel.</p>
pub fn contact_channel_id(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.contact_channel_id(inp);
self
}
pub fn set_contact_channel_id(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_contact_channel_id(input);
self
}
/// <p>The type indicates if the page was <code>DELIVERED</code> or <code>READ</code>.</p>
pub fn accept_type(mut self, inp: crate::model::AcceptType) -> Self {
self.inner = self.inner.accept_type(inp);
self
}
pub fn set_accept_type(
mut self,
input: std::option::Option<crate::model::AcceptType>,
) -> Self {
self.inner = self.inner.set_accept_type(input);
self
}
/// <p>Information provided by the user when the user acknowledges the page.</p>
pub fn note(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.note(inp);
self
}
pub fn set_note(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_note(input);
self
}
/// <p>The accept code is a 6-digit code used to acknowledge the page.</p>
pub fn accept_code(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.accept_code(inp);
self
}
pub fn set_accept_code(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_accept_code(input);
self
}
/// <p>An optional field that Incident Manager uses to <code>ENFORCE</code>
/// <code>AcceptCode</code> validation when acknowledging an page. Acknowledgement can occur by
/// replying to a page, or when entering the AcceptCode in the console. Enforcing AcceptCode
/// validation causes Incident Manager to verify that the code entered by the user matches the
/// code sent by Incident Manager with the page.</p>
/// <p>Incident Manager can also <code>IGNORE</code>
/// <code>AcceptCode</code> validation. Ignoring <code>AcceptCode</code> validation causes
/// Incident Manager to accept any value entered for the <code>AcceptCode</code>.</p>
pub fn accept_code_validation(mut self, inp: crate::model::AcceptCodeValidation) -> Self {
self.inner = self.inner.accept_code_validation(inp);
self
}
pub fn set_accept_code_validation(
mut self,
input: std::option::Option<crate::model::AcceptCodeValidation>,
) -> Self {
self.inner = self.inner.set_accept_code_validation(input);
self
}
}
#[derive(std::fmt::Debug)]
pub struct ActivateContactChannel<
C = smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::activate_contact_channel_input::Builder,
}
impl<C, M, R> ActivateContactChannel<C, M, R>
where
C: smithy_client::bounds::SmithyConnector,
M: smithy_client::bounds::SmithyMiddleware<C>,
R: smithy_client::retry::NewRequestPolicy,
{
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> std::result::Result<
crate::output::ActivateContactChannelOutput,
smithy_http::result::SdkError<crate::error::ActivateContactChannelError>,
>
where
R::Policy: smithy_client::bounds::SmithyRetryPolicy<
crate::input::ActivateContactChannelInputOperationOutputAlias,
crate::output::ActivateContactChannelOutput,
crate::error::ActivateContactChannelError,
crate::input::ActivateContactChannelInputOperationRetryAlias,
>,
{
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The Amazon Resource Name (ARN) of the contact channel.</p>
pub fn contact_channel_id(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.contact_channel_id(inp);
self
}
pub fn set_contact_channel_id(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_contact_channel_id(input);
self
}
/// <p>The code sent to the contact channel when it was created in the contact. </p>
pub fn activation_code(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.activation_code(inp);
self
}
pub fn set_activation_code(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_activation_code(input);
self
}
}
#[derive(std::fmt::Debug)]
pub struct CreateContact<
C = smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::create_contact_input::Builder,
}
impl<C, M, R> CreateContact<C, M, R>
where
C: smithy_client::bounds::SmithyConnector,
M: smithy_client::bounds::SmithyMiddleware<C>,
R: smithy_client::retry::NewRequestPolicy,
{
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> std::result::Result<
crate::output::CreateContactOutput,
smithy_http::result::SdkError<crate::error::CreateContactError>,
>
where
R::Policy: smithy_client::bounds::SmithyRetryPolicy<
crate::input::CreateContactInputOperationOutputAlias,
crate::output::CreateContactOutput,
crate::error::CreateContactError,
crate::input::CreateContactInputOperationRetryAlias,
>,
{
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The short name to quickly identify a contact or escalation plan. The contact alias must
/// be unique and identifiable. </p>
pub fn alias(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.alias(inp);
self
}
pub fn set_alias(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_alias(input);
self
}
/// <p>The full name of the contact or escalation plan. </p>
pub fn display_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.display_name(inp);
self
}
pub fn set_display_name(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_display_name(input);
self
}
/// <p>To create an escalation plan use <code>ESCALATION</code>. To create a contact use
/// <code>PERSONAL</code>.</p>
pub fn r#type(mut self, inp: crate::model::ContactType) -> Self {
self.inner = self.inner.r#type(inp);
self
}
pub fn set_type(mut self, input: std::option::Option<crate::model::ContactType>) -> Self {
self.inner = self.inner.set_type(input);
self
}
/// <p>A list of stages. A contact has an engagement plan with stages that contact specified
/// contact channels. An escalation plan uses stages that contact specified contacts. </p>
pub fn plan(mut self, inp: crate::model::Plan) -> Self {
self.inner = self.inner.plan(inp);
self
}
pub fn set_plan(mut self, input: std::option::Option<crate::model::Plan>) -> Self {
self.inner = self.inner.set_plan(input);
self
}
/// Appends an item to `Tags`.
///
/// To override the contents of this collection use [`set_tags`](Self::set_tags).
/// <p>Adds a tag to the target. You can only tag resources created in the first Region of your
/// replication set. </p>
pub fn tags(mut self, inp: impl Into<crate::model::Tag>) -> Self {
self.inner = self.inner.tags(inp);
self
}
pub fn set_tags(
mut self,
input: std::option::Option<std::vec::Vec<crate::model::Tag>>,
) -> Self {
self.inner = self.inner.set_tags(input);
self
}
/// <p>A token ensuring that the operation is called only once with the specified
/// details.</p>
pub fn idempotency_token(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.idempotency_token(inp);
self
}
pub fn set_idempotency_token(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_idempotency_token(input);
self
}
}
#[derive(std::fmt::Debug)]
pub struct CreateContactChannel<
C = smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::create_contact_channel_input::Builder,
}
impl<C, M, R> CreateContactChannel<C, M, R>
where
C: smithy_client::bounds::SmithyConnector,
M: smithy_client::bounds::SmithyMiddleware<C>,
R: smithy_client::retry::NewRequestPolicy,
{
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> std::result::Result<
crate::output::CreateContactChannelOutput,
smithy_http::result::SdkError<crate::error::CreateContactChannelError>,
>
where
R::Policy: smithy_client::bounds::SmithyRetryPolicy<
crate::input::CreateContactChannelInputOperationOutputAlias,
crate::output::CreateContactChannelOutput,
crate::error::CreateContactChannelError,
crate::input::CreateContactChannelInputOperationRetryAlias,
>,
{
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The Amazon Resource Name (ARN) of the contact you are adding the contact channel to.</p>
pub fn contact_id(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.contact_id(inp);
self
}
pub fn set_contact_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_contact_id(input);
self
}
/// <p>The name of the contact channel.</p>
pub fn name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.name(inp);
self
}
pub fn set_name(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_name(input);
self
}
/// <p>Incident Manager supports three types of contact channels:</p>
/// <ul>
/// <li>
/// <p>
/// <code>SMS</code>
/// </p>
/// </li>
/// <li>
/// <p>
/// <code>VOICE</code>
/// </p>
/// </li>
/// <li>
/// <p>
/// <code>EMAIL</code>
/// </p>
/// </li>
/// </ul>
pub fn r#type(mut self, inp: crate::model::ChannelType) -> Self {
self.inner = self.inner.r#type(inp);
self
}
pub fn set_type(mut self, input: std::option::Option<crate::model::ChannelType>) -> Self {
self.inner = self.inner.set_type(input);
self
}
/// <p>The details that Incident Manager uses when trying to engage the contact channel. The format
/// is dependent on the type of the contact channel. The following are the expected
/// formats:</p>
/// <ul>
/// <li>
/// <p>SMS - '+' followed by the country code and phone number</p>
/// </li>
/// <li>
/// <p>VOICE - '+' followed by the country code and phone number</p>
/// </li>
/// <li>
/// <p>EMAIL - any standard email format</p>
/// </li>
/// </ul>
pub fn delivery_address(mut self, inp: crate::model::ContactChannelAddress) -> Self {
self.inner = self.inner.delivery_address(inp);
self
}
pub fn set_delivery_address(
mut self,
input: std::option::Option<crate::model::ContactChannelAddress>,
) -> Self {
self.inner = self.inner.set_delivery_address(input);
self
}
/// <p>If you want to activate the channel at a later time, you can choose to defer activation.
/// Incident Manager can't engage your contact channel until it has been activated.</p>
pub fn defer_activation(mut self, inp: bool) -> Self {
self.inner = self.inner.defer_activation(inp);
self
}
pub fn set_defer_activation(mut self, input: std::option::Option<bool>) -> Self {
self.inner = self.inner.set_defer_activation(input);
self
}
/// <p>A token ensuring that the operation is called only once with the specified
/// details.</p>
pub fn idempotency_token(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.idempotency_token(inp);
self
}
pub fn set_idempotency_token(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_idempotency_token(input);
self
}
}
#[derive(std::fmt::Debug)]
pub struct DeactivateContactChannel<
C = smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::deactivate_contact_channel_input::Builder,
}
impl<C, M, R> DeactivateContactChannel<C, M, R>
where
C: smithy_client::bounds::SmithyConnector,
M: smithy_client::bounds::SmithyMiddleware<C>,
R: smithy_client::retry::NewRequestPolicy,
{
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> std::result::Result<
crate::output::DeactivateContactChannelOutput,
smithy_http::result::SdkError<crate::error::DeactivateContactChannelError>,
>
where
R::Policy: smithy_client::bounds::SmithyRetryPolicy<
crate::input::DeactivateContactChannelInputOperationOutputAlias,
crate::output::DeactivateContactChannelOutput,
crate::error::DeactivateContactChannelError,
crate::input::DeactivateContactChannelInputOperationRetryAlias,
>,
{
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The Amazon Resource Name (ARN) of the contact channel you're deactivating.</p>
pub fn contact_channel_id(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.contact_channel_id(inp);
self
}
pub fn set_contact_channel_id(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_contact_channel_id(input);
self
}
}
#[derive(std::fmt::Debug)]
pub struct DeleteContact<
C = smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::delete_contact_input::Builder,
}
impl<C, M, R> DeleteContact<C, M, R>
where
C: smithy_client::bounds::SmithyConnector,
M: smithy_client::bounds::SmithyMiddleware<C>,
R: smithy_client::retry::NewRequestPolicy,
{
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> std::result::Result<
crate::output::DeleteContactOutput,
smithy_http::result::SdkError<crate::error::DeleteContactError>,
>
where
R::Policy: smithy_client::bounds::SmithyRetryPolicy<
crate::input::DeleteContactInputOperationOutputAlias,
crate::output::DeleteContactOutput,
crate::error::DeleteContactError,
crate::input::DeleteContactInputOperationRetryAlias,
>,
{
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The Amazon Resource Name (ARN) of the contact that you're deleting.</p>
pub fn contact_id(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.contact_id(inp);
self
}
pub fn set_contact_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_contact_id(input);
self
}
}
#[derive(std::fmt::Debug)]
pub struct DeleteContactChannel<
C = smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::delete_contact_channel_input::Builder,
}
impl<C, M, R> DeleteContactChannel<C, M, R>
where
C: smithy_client::bounds::SmithyConnector,
M: smithy_client::bounds::SmithyMiddleware<C>,
R: smithy_client::retry::NewRequestPolicy,
{
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> std::result::Result<
crate::output::DeleteContactChannelOutput,
smithy_http::result::SdkError<crate::error::DeleteContactChannelError>,
>
where
R::Policy: smithy_client::bounds::SmithyRetryPolicy<
crate::input::DeleteContactChannelInputOperationOutputAlias,
crate::output::DeleteContactChannelOutput,
crate::error::DeleteContactChannelError,
crate::input::DeleteContactChannelInputOperationRetryAlias,
>,
{
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The Amazon Resource Name (ARN) of the contact channel.</p>
pub fn contact_channel_id(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.contact_channel_id(inp);
self
}
pub fn set_contact_channel_id(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_contact_channel_id(input);
self
}
}
#[derive(std::fmt::Debug)]
pub struct DescribeEngagement<
C = smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::describe_engagement_input::Builder,
}
impl<C, M, R> DescribeEngagement<C, M, R>
where
C: smithy_client::bounds::SmithyConnector,
M: smithy_client::bounds::SmithyMiddleware<C>,
R: smithy_client::retry::NewRequestPolicy,
{
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> std::result::Result<
crate::output::DescribeEngagementOutput,
smithy_http::result::SdkError<crate::error::DescribeEngagementError>,
>
where
R::Policy: smithy_client::bounds::SmithyRetryPolicy<
crate::input::DescribeEngagementInputOperationOutputAlias,
crate::output::DescribeEngagementOutput,
crate::error::DescribeEngagementError,
crate::input::DescribeEngagementInputOperationRetryAlias,
>,
{
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The Amazon Resource Name (ARN) of the engagement you want the details of.</p>
pub fn engagement_id(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.engagement_id(inp);
self
}
pub fn set_engagement_id(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_engagement_id(input);
self
}
}
#[derive(std::fmt::Debug)]
pub struct DescribePage<
C = smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::describe_page_input::Builder,
}
impl<C, M, R> DescribePage<C, M, R>
where
C: smithy_client::bounds::SmithyConnector,
M: smithy_client::bounds::SmithyMiddleware<C>,
R: smithy_client::retry::NewRequestPolicy,
{
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> std::result::Result<
crate::output::DescribePageOutput,
smithy_http::result::SdkError<crate::error::DescribePageError>,
>
where
R::Policy: smithy_client::bounds::SmithyRetryPolicy<
crate::input::DescribePageInputOperationOutputAlias,
crate::output::DescribePageOutput,
crate::error::DescribePageError,
crate::input::DescribePageInputOperationRetryAlias,
>,
{
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The ID of the engagement to a contact channel.</p>
pub fn page_id(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.page_id(inp);
self
}
pub fn set_page_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_page_id(input);
self
}
}
#[derive(std::fmt::Debug)]
pub struct GetContact<
C = smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::get_contact_input::Builder,
}
impl<C, M, R> GetContact<C, M, R>
where
C: smithy_client::bounds::SmithyConnector,
M: smithy_client::bounds::SmithyMiddleware<C>,
R: smithy_client::retry::NewRequestPolicy,
{
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> std::result::Result<
crate::output::GetContactOutput,
smithy_http::result::SdkError<crate::error::GetContactError>,
>
where
R::Policy: smithy_client::bounds::SmithyRetryPolicy<
crate::input::GetContactInputOperationOutputAlias,
crate::output::GetContactOutput,
crate::error::GetContactError,
crate::input::GetContactInputOperationRetryAlias,
>,
{
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The Amazon Resource Name (ARN) of the contact or escalation plan.</p>
pub fn contact_id(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.contact_id(inp);
self
}
pub fn set_contact_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_contact_id(input);
self
}
}
#[derive(std::fmt::Debug)]
pub struct GetContactChannel<
C = smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::get_contact_channel_input::Builder,
}
impl<C, M, R> GetContactChannel<C, M, R>
where
C: smithy_client::bounds::SmithyConnector,
M: smithy_client::bounds::SmithyMiddleware<C>,
R: smithy_client::retry::NewRequestPolicy,
{
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> std::result::Result<
crate::output::GetContactChannelOutput,
smithy_http::result::SdkError<crate::error::GetContactChannelError>,
>
where
R::Policy: smithy_client::bounds::SmithyRetryPolicy<
crate::input::GetContactChannelInputOperationOutputAlias,
crate::output::GetContactChannelOutput,
crate::error::GetContactChannelError,
crate::input::GetContactChannelInputOperationRetryAlias,
>,
{
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The Amazon Resource Name (ARN) of the contact channel you want information about.</p>
pub fn contact_channel_id(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.contact_channel_id(inp);
self
}
pub fn set_contact_channel_id(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_contact_channel_id(input);
self
}
}
#[derive(std::fmt::Debug)]
pub struct GetContactPolicy<
C = smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::get_contact_policy_input::Builder,
}
impl<C, M, R> GetContactPolicy<C, M, R>
where
C: smithy_client::bounds::SmithyConnector,
M: smithy_client::bounds::SmithyMiddleware<C>,
R: smithy_client::retry::NewRequestPolicy,
{
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> std::result::Result<
crate::output::GetContactPolicyOutput,
smithy_http::result::SdkError<crate::error::GetContactPolicyError>,
>
where
R::Policy: smithy_client::bounds::SmithyRetryPolicy<
crate::input::GetContactPolicyInputOperationOutputAlias,
crate::output::GetContactPolicyOutput,
crate::error::GetContactPolicyError,
crate::input::GetContactPolicyInputOperationRetryAlias,
>,
{
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The Amazon Resource Name (ARN) of the contact or escalation plan.</p>
pub fn contact_arn(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.contact_arn(inp);
self
}
pub fn set_contact_arn(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_contact_arn(input);
self
}
}
#[derive(std::fmt::Debug)]
pub struct ListContactChannels<
C = smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::list_contact_channels_input::Builder,
}
impl<C, M, R> ListContactChannels<C, M, R>
where
C: smithy_client::bounds::SmithyConnector,
M: smithy_client::bounds::SmithyMiddleware<C>,
R: smithy_client::retry::NewRequestPolicy,
{
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> std::result::Result<
crate::output::ListContactChannelsOutput,
smithy_http::result::SdkError<crate::error::ListContactChannelsError>,
>
where
R::Policy: smithy_client::bounds::SmithyRetryPolicy<
crate::input::ListContactChannelsInputOperationOutputAlias,
crate::output::ListContactChannelsOutput,
crate::error::ListContactChannelsError,
crate::input::ListContactChannelsInputOperationRetryAlias,
>,
{
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The Amazon Resource Name (ARN) of the contact. </p>
pub fn contact_id(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.contact_id(inp);
self
}
pub fn set_contact_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_contact_id(input);
self
}
/// <p>The pagination token to continue to the next page of results.</p>
pub fn next_token(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.next_token(inp);
self
}
pub fn set_next_token(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_next_token(input);
self
}
/// <p>The maximum number of contact channels per page.</p>
pub fn max_results(mut self, inp: i32) -> Self {
self.inner = self.inner.max_results(inp);
self
}
pub fn set_max_results(mut self, input: std::option::Option<i32>) -> Self {
self.inner = self.inner.set_max_results(input);
self
}
}
#[derive(std::fmt::Debug)]
pub struct ListContacts<
C = smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::list_contacts_input::Builder,
}
impl<C, M, R> ListContacts<C, M, R>
where
C: smithy_client::bounds::SmithyConnector,
M: smithy_client::bounds::SmithyMiddleware<C>,
R: smithy_client::retry::NewRequestPolicy,
{
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> std::result::Result<
crate::output::ListContactsOutput,
smithy_http::result::SdkError<crate::error::ListContactsError>,
>
where
R::Policy: smithy_client::bounds::SmithyRetryPolicy<
crate::input::ListContactsInputOperationOutputAlias,
crate::output::ListContactsOutput,
crate::error::ListContactsError,
crate::input::ListContactsInputOperationRetryAlias,
>,
{
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The pagination token to continue to the next page of results.</p>
pub fn next_token(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.next_token(inp);
self
}
pub fn set_next_token(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_next_token(input);
self
}
/// <p>The maximum number of contacts and escalation plans per page of results.</p>
pub fn max_results(mut self, inp: i32) -> Self {
self.inner = self.inner.max_results(inp);
self
}
pub fn set_max_results(mut self, input: std::option::Option<i32>) -> Self {
self.inner = self.inner.set_max_results(input);
self
}
/// <p>Used to list only contacts who's aliases start with the specified prefix.</p>
pub fn alias_prefix(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.alias_prefix(inp);
self
}
pub fn set_alias_prefix(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_alias_prefix(input);
self
}
/// <p>The type of contact. A contact is type <code>PERSONAL</code> and an escalation plan is
/// type <code>ESCALATION</code>.</p>
pub fn r#type(mut self, inp: crate::model::ContactType) -> Self {
self.inner = self.inner.r#type(inp);
self
}
pub fn set_type(mut self, input: std::option::Option<crate::model::ContactType>) -> Self {
self.inner = self.inner.set_type(input);
self
}
}
#[derive(std::fmt::Debug)]
pub struct ListEngagements<
C = smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::list_engagements_input::Builder,
}
impl<C, M, R> ListEngagements<C, M, R>
where
C: smithy_client::bounds::SmithyConnector,
M: smithy_client::bounds::SmithyMiddleware<C>,
R: smithy_client::retry::NewRequestPolicy,
{
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> std::result::Result<
crate::output::ListEngagementsOutput,
smithy_http::result::SdkError<crate::error::ListEngagementsError>,
>
where
R::Policy: smithy_client::bounds::SmithyRetryPolicy<
crate::input::ListEngagementsInputOperationOutputAlias,
crate::output::ListEngagementsOutput,
crate::error::ListEngagementsError,
crate::input::ListEngagementsInputOperationRetryAlias,
>,
{
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The pagination token to continue to the next page of results.</p>
pub fn next_token(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.next_token(inp);
self
}
pub fn set_next_token(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_next_token(input);
self
}
/// <p>The maximum number of engagements per page of results.</p>
pub fn max_results(mut self, inp: i32) -> Self {
self.inner = self.inner.max_results(inp);
self
}
pub fn set_max_results(mut self, input: std::option::Option<i32>) -> Self {
self.inner = self.inner.set_max_results(input);
self
}
/// <p>The Amazon Resource Name (ARN) of the incident you're listing engagements for.</p>
pub fn incident_id(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.incident_id(inp);
self
}
pub fn set_incident_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_incident_id(input);
self
}
/// <p>The time range to lists engagements for an incident.</p>
pub fn time_range_value(mut self, inp: crate::model::TimeRange) -> Self {
self.inner = self.inner.time_range_value(inp);
self
}
pub fn set_time_range_value(
mut self,
input: std::option::Option<crate::model::TimeRange>,
) -> Self {
self.inner = self.inner.set_time_range_value(input);
self
}
}
#[derive(std::fmt::Debug)]
pub struct ListPageReceipts<
C = smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::list_page_receipts_input::Builder,
}
impl<C, M, R> ListPageReceipts<C, M, R>
where
C: smithy_client::bounds::SmithyConnector,
M: smithy_client::bounds::SmithyMiddleware<C>,
R: smithy_client::retry::NewRequestPolicy,
{
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> std::result::Result<
crate::output::ListPageReceiptsOutput,
smithy_http::result::SdkError<crate::error::ListPageReceiptsError>,
>
where
R::Policy: smithy_client::bounds::SmithyRetryPolicy<
crate::input::ListPageReceiptsInputOperationOutputAlias,
crate::output::ListPageReceiptsOutput,
crate::error::ListPageReceiptsError,
crate::input::ListPageReceiptsInputOperationRetryAlias,
>,
{
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The Amazon Resource Name (ARN) of the engagement to a specific contact channel.</p>
pub fn page_id(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.page_id(inp);
self
}
pub fn set_page_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_page_id(input);
self
}
/// <p>The pagination token to continue to the next page of results.</p>
pub fn next_token(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.next_token(inp);
self
}
pub fn set_next_token(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_next_token(input);
self
}
/// <p>The maximum number of acknowledgements per page of results.</p>
pub fn max_results(mut self, inp: i32) -> Self {
self.inner = self.inner.max_results(inp);
self
}
pub fn set_max_results(mut self, input: std::option::Option<i32>) -> Self {
self.inner = self.inner.set_max_results(input);
self
}
}
#[derive(std::fmt::Debug)]
pub struct ListPagesByContact<
C = smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::list_pages_by_contact_input::Builder,
}
impl<C, M, R> ListPagesByContact<C, M, R>
where
C: smithy_client::bounds::SmithyConnector,
M: smithy_client::bounds::SmithyMiddleware<C>,
R: smithy_client::retry::NewRequestPolicy,
{
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> std::result::Result<
crate::output::ListPagesByContactOutput,
smithy_http::result::SdkError<crate::error::ListPagesByContactError>,
>
where
R::Policy: smithy_client::bounds::SmithyRetryPolicy<
crate::input::ListPagesByContactInputOperationOutputAlias,
crate::output::ListPagesByContactOutput,
crate::error::ListPagesByContactError,
crate::input::ListPagesByContactInputOperationRetryAlias,
>,
{
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The Amazon Resource Name (ARN) of the contact you are retrieving engagements for.</p>
pub fn contact_id(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.contact_id(inp);
self
}
pub fn set_contact_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_contact_id(input);
self
}
/// <p>The pagination token to continue to the next page of results.</p>
pub fn next_token(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.next_token(inp);
self
}
pub fn set_next_token(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_next_token(input);
self
}
/// <p>The maximum number of engagements to contact channels to list per page of results. </p>
pub fn max_results(mut self, inp: i32) -> Self {
self.inner = self.inner.max_results(inp);
self
}
pub fn set_max_results(mut self, input: std::option::Option<i32>) -> Self {
self.inner = self.inner.set_max_results(input);
self
}
}
#[derive(std::fmt::Debug)]
pub struct ListPagesByEngagement<
C = smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::list_pages_by_engagement_input::Builder,
}
impl<C, M, R> ListPagesByEngagement<C, M, R>
where
C: smithy_client::bounds::SmithyConnector,
M: smithy_client::bounds::SmithyMiddleware<C>,
R: smithy_client::retry::NewRequestPolicy,
{
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> std::result::Result<
crate::output::ListPagesByEngagementOutput,
smithy_http::result::SdkError<crate::error::ListPagesByEngagementError>,
>
where
R::Policy: smithy_client::bounds::SmithyRetryPolicy<
crate::input::ListPagesByEngagementInputOperationOutputAlias,
crate::output::ListPagesByEngagementOutput,
crate::error::ListPagesByEngagementError,
crate::input::ListPagesByEngagementInputOperationRetryAlias,
>,
{
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The Amazon Resource Name (ARN) of the engagement.</p>
pub fn engagement_id(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.engagement_id(inp);
self
}
pub fn set_engagement_id(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_engagement_id(input);
self
}
/// <p>The pagination token to continue to the next page of results.</p>
pub fn next_token(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.next_token(inp);
self
}
pub fn set_next_token(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_next_token(input);
self
}
/// <p>The maximum number of engagements to contact channels to list per page of
/// results.</p>
pub fn max_results(mut self, inp: i32) -> Self {
self.inner = self.inner.max_results(inp);
self
}
pub fn set_max_results(mut self, input: std::option::Option<i32>) -> Self {
self.inner = self.inner.set_max_results(input);
self
}
}
#[derive(std::fmt::Debug)]
pub struct ListTagsForResource<
C = smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::list_tags_for_resource_input::Builder,
}
impl<C, M, R> ListTagsForResource<C, M, R>
where
C: smithy_client::bounds::SmithyConnector,
M: smithy_client::bounds::SmithyMiddleware<C>,
R: smithy_client::retry::NewRequestPolicy,
{
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> std::result::Result<
crate::output::ListTagsForResourceOutput,
smithy_http::result::SdkError<crate::error::ListTagsForResourceError>,
>
where
R::Policy: smithy_client::bounds::SmithyRetryPolicy<
crate::input::ListTagsForResourceInputOperationOutputAlias,
crate::output::ListTagsForResourceOutput,
crate::error::ListTagsForResourceError,
crate::input::ListTagsForResourceInputOperationRetryAlias,
>,
{
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The Amazon Resource Name (ARN) of the contact or escalation plan.</p>
pub fn resource_arn(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.resource_arn(inp);
self
}
pub fn set_resource_arn(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_resource_arn(input);
self
}
}
#[derive(std::fmt::Debug)]
pub struct PutContactPolicy<
C = smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::put_contact_policy_input::Builder,
}
impl<C, M, R> PutContactPolicy<C, M, R>
where
C: smithy_client::bounds::SmithyConnector,
M: smithy_client::bounds::SmithyMiddleware<C>,
R: smithy_client::retry::NewRequestPolicy,
{
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> std::result::Result<
crate::output::PutContactPolicyOutput,
smithy_http::result::SdkError<crate::error::PutContactPolicyError>,
>
where
R::Policy: smithy_client::bounds::SmithyRetryPolicy<
crate::input::PutContactPolicyInputOperationOutputAlias,
crate::output::PutContactPolicyOutput,
crate::error::PutContactPolicyError,
crate::input::PutContactPolicyInputOperationRetryAlias,
>,
{
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The Amazon Resource Name (ARN) of the contact or escalation plan.</p>
pub fn contact_arn(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.contact_arn(inp);
self
}
pub fn set_contact_arn(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_contact_arn(input);
self
}
/// <p>Details of the resource policy.</p>
pub fn policy(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.policy(inp);
self
}
pub fn set_policy(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_policy(input);
self
}
}
#[derive(std::fmt::Debug)]
pub struct SendActivationCode<
C = smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::send_activation_code_input::Builder,
}
impl<C, M, R> SendActivationCode<C, M, R>
where
C: smithy_client::bounds::SmithyConnector,
M: smithy_client::bounds::SmithyMiddleware<C>,
R: smithy_client::retry::NewRequestPolicy,
{
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> std::result::Result<
crate::output::SendActivationCodeOutput,
smithy_http::result::SdkError<crate::error::SendActivationCodeError>,
>
where
R::Policy: smithy_client::bounds::SmithyRetryPolicy<
crate::input::SendActivationCodeInputOperationOutputAlias,
crate::output::SendActivationCodeOutput,
crate::error::SendActivationCodeError,
crate::input::SendActivationCodeInputOperationRetryAlias,
>,
{
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The Amazon Resource Name (ARN) of the contact channel.</p>
pub fn contact_channel_id(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.contact_channel_id(inp);
self
}
pub fn set_contact_channel_id(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_contact_channel_id(input);
self
}
}
#[derive(std::fmt::Debug)]
pub struct StartEngagement<
C = smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::start_engagement_input::Builder,
}
impl<C, M, R> StartEngagement<C, M, R>
where
C: smithy_client::bounds::SmithyConnector,
M: smithy_client::bounds::SmithyMiddleware<C>,
R: smithy_client::retry::NewRequestPolicy,
{
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> std::result::Result<
crate::output::StartEngagementOutput,
smithy_http::result::SdkError<crate::error::StartEngagementError>,
>
where
R::Policy: smithy_client::bounds::SmithyRetryPolicy<
crate::input::StartEngagementInputOperationOutputAlias,
crate::output::StartEngagementOutput,
crate::error::StartEngagementError,
crate::input::StartEngagementInputOperationRetryAlias,
>,
{
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The Amazon Resource Name (ARN) of the contact being engaged.</p>
pub fn contact_id(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.contact_id(inp);
self
}
pub fn set_contact_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_contact_id(input);
self
}
/// <p>The user that started the engagement.</p>
pub fn sender(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.sender(inp);
self
}
pub fn set_sender(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_sender(input);
self
}
/// <p>The secure subject of the message that was sent to the contact. Use this field for
/// engagements to <code>VOICE</code> or <code>EMAIL</code>.</p>
pub fn subject(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.subject(inp);
self
}
pub fn set_subject(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_subject(input);
self
}
/// <p>The secure content of the message that was sent to the contact. Use this field for
/// engagements to <code>VOICE</code> or <code>EMAIL</code>.</p>
pub fn content(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.content(inp);
self
}
pub fn set_content(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_content(input);
self
}
/// <p>The insecure subject of the message that was sent to the contact. Use this field for
/// engagements to <code>SMS</code>.</p>
pub fn public_subject(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.public_subject(inp);
self
}
pub fn set_public_subject(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_public_subject(input);
self
}
/// <p>The insecure content of the message that was sent to the contact. Use this field for
/// engagements to <code>SMS</code>.</p>
pub fn public_content(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.public_content(inp);
self
}
pub fn set_public_content(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_public_content(input);
self
}
/// <p>The ARN of the incident that the engagement is part of.</p>
pub fn incident_id(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.incident_id(inp);
self
}
pub fn set_incident_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_incident_id(input);
self
}
/// <p>A token ensuring that the operation is called only once with the specified
/// details.</p>
pub fn idempotency_token(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.idempotency_token(inp);
self
}
pub fn set_idempotency_token(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_idempotency_token(input);
self
}
}
#[derive(std::fmt::Debug)]
pub struct StopEngagement<
C = smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::stop_engagement_input::Builder,
}
impl<C, M, R> StopEngagement<C, M, R>
where
C: smithy_client::bounds::SmithyConnector,
M: smithy_client::bounds::SmithyMiddleware<C>,
R: smithy_client::retry::NewRequestPolicy,
{
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> std::result::Result<
crate::output::StopEngagementOutput,
smithy_http::result::SdkError<crate::error::StopEngagementError>,
>
where
R::Policy: smithy_client::bounds::SmithyRetryPolicy<
crate::input::StopEngagementInputOperationOutputAlias,
crate::output::StopEngagementOutput,
crate::error::StopEngagementError,
crate::input::StopEngagementInputOperationRetryAlias,
>,
{
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The Amazon Resource Name (ARN) of the engagement.</p>
pub fn engagement_id(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.engagement_id(inp);
self
}
pub fn set_engagement_id(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_engagement_id(input);
self
}
/// <p>The reason that you're stopping the engagement. </p>
pub fn reason(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.reason(inp);
self
}
pub fn set_reason(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_reason(input);
self
}
}
#[derive(std::fmt::Debug)]
pub struct TagResource<
C = smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::tag_resource_input::Builder,
}
impl<C, M, R> TagResource<C, M, R>
where
C: smithy_client::bounds::SmithyConnector,
M: smithy_client::bounds::SmithyMiddleware<C>,
R: smithy_client::retry::NewRequestPolicy,
{
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> std::result::Result<
crate::output::TagResourceOutput,
smithy_http::result::SdkError<crate::error::TagResourceError>,
>
where
R::Policy: smithy_client::bounds::SmithyRetryPolicy<
crate::input::TagResourceInputOperationOutputAlias,
crate::output::TagResourceOutput,
crate::error::TagResourceError,
crate::input::TagResourceInputOperationRetryAlias,
>,
{
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The Amazon Resource Name (ARN) of the contact or escalation plan.</p>
pub fn resource_arn(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.resource_arn(inp);
self
}
pub fn set_resource_arn(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_resource_arn(input);
self
}
/// Appends an item to `Tags`.
///
/// To override the contents of this collection use [`set_tags`](Self::set_tags).
/// <p>A list of tags that you are adding to the contact or escalation plan.</p>
pub fn tags(mut self, inp: impl Into<crate::model::Tag>) -> Self {
self.inner = self.inner.tags(inp);
self
}
pub fn set_tags(
mut self,
input: std::option::Option<std::vec::Vec<crate::model::Tag>>,
) -> Self {
self.inner = self.inner.set_tags(input);
self
}
}
#[derive(std::fmt::Debug)]
pub struct UntagResource<
C = smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::untag_resource_input::Builder,
}
impl<C, M, R> UntagResource<C, M, R>
where
C: smithy_client::bounds::SmithyConnector,
M: smithy_client::bounds::SmithyMiddleware<C>,
R: smithy_client::retry::NewRequestPolicy,
{
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> std::result::Result<
crate::output::UntagResourceOutput,
smithy_http::result::SdkError<crate::error::UntagResourceError>,
>
where
R::Policy: smithy_client::bounds::SmithyRetryPolicy<
crate::input::UntagResourceInputOperationOutputAlias,
crate::output::UntagResourceOutput,
crate::error::UntagResourceError,
crate::input::UntagResourceInputOperationRetryAlias,
>,
{
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The Amazon Resource Name (ARN) of the contact or escalation plan.</p>
pub fn resource_arn(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.resource_arn(inp);
self
}
pub fn set_resource_arn(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_resource_arn(input);
self
}
/// Appends an item to `TagKeys`.
///
/// To override the contents of this collection use [`set_tag_keys`](Self::set_tag_keys).
/// <p>The key of the tag that you want to remove.</p>
pub fn tag_keys(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.tag_keys(inp);
self
}
pub fn set_tag_keys(
mut self,
input: std::option::Option<std::vec::Vec<std::string::String>>,
) -> Self {
self.inner = self.inner.set_tag_keys(input);
self
}
}
#[derive(std::fmt::Debug)]
pub struct UpdateContact<
C = smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::update_contact_input::Builder,
}
impl<C, M, R> UpdateContact<C, M, R>
where
C: smithy_client::bounds::SmithyConnector,
M: smithy_client::bounds::SmithyMiddleware<C>,
R: smithy_client::retry::NewRequestPolicy,
{
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> std::result::Result<
crate::output::UpdateContactOutput,
smithy_http::result::SdkError<crate::error::UpdateContactError>,
>
where
R::Policy: smithy_client::bounds::SmithyRetryPolicy<
crate::input::UpdateContactInputOperationOutputAlias,
crate::output::UpdateContactOutput,
crate::error::UpdateContactError,
crate::input::UpdateContactInputOperationRetryAlias,
>,
{
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The Amazon Resource Name (ARN) of the contact or escalation plan you're updating.</p>
pub fn contact_id(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.contact_id(inp);
self
}
pub fn set_contact_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_contact_id(input);
self
}
/// <p>The full name of the contact or escalation plan.</p>
pub fn display_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.display_name(inp);
self
}
pub fn set_display_name(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_display_name(input);
self
}
/// <p>A list of stages. A contact has an engagement plan with stages for specified contact
/// channels. An escalation plan uses these stages to contact specified contacts. </p>
pub fn plan(mut self, inp: crate::model::Plan) -> Self {
self.inner = self.inner.plan(inp);
self
}
pub fn set_plan(mut self, input: std::option::Option<crate::model::Plan>) -> Self {
self.inner = self.inner.set_plan(input);
self
}
}
#[derive(std::fmt::Debug)]
pub struct UpdateContactChannel<
C = smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::update_contact_channel_input::Builder,
}
impl<C, M, R> UpdateContactChannel<C, M, R>
where
C: smithy_client::bounds::SmithyConnector,
M: smithy_client::bounds::SmithyMiddleware<C>,
R: smithy_client::retry::NewRequestPolicy,
{
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> std::result::Result<
crate::output::UpdateContactChannelOutput,
smithy_http::result::SdkError<crate::error::UpdateContactChannelError>,
>
where
R::Policy: smithy_client::bounds::SmithyRetryPolicy<
crate::input::UpdateContactChannelInputOperationOutputAlias,
crate::output::UpdateContactChannelOutput,
crate::error::UpdateContactChannelError,
crate::input::UpdateContactChannelInputOperationRetryAlias,
>,
{
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The Amazon Resource Name (ARN) of the contact channel you want to update.</p>
pub fn contact_channel_id(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.contact_channel_id(inp);
self
}
pub fn set_contact_channel_id(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_contact_channel_id(input);
self
}
/// <p>The name of the contact channel.</p>
pub fn name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.name(inp);
self
}
pub fn set_name(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_name(input);
self
}
/// <p>The details that Incident Manager uses when trying to engage the contact channel. </p>
pub fn delivery_address(mut self, inp: crate::model::ContactChannelAddress) -> Self {
self.inner = self.inner.delivery_address(inp);
self
}
pub fn set_delivery_address(
mut self,
input: std::option::Option<crate::model::ContactChannelAddress>,
) -> Self {
self.inner = self.inner.set_delivery_address(input);
self
}
}
}
impl<C> Client<C, aws_hyper::AwsMiddleware, smithy_client::retry::Standard> {
pub fn from_conf_conn(conf: crate::Config, conn: C) -> Self {
let client = aws_hyper::Client::new(conn);
Self {
handle: std::sync::Arc::new(Handle { client, conf }),
}
}
}
impl
Client<
smithy_client::erase::DynConnector,
aws_hyper::AwsMiddleware,
smithy_client::retry::Standard,
>
{
#[cfg(any(feature = "rustls", feature = "native-tls"))]
pub fn new(config: &aws_types::config::Config) -> Self {
Self::from_conf(config.into())
}
#[cfg(any(feature = "rustls", feature = "native-tls"))]
pub fn from_conf(conf: crate::Config) -> Self {
let client = aws_hyper::Client::https();
Self {
handle: std::sync::Arc::new(Handle { client, conf }),
}
}
}
| true |
4cdf51d47e762fb92c2b5ef7f0fc73dc0af807ea
|
Rust
|
hegza/serpent-rs
|
/src/transpile/rust.rs
|
UTF-8
| 605 | 2.6875 | 3 |
[
"MIT"
] |
permissive
|
use rustc_ap_rustc_ast::ast::{Item, ItemKind, Stmt, StmtKind};
/// An item, a statement, a newline or a comment of Rust.
#[derive(Clone, Debug)]
pub enum NodeKind {
/// An anonymous Rust AST item matching with rustc_ast::ItemKind.
Item(ItemKind),
/// A Rust AST item with attributes, ident, etc. matching with
/// rustc_ast::Item.
ExtendedItem(Item),
/// A Rust statement matching with rustc_ast::StmtKind.
Stmt(StmtKind),
/// A Rust statement with attributes, ident, etc. matching with
/// rustc_ast::Stmt.
ExtendedStmt(Stmt),
Newline,
Comment(String),
}
| true |
4116dc16a74536b558df6f83c8505d3ca5973e5b
|
Rust
|
multifacet/0sim-experiments
|
/src/bin/memcached_and_capture_thp.rs
|
UTF-8
| 6,060 | 2.609375 | 3 |
[] |
no_license
|
//! Sits in a loop doing `put` operations on the given memcached instance. The keys are unique, but
//! the values are large, all-zero values.
//!
//! We do N insertions, followed by N/3 deletions, followed by N/2 more insertions.
//!
//! In the meantime, every N seconds, it executes syscall 335 to get THP compaction stats, where N
//! is a command line arg. The results are printed to stdout.
//!
//! NOTE: This should be run from a machine that has a high-bandwidth, low-latency connection with
//! the test machine.
//!
//! NOTE: The server should be started with e.g. `memcached -m 50000` for 50GB.
use std::{
fs::OpenOptions,
io::{BufWriter, Write},
sync::{
atomic::{AtomicBool, Ordering},
Arc,
},
time::Duration,
};
use bmk_linux::timing::rdtsc;
use clap::clap_app;
use memcache::Client;
use paperexp::CompactInstrumentationStats;
/// The TTL of the key/value pairs
const EXPIRATION: u32 = 1_000_000; // A really long time
/// The order of magnitude of the size of the values
const VAL_ORDER: usize = 19; // 20 seems to give a "too large" error
/// 2^`VAL_ORDER`
const VAL_SIZE: usize = 1 << VAL_ORDER;
/// A big array that constitutes the values to be `put`
const ZEROS: &[u8] = &[0; VAL_SIZE];
fn is_addr(arg: String) -> Result<(), String> {
use std::net::ToSocketAddrs;
arg.to_socket_addrs()
.map_err(|_| "Not a valid IP:Port".to_owned())
.map(|_| ())
}
fn is_int(arg: String) -> Result<(), String> {
arg.to_string()
.parse::<usize>()
.map_err(|_| "Not a valid usize".to_owned())
.map(|_| ())
}
macro_rules! try_again {
($e:expr) => {{
if let Err(e) = $e {
println!("unexpected error: {:?}", e);
if let Err(e) = $e {
println!("unexpected error: {:?}", e);
return;
}
}
}};
}
fn run() {
let matches = clap_app! { time_mmap_touch =>
(@arg MEMCACHED: +required {is_addr} "The IP:PORT of the memcached instance")
(@arg SIZE: +required {is_int} "The amount of data to put (in GB)")
(@arg INTERVAL: +required {is_int} "The interval at which to read compaction stats")
(@arg OUTFILE: +required "The location to write memcached performance measurements to")
(@arg CONTINUAL: --continual_compaction "Continually trigger compaction")
}
.get_matches();
// Get the memcached addr
let addr = matches.value_of("MEMCACHED").unwrap();
// Get the amount of data to put
let size = matches
.value_of("SIZE")
.unwrap()
.to_string()
.parse::<usize>()
.unwrap()
<< 30;
// Total number of `put`s required
let nputs = size / VAL_SIZE;
// Connect to the kv-store
let mut client = Client::new(format!("memcache://{}", addr).as_str()).unwrap();
// Interval to poll
let interval = matches
.value_of("INTERVAL")
.unwrap()
.to_string()
.parse::<u64>()
.unwrap();
let memcached_latency_file = matches.value_of("OUTFILE").unwrap();
let continual_compaction = matches.is_present("CONTINUAL");
// Start a thread that does stuff
let stop_flag = Arc::new(AtomicBool::new(false));
let measure_thread = {
let stop_flag = Arc::clone(&stop_flag);
std::thread::spawn(move || {
let mut prev = 0;
loop {
// Sleep for a while
std::thread::sleep(Duration::from_secs(interval));
// Take a measurement
let CompactInstrumentationStats { ops, undos } =
paperexp::thp_compact_instrumentation();
// once the flag is set, wait to stabilize...
if stop_flag.load(Ordering::Relaxed) {
if ops == prev {
break;
}
}
prev = ops;
println!("{} {}", ops, undos);
}
})
};
// A thread that triggers continual compaction
let compact_thread = if continual_compaction {
let stop_flag = Arc::clone(&stop_flag);
Some(std::thread::spawn(move || {
loop {
// Take a measurement
paperexp::trigger_compaction(512).expect("trigger compaction failed");
// once the flag is set, exit
if stop_flag.load(Ordering::Relaxed) {
break;
}
}
}))
} else {
None
};
// Open a file for the latency measurements
let memcached_latency_file = OpenOptions::new()
.write(true)
.truncate(true)
.create(true)
.open(memcached_latency_file)
.unwrap();
let mut memcached_latency_file = BufWriter::new(memcached_latency_file);
// Do the work.
for i in 0..nputs {
let start = rdtsc();
// `put`
try_again!(client.set(&format!("{}", i), ZEROS, EXPIRATION));
write!(memcached_latency_file, "{}\n", rdtsc() - start).unwrap();
}
println!("NEXT!");
writeln!(memcached_latency_file, "NEXT!").unwrap();
// delete a third of previously inserted keys (they are random because memcached is a hashmap).
for i in 0..nputs / 3 {
let start = rdtsc();
try_again!(client.delete(&format!("{}", i)));
write!(memcached_latency_file, "{}\n", rdtsc() - start).unwrap();
}
println!("NEXT!");
writeln!(memcached_latency_file, "NEXT!").unwrap();
// insert more keys
for i in nputs..(nputs + nputs / 2) {
let start = rdtsc();
// `put`
try_again!(client.set(&format!("{}", i), ZEROS, EXPIRATION));
write!(memcached_latency_file, "{}\n", rdtsc() - start).unwrap();
}
println!("DONE!");
stop_flag.store(true, Ordering::Relaxed);
measure_thread.join().unwrap();
if let Some(compact_thread) = compact_thread {
compact_thread.join().unwrap();
}
}
fn main() {
run();
}
| true |
333678a476a4f451f9e5678e5d228cc2469d0748
|
Rust
|
wieslander/aoc-2019
|
/src/bin/07-02.rs
|
UTF-8
| 1,000 | 2.78125 | 3 |
[] |
no_license
|
use itertools::Itertools;
use std::cmp;
use aoc::get_input;
use aoc::intcode::Program;
fn main() {
let initial_memory = get_input()
.split(',')
.map(|x| x.parse().expect("NaN"))
.collect();
let mut max_output = 0;
let mut amps = vec![];
for _ in 0..5 {
let amp = Program::new(&initial_memory);
amps.push(amp);
}
for phases in (5..10).permutations(5) {
let mut propagated_value = 0;
for (amp, &phase) in amps.iter_mut().zip(&phases) {
amp.reset(&initial_memory);
amp.set_input(phase);
}
while amps[amps.len() - 1].is_running() {
for amp in amps.iter_mut() {
amp.set_input(propagated_value);
if let Some(output) = amp.pause_on_output() {
propagated_value = output;
}
}
}
max_output = cmp::max(propagated_value, max_output);
}
println!("{}", max_output);
}
| true |
c31b5c8522fd55129ad3704e7871a7526dc3ae24
|
Rust
|
liguangsheng/leetcode-rust
|
/src/a0643_maximum_average_subarray_i.rs
|
UTF-8
| 932 | 3.359375 | 3 |
[
"MIT"
] |
permissive
|
/*
* [0643] maximum-average-subarray-i
*/
pub struct Solution {}
// solution impl starts here
impl Solution {
pub fn find_max_average(nums: Vec<i32>, k: i32) -> f64 {
let mut max_sum;
let mut sum = 0;
for i in 0..=k - 1 {
sum += nums[i as usize];
}
max_sum = sum;
for i in k..=(nums.len() - 1) as i32 {
sum = sum - nums[(i - k) as usize] + nums[i as usize];
max_sum = if sum > max_sum { sum } else { max_sum };
}
max_sum as f64 / k as f64
}
}
// solution impl ends here
// solution tests starts here
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_case0() {
assert_eq!(Solution::find_max_average(vec![1, 2, 3, 4], 2), 3.5f64);
assert_eq!(
Solution::find_max_average(vec![1, 12, -5, -6, 50, 3], 4),
12.75f64
);
}
}
// solution tests ends here
| true |
f6d76eda012d671e2f72ac0aa41b9510ef65ab9c
|
Rust
|
Inspirateur/DungeonChess
|
/src/pgn.rs
|
UTF-8
| 908 | 3.203125 | 3 |
[
"MIT"
] |
permissive
|
use crate::piece::{Action, Piece};
use crate::pos::Pos;
fn piece2pgn(piece: Piece) -> &'static str {
match piece {
Piece::Pawn {
orientation: _,
status: _,
} => "p",
Piece::Knight => "N",
Piece::Bishop => "B",
Piece::Rook => "R",
Piece::Queen => "Q",
Piece::King => "K",
}
}
fn pos2pgn(pos: Pos) -> String {
let letters = ["a", "b", "c", "d", "e", "f", "g", "h"];
format!("{}{}", letters[pos.0 as usize], 8 - pos.1)
}
pub fn move2pgn(pos: Pos, actions: &Vec<Action>) -> String {
let mut res = String::new();
for action in actions {
if let Action::Go(go_pos) = action {
res += format!("{}{}", pos2pgn(pos), pos2pgn(*go_pos)).as_str();
} else if let Action::Promotion(piece) = action {
res += format!("={}", piece2pgn(*piece)).as_str();
}
}
res
}
| true |
aa77f422f615c90169d345aee2faa66fc6671fff
|
Rust
|
deadalusai/raytracer
|
/raytracer-impl/src/texture.rs
|
UTF-8
| 3,138 | 3.109375 | 3 |
[] |
no_license
|
use std::sync::Arc;
use super::implementation::{ Texture, HitRecord };
use super::types::{ V2, V3 };
// Constant colors
#[derive(Clone)]
pub struct ColorTexture(pub V3);
impl Texture for ColorTexture {
fn value(&self, _hit_record: &HitRecord) -> V3 {
self.0
}
}
// Checker texture
#[derive(Clone)]
pub struct CheckerTexture<T1: Texture, T2: Texture> {
size: f32,
odd: T1,
even: T2,
}
impl<T1: Texture, T2: Texture> CheckerTexture<T1, T2> {
pub fn new(size: f32, odd: T1, even: T2) -> Self {
Self { size, odd, even }
}
}
impl<T1: Texture, T2: Texture> Texture for CheckerTexture<T1, T2> {
fn value(&self, hit_record: &HitRecord) -> V3 {
let sines =
(self.size * hit_record.p.x()).sin() *
(self.size * hit_record.p.y()).sin() *
(self.size * hit_record.p.z()).sin();
if sines < 0.0 {
self.odd.value(hit_record)
}
else {
self.even.value(hit_record)
}
}
}
// Test texture
pub struct UvTestTexture;
impl Texture for UvTestTexture {
fn value(&self, hit_record: &HitRecord) -> V3 {
let V2(u, v) = hit_record.uv;
V3(u, v, 1.0 - u - v)
}
}
pub struct XyzTestTexture(pub f32);
impl Texture for XyzTestTexture {
fn value(&self, hit_record: &HitRecord) -> V3 {
fn map_into_range(max: f32, v: f32) -> f32 {
// Values on {-max..0..+max} range mapped to {0..1} range, so {0} always corresponds to {0.5}
0.5 + (v / max / 2.0)
}
let V3(x, y, z) = hit_record.p;
V3(map_into_range(self.0, x),
map_into_range(self.0, y),
map_into_range(self.0, z))
}
}
// Image texture / color maps
pub struct ColorMap {
pub width: usize,
pub height: usize,
pub pixels: Vec<V3>,
}
impl Texture for ColorMap {
fn value(&self, hit_record: &HitRecord) -> V3 {
let x = (hit_record.uv.0 * self.width as f32) as usize;
let y = (hit_record.uv.1 * self.height as f32) as usize;
let offset = y * self.width + x;
self.pixels.get(offset).cloned().unwrap_or_default()
}
}
/// A texture loaded from an OBJ mtl ile
pub struct MeshTexture {
pub name: String,
pub ambient_color: V3,
pub diffuse_color: V3,
pub diffuse_color_map: Option<Arc<ColorMap>>,
}
impl Texture for MeshTexture {
fn value(&self, hit_record: &HitRecord) -> V3 {
self.ambient_color + match self.diffuse_color_map {
Some(ref map) => map.value(hit_record) * self.diffuse_color,
None => self.diffuse_color
}
}
}
// A collection of OBJ mtl materials.
// Only supported if the HitRecord specifies a {tex_key}
pub struct MeshTextureSet {
pub textures: Vec<MeshTexture>,
}
const NOT_FOUND_COLOR: V3 = V3(1.0, 0.41, 0.70); // #FF69B4
impl Texture for MeshTextureSet {
fn value(&self, hit_record: &HitRecord) -> V3 {
hit_record.tex_key
.and_then(|key| self.textures.get(key))
.map(|mat| mat.value(hit_record))
// texture not found
.unwrap_or(NOT_FOUND_COLOR)
}
}
| true |
4a3e0845beb24167fd5fe7ccc8974ee1b6a74a2e
|
Rust
|
antonromanov1/dragon-book-compiler
|
/src/ir.rs
|
UTF-8
| 19,397 | 2.875 | 3 |
[] |
no_license
|
use std::cell::RefCell;
use std::rc::Rc;
use crate::lexer::*;
macro_rules! unreachable {
() => {
panic!("Unreachable code");
};
}
fn error(s: &str, line: u32) -> ! {
println!("near line {}: {}", line, s);
std::process::exit(0);
}
pub fn emit_label(i: u32) {
print!("L{}:", i);
}
fn emit(s: String) {
println!("\t{}", s);
}
// Expressions:
pub trait ExprAble {
fn gen(&self) -> Box<dyn ExprAble>;
fn reduce(&self) -> Box<dyn ExprAble>;
fn jumping(&self, t: u32, f: u32);
fn emit_jumps(&self, test: String, t: u32, f: u32);
fn to_string(&self) -> String;
fn get_type(&self) -> &TypeBase;
}
#[derive(Clone)]
pub struct ExprBase {
op: Token,
type_: TypeBase,
}
impl ExprBase {
pub fn new(tok: Token, p: TypeBase) -> ExprBase {
ExprBase { op: tok, type_: p }
}
fn get_op(&self) -> &Token {
&self.op
}
}
impl ExprAble for ExprBase {
fn gen(&self) -> Box<dyn ExprAble> {
Box::new(self.clone())
}
fn reduce(&self) -> Box<dyn ExprAble> {
Box::new(self.clone())
}
fn emit_jumps(&self, test: String, t: u32, f: u32) {
if t != 0 && f != 0 {
emit(format!("if {} goto L{}", test, t));
emit(format!("goto L{}", f));
} else if t != 0 {
emit(format!("if {} goto L{}", test, t));
} else if f != 0 {
emit(format!("iffalse {} goto L{}", test, f));
}
}
fn to_string(&self) -> String {
self.op.to_string()
}
fn jumping(&self, t: u32, f: u32) {
self.emit_jumps(self.to_string(), t, f);
}
fn get_type(&self) -> &TypeBase {
&self.type_
}
}
macro_rules! gen {
( $self:ident, $field:ident ) => {
fn gen(&$self) -> Box<dyn ExprAble> {
$self.$field.gen()
}
}
}
macro_rules! reduce {
( $self:ident, $field:ident ) => {
fn reduce(&$self) -> Box<dyn ExprAble> {
$self.$field.gen()
}
}
}
macro_rules! jumping {
( $self:ident, $field:ident ) => {
fn jumping(&$self, t: u32, f: u32) {
$self.$field.jumping(t, f);
}
}
}
macro_rules! emit_jumps {
( $self:ident, $field:ident ) => {
fn emit_jumps(&$self, test: String, t: u32, f: u32) {
$self.$field.emit_jumps(test, t, f);
}
}
}
macro_rules! to_string {
( $self:ident, $field:ident ) => {
fn to_string(&$self) -> String {
$self.$field.to_string()
}
}
}
macro_rules! get_type {
( $self:ident, $field:ident ) => {
fn get_type(&$self) -> &TypeBase {
$self.$field.get_type()
}
}
}
struct Temp {
expr_base: ExprBase,
number: u8,
}
impl Temp {
fn new(p: TypeBase, temp_count: Rc<RefCell<u8>>) -> Temp {
{
let mut reference = temp_count.borrow_mut();
*reference = *reference + 1;
}
Temp {
expr_base: ExprBase {
op: Token::Word(Word::Word(WordBase {
lexeme: "t".to_string(),
token: TokenBase {
tag: Tag::Temp as u32,
},
})),
type_: p,
},
number: *temp_count.borrow(),
}
}
}
impl ExprAble for Temp {
fn to_string(&self) -> String {
format!("t{}", self.number)
}
// Explicitly inherited:
gen! {self, expr_base}
reduce! {self, expr_base}
jumping! {self, expr_base}
emit_jumps! {self, expr_base}
get_type! {self, expr_base}
}
#[derive(Clone)]
pub struct Id {
expr_base: ExprBase,
offset: u32,
}
impl Id {
pub fn new(id: WordBase, p: TypeBase, b: u32) -> Id {
Id {
expr_base: ExprBase::new(Token::Word(Word::Word(id)), p),
offset: b,
}
}
}
impl ExprAble for Id {
// All explicitly inherited
gen! {self, expr_base}
reduce! {self, expr_base}
jumping! {self, expr_base}
emit_jumps! {self, expr_base}
to_string! {self, expr_base}
get_type! {self, expr_base}
}
struct OpBase {
expr_base: ExprBase,
pub temp_count: Rc<RefCell<u8>>,
}
impl OpBase {
pub fn new(tok: Token, p: TypeBase, count: Rc<RefCell<u8>>) -> OpBase {
OpBase {
expr_base: ExprBase::new(tok, p),
temp_count: count,
}
}
}
macro_rules! op_reduce {
( $self:expr ) => {{
let x = $self.gen();
let t = Box::new(Temp::new(
(*$self.get_type()).clone(),
$self.temp_count.clone(),
));
emit(format!("{} = {}", t.to_string(), x.to_string()));
t
}};
}
impl ExprAble for OpBase {
fn reduce(&self) -> Box<dyn ExprAble> {
op_reduce!(self)
}
// Explicitly inherited:
gen! {self, expr_base}
jumping! {self, expr_base}
emit_jumps! {self, expr_base}
to_string! {self, expr_base}
get_type! {self, expr_base}
}
pub struct Arith {
op_base: OpBase,
expr1: Box<dyn ExprAble>,
expr2: Box<dyn ExprAble>,
line: u32,
temp_count: Rc<RefCell<u8>>,
}
impl Arith {
pub fn new(
tok: Token,
x1: Box<dyn ExprAble>,
x2: Box<dyn ExprAble>,
line: u32,
count: Rc<RefCell<u8>>,
) -> Arith {
let type1 = (*x1).get_type();
let type2 = (*x2).get_type();
match TypeBase::max(type1, type2) {
Some(type_base) => {
return Arith {
op_base: OpBase::new(tok, type_base, count.clone()),
expr1: x1,
expr2: x2,
line: line,
temp_count: count.clone(),
};
}
None => error("type error", line),
};
}
}
impl ExprAble for Arith {
fn gen(&self) -> Box<dyn ExprAble> {
Box::new(Arith::new(
self.op_base.expr_base.op.clone(),
self.expr1.reduce(),
self.expr2.reduce(),
self.line,
self.op_base.temp_count.clone(),
))
}
fn to_string(&self) -> String {
format!(
"{} {} {}",
(*self.expr1).to_string(),
self.op_base.expr_base.op.to_string(),
(*self.expr2).to_string()
)
}
// Explicitly inherited:
fn reduce(&self) -> Box<dyn ExprAble> {
op_reduce!(self)
}
jumping! {self, op_base}
emit_jumps! {self, op_base}
get_type! {self, op_base}
}
pub struct Unary {
op_base: OpBase,
expr: Box<dyn ExprAble>,
}
impl Unary {
pub fn new(tok: Token, x: Box<dyn ExprAble>, count: Rc<RefCell<u8>>) -> Unary {
let type_ = TypeBase::max(&type_int(), (*x).get_type());
if type_ == None {
panic!("type error");
}
Unary {
op_base: OpBase::new(tok, type_.unwrap(), count),
expr: x,
}
}
}
impl ExprAble for Unary {
fn gen(&self) -> Box<dyn ExprAble> {
Box::new(Unary::new(
self.op_base.expr_base.op.clone(),
(*self.expr).reduce(),
self.op_base.temp_count.clone(),
))
}
fn to_string(&self) -> String {
self.op_base.expr_base.op.to_string().clone() + &(*self.expr).to_string()
}
// Explicitly inherited
reduce! {self, op_base}
jumping! {self, op_base}
emit_jumps! {self, op_base}
get_type! {self, op_base}
}
pub struct Constant {
expr_base: ExprBase,
}
impl Constant {
pub fn new(tok: Token, p: TypeBase) -> Constant {
Constant {
expr_base: ExprBase::new(tok, p),
}
}
}
#[inline]
pub fn constant_true() -> Constant {
Constant {
expr_base: ExprBase::new(Token::Word(Word::Word(word_true())), type_bool()),
}
}
#[inline]
pub fn constant_false() -> Constant {
Constant {
expr_base: ExprBase::new(Token::Word(Word::Word(word_false())), type_bool()),
}
}
impl ExprAble for Constant {
fn jumping(&self, t: u32, f: u32) {
match &self.expr_base.op {
Token::Word(word) => match word {
Word::Word(base) => {
if (base.lexeme == "true".to_string()) && (t != 0) {
emit(format!("goto L{}", t));
} else if (base.lexeme == "false".to_string()) && (f != 0) {
emit(format!("goto L{}", f));
}
}
_ => {}
},
_ => {}
}
}
// Explicitly inherited:
gen! {self, expr_base}
reduce! {self, expr_base}
emit_jumps! {self, expr_base}
to_string! {self, expr_base}
get_type! {self, expr_base}
}
pub fn new_label(labels: Rc<RefCell<u32>>) -> u32 {
*labels.borrow_mut() += 1;
*labels.borrow()
}
struct Logical {
pub expr_base: ExprBase,
pub expr1: Box<dyn ExprAble>,
pub expr2: Box<dyn ExprAble>,
temp_count: Rc<RefCell<u8>>,
labels: Rc<RefCell<u32>>,
}
macro_rules! logical_construct {
( $check:expr, $tok:ident, $x1:ident, $x2:ident, $count:ident, $labels:ident ) => {{
if $check((*$x1).get_type(), (*$x2).get_type()) {
Logical {
expr_base: ExprBase::new($tok, type_bool()),
expr1: $x1,
expr2: $x2,
temp_count: $count,
labels: $labels,
}
} else {
panic!("type error");
}
}};
}
impl Logical {
fn new(
tok: Token,
x1: Box<dyn ExprAble>,
x2: Box<dyn ExprAble>,
count: Rc<RefCell<u8>>,
labels: Rc<RefCell<u32>>,
) -> Logical {
logical_construct!(Logical::check, tok, x1, x2, count, labels)
}
fn check(p1: &TypeBase, p2: &TypeBase) -> bool {
if *p1 == type_bool() && *p2 == type_bool() {
true
} else {
false
}
}
}
macro_rules! logical_gen {
( $self:expr, $labels:expr, $count:expr ) => {{
let f = new_label($labels.clone());
let a = new_label($labels.clone());
let temp = Temp::new((*$self.get_type()).clone(), $count.clone());
$self.jumping(0, f);
emit(format!("{} = true", temp.to_string()));
emit(format!("goto L{}", a));
emit_label(f);
emit(format!("{} = false", temp.to_string()));
emit_label(a);
Box::new(temp)
}};
}
impl ExprAble for Logical {
fn gen(&self) -> Box<dyn ExprAble> {
logical_gen!(self, self.labels, self.temp_count)
}
fn to_string(&self) -> String {
format!(
"{} {} {}",
(*self.expr1).to_string(),
self.expr_base.op.to_string(),
(*self.expr2).to_string()
)
}
// Explicitly inherited:
reduce! {self, expr_base}
jumping! {self, expr_base}
emit_jumps! {self, expr_base}
get_type! {self, expr_base}
}
pub struct And {
logic: Logical,
}
impl And {
pub fn new(
tok: Token,
x1: Box<dyn ExprAble>,
x2: Box<dyn ExprAble>,
count: Rc<RefCell<u8>>,
labels: Rc<RefCell<u32>>,
) -> And {
And {
logic: Logical::new(tok, x1, x2, count, labels),
}
}
}
impl ExprAble for And {
fn jumping(&self, t: u32, f: u32) {
let label: u32;
if f != 0 {
label = f;
} else {
label = new_label(self.logic.labels.clone());
}
self.logic.expr1.jumping(0, label);
self.logic.expr2.jumping(t, f);
if f == 0 {
emit_label(label);
}
}
// Explicitly inherited:
gen! {self, logic}
reduce! {self, logic}
emit_jumps! {self, logic}
to_string! {self, logic}
get_type! {self, logic}
}
pub struct Or {
logic: Logical,
}
impl Or {
pub fn new(
tok: Token,
x1: Box<dyn ExprAble>,
x2: Box<dyn ExprAble>,
count: Rc<RefCell<u8>>,
labels: Rc<RefCell<u32>>,
) -> Or {
Or {
logic: Logical::new(tok, x1, x2, count, labels),
}
}
}
impl ExprAble for Or {
fn jumping(&self, t: u32, f: u32) {
let label: u32;
if t != 0 {
label = t;
} else {
label = new_label(self.logic.labels.clone());
}
self.logic.expr1.jumping(label, 0);
self.logic.expr2.jumping(t, f);
if t == 0 {
emit_label(label);
}
}
// Explicitly inherited:
gen! {self, logic}
reduce! {self, logic}
emit_jumps! {self, logic}
to_string! {self, logic}
get_type! {self, logic}
}
pub struct Not {
logic: Logical,
}
impl Not {
pub fn new(
tok: Token,
x2: Box<dyn ExprAble>,
count: Rc<RefCell<u8>>,
labels: Rc<RefCell<u32>>,
) -> Not {
// I use Box::new(Id::new()) as an unuseful thing cause Logical requires 2 pointers
// TODO: rewrite it
Not {
logic: Logical::new(
tok,
Box::new(Id::new(word_true(), type_bool(), 0)),
x2,
count,
labels,
),
}
}
}
impl ExprAble for Not {
fn jumping(&self, t: u32, f: u32) {
(*self.logic.expr2).jumping(f, t);
}
fn to_string(&self) -> String {
format!(
"{} {}",
self.logic.expr_base.op.to_string(),
self.logic.expr2.to_string()
)
}
// Explicitly inherited:
gen! {self, logic}
reduce! {self, logic}
emit_jumps! {self, logic}
get_type! {self, logic}
}
pub struct Rel {
logic: Logical,
}
impl Rel {
pub fn new(
tok: Token,
x1: Box<dyn ExprAble>,
x2: Box<dyn ExprAble>,
count: Rc<RefCell<u8>>,
labels: Rc<RefCell<u32>>,
) -> Rel {
Rel {
logic: logical_construct!(Rel::check, tok, x1, x2, count, labels),
}
}
fn check(p1: &TypeBase, p2: &TypeBase) -> bool {
if *p1 == *p2 {
true
} else {
false
}
}
}
impl ExprAble for Rel {
fn gen(&self) -> Box<dyn ExprAble> {
logical_gen!(self, self.logic.labels, self.logic.temp_count)
}
fn jumping(&self, t: u32, f: u32) {
let a = self.logic.expr1.reduce();
let b = self.logic.expr2.reduce();
let test = a.to_string()
+ " "
+ &(*self.logic.expr_base.get_op()).to_string()
+ " "
+ &b.to_string();
self.emit_jumps(test, t, f);
}
// Explicitly inherited:
reduce! {self, logic}
emit_jumps! {self, logic}
to_string! {self, logic}
get_type! {self, logic}
}
// Statements:
pub trait StmtAble {
// gen is called with labels begin, after and _gen_after which is passed by While node
fn gen(&self, _b: u32, _a: u32, _gen_after: u32) {}
fn is_null(&self) -> bool {
false
}
fn init(&mut self, _x: Box<dyn ExprAble>, _s: Box<dyn StmtAble>) {
unreachable!();
}
}
pub struct Null {}
impl StmtAble for Null {
fn is_null(&self) -> bool {
true
}
}
pub struct Break {}
impl StmtAble for Break {
fn gen(&self, _b: u32, _a: u32, gen_after: u32) {
emit(format!("goto L{}", gen_after));
}
}
pub struct Seq {
stmt1: Box<dyn StmtAble>,
stmt2: Box<dyn StmtAble>,
labels: Rc<RefCell<u32>>,
}
impl Seq {
pub fn new(s1: Box<dyn StmtAble>, s2: Box<dyn StmtAble>, labels: Rc<RefCell<u32>>) -> Seq {
Seq {
stmt1: s1,
stmt2: s2,
labels: labels,
}
}
}
impl StmtAble for Seq {
fn gen(&self, b: u32, a: u32, gen_after: u32) {
if (*self.stmt1).is_null() {
(*self.stmt2).gen(b, a, gen_after);
} else if (*self.stmt2).is_null() {
(*self.stmt1).gen(b, a, gen_after);
} else {
let label = new_label(self.labels.clone());
(*self.stmt1).gen(b, label, gen_after);
emit_label(label);
(*self.stmt2).gen(label, a, gen_after);
}
}
}
pub struct Set {
id: Box<dyn ExprAble>,
expr: Box<dyn ExprAble>,
}
impl Set {
pub fn new(i: Box<dyn ExprAble>, x: Box<dyn ExprAble>) -> Set {
let p1 = (*i).get_type();
let p2 = (*x).get_type();
if numeric(p1) && numeric(p2) {
} else if *p1 == type_bool() && *p2 == type_bool() {
} else {
panic!("type error");
}
Set { id: i, expr: x }
}
}
impl StmtAble for Set {
fn gen(&self, _b: u32, _a: u32, _gen_after: u32) {
emit(format!(
"{} = {}",
(*self.id).to_string(),
(*(*self.expr).gen()).to_string()
));
}
}
pub struct If {
expr: Box<dyn ExprAble>,
stmt: Box<dyn StmtAble>,
labels: Rc<RefCell<u32>>,
}
macro_rules! bool_check {
( $x:ident, $line:expr ) => {
if *(*$x).get_type() != type_bool() {
error("boolean required in if", $line);
}
};
}
impl If {
pub fn new(
x: Box<dyn ExprAble>,
s: Box<dyn StmtAble>,
line: u32,
labels: Rc<RefCell<u32>>,
) -> If {
bool_check!(x, line);
If {
expr: x,
stmt: s,
labels: labels,
}
}
}
impl StmtAble for If {
fn gen(&self, _b: u32, a: u32, gen_after: u32) {
let label = new_label(self.labels.clone());
(*self.expr).jumping(0, a);
emit_label(label);
(*self.stmt).gen(label, a, gen_after);
}
}
pub struct Else {
expr: Box<dyn ExprAble>,
stmt1: Box<dyn StmtAble>,
stmt2: Box<dyn StmtAble>,
labels: Rc<RefCell<u32>>,
}
impl Else {
pub fn new(
x: Box<dyn ExprAble>,
s1: Box<dyn StmtAble>,
s2: Box<dyn StmtAble>,
line: u32,
labels: Rc<RefCell<u32>>,
) -> Else {
bool_check!(x, line);
Else {
expr: x,
stmt1: s1,
stmt2: s2,
labels: labels,
}
}
}
impl StmtAble for Else {
fn gen(&self, _b: u32, a: u32, gen_after: u32) {
let label1 = new_label(self.labels.clone());
let label2 = new_label(self.labels.clone());
self.expr.jumping(0, label2);
emit_label(label1);
(*self.stmt1).gen(label1, a, gen_after);
emit(format!("goto L{}", a));
emit_label(label2);
(*self.stmt2).gen(label2, a, gen_after);
}
}
pub struct While {
expr: Option<Box<dyn ExprAble>>,
stmt: Option<Box<dyn StmtAble>>,
line: u32,
labels: Rc<RefCell<u32>>,
}
impl While {
pub fn new(line: u32, labels: Rc<RefCell<u32>>) -> While {
While {
expr: None,
stmt: None,
line: line,
labels: labels,
}
}
}
impl StmtAble for While {
fn gen(&self, b: u32, a: u32, _gen_after: u32) {
self.expr.as_ref().unwrap().jumping(0, a);
let label = new_label(self.labels.clone());
emit_label(label);
self.stmt.as_ref().unwrap().gen(label, b, a);
emit(format!("goto L{}", b));
}
fn init(&mut self, x: Box<dyn ExprAble>, s: Box<dyn StmtAble>) {
bool_check!(x, self.line);
self.expr = Some(x);
self.stmt = Some(s);
}
}
| true |
5e2e8151f993b80a5a341565f288f258c583142b
|
Rust
|
fooki/pong-deathmatch
|
/src/server.rs
|
UTF-8
| 1,011 | 2.984375 | 3 |
[] |
no_license
|
use crate::server_network::ServerNet;
use crate::server_state::{ServerState, WaitingForP1};
use laminar::{ErrorKind};
use std::net::SocketAddr;
pub fn run(my_addr: &str) ->Result<(), ErrorKind> {
let addr: SocketAddr = my_addr.parse().unwrap();
let net = ServerNet::bind(addr)?;
let initial_state = Box::new(WaitingForP1::new());
let mut server = Server::new(net, initial_state);
println!("State: {:?}", server.state);
loop {
server.update()?;
}
}
struct Server {
net: ServerNet,
state: Box<dyn ServerState>,
}
impl Server {
fn new(net: ServerNet, initial_state: Box<dyn ServerState>) -> Self {
Self { net, state: initial_state }
}
// Runs the server within one state until the server changes state.
fn update(&mut self) -> Result<(), ErrorKind> {
if let Some(new_state) = self.state.update(&mut self.net)? {
println!("State: {:?}", &new_state);
self.state = new_state;
}
Ok(())
}
}
| true |
05f1ba2791030bf51067dc1c64590ceb13a2db72
|
Rust
|
kellerkindt/w5500
|
/src/host/mod.rs
|
UTF-8
| 2,263 | 2.796875 | 3 |
[
"MIT",
"Apache-2.0"
] |
permissive
|
mod dhcp;
mod manual;
pub use self::dhcp::Dhcp;
pub use self::manual::Manual;
use crate::bus::Bus;
use crate::register;
use crate::MacAddress;
use embedded_nal::Ipv4Addr;
#[derive(Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct HostConfig {
mac: MacAddress,
#[cfg_attr(feature = "defmt", defmt(Display2Format))]
ip: Ipv4Addr,
#[cfg_attr(feature = "defmt", defmt(Display2Format))]
gateway: Ipv4Addr,
#[cfg_attr(feature = "defmt", defmt(Display2Format))]
subnet: Ipv4Addr,
}
impl Default for HostConfig {
fn default() -> Self {
Self {
mac: MacAddress::default(),
ip: Ipv4Addr::unspecified(),
gateway: Ipv4Addr::unspecified(),
subnet: Ipv4Addr::unspecified(),
}
}
}
pub trait Host {
/// Gets (if necessary) and sets the host settings on the chip
fn refresh<SpiBus: Bus>(&mut self, bus: &mut SpiBus) -> Result<(), SpiBus::Error>;
/// Write changed settings to chip
///
/// Will check all settings and write any new ones to the chip. Will update the settings returned by `current`
/// with any changes.
fn write_settings<SpiBus: Bus>(
bus: &mut SpiBus,
current: &mut HostConfig,
settings: &HostConfig,
) -> Result<(), SpiBus::Error> {
if settings.gateway != current.gateway {
let address = settings.gateway.octets();
bus.write_frame(register::COMMON, register::common::GATEWAY, &address)?;
current.gateway = settings.gateway;
}
if settings.subnet != current.subnet {
let address = settings.subnet.octets();
bus.write_frame(register::COMMON, register::common::SUBNET_MASK, &address)?;
current.subnet = settings.subnet;
}
if settings.mac != current.mac {
let address = settings.mac.octets;
bus.write_frame(register::COMMON, register::common::MAC, &address)?;
current.mac = settings.mac;
}
if settings.ip != current.ip {
let address = settings.ip.octets();
bus.write_frame(register::COMMON, register::common::IP, &address)?;
current.ip = settings.ip;
}
Ok(())
}
}
| true |
9fb7b8c3c179d863a3fda9c3d787b28334627895
|
Rust
|
algeriastartupjobs/algeriastartupjobs.com
|
/api/src/search/service.rs
|
UTF-8
| 9,648 | 2.5625 | 3 |
[
"MIT"
] |
permissive
|
use bk_tree::{metrics, BKTree};
use itertools::Itertools;
use serde::{Deserialize, Serialize};
use sqlx::{Pool, QueryBuilder, Row, Sqlite};
use std::sync::{Arc, Mutex};
use crate::{
_utils::{
error::SearchError,
string::{escape_double_quote, get_searchable_words, get_words},
},
account::model::{AccountNameTrait, CompactAccount},
post::model::Post,
tag::model::CompactTag,
};
#[derive(Debug, Serialize, Deserialize)]
struct WordIndex {
word: String,
model_id: u32,
appear_in: String,
}
#[derive(Debug, Serialize, Deserialize)]
struct WordRecord {
word: String,
}
pub struct SearchService {
search_sql_db: Arc<Pool<Sqlite>>,
bk_tree: Arc<Mutex<BKTree<String>>>,
}
impl SearchService {
pub fn new(search_sql_db: Arc<Pool<Sqlite>>) -> Self {
Self {
search_sql_db,
bk_tree: Arc::new(Mutex::new(BKTree::new(metrics::Levenshtein))),
}
}
pub async fn refresh_bk_tree(&self) -> Result<(), SearchError> {
let conn = self.search_sql_db.acquire().await;
if conn.is_err() {
tracing::error!(
"Error while getting sql connection to refresh bk tree: {:?}",
conn
);
return Err(SearchError::InternalError);
}
let mut conn = conn.unwrap();
// @TODO-ZM: figure out how query $ replacement work, there is some unneeded "magic" here
let db_result = sqlx::query(
r#"
SELECT DISTINCT word
FROM word
WHERE appear_in IN ('post_title', 'post_short_description', 'post_tag_name', 'post_poster_display_name');
"#,
)
.fetch_all(&mut *conn)
.await;
if db_result.is_err() {
tracing::error!("Error while getting all words: {:?}", db_result.err());
return Err(SearchError::InternalError);
}
let db_result = db_result.unwrap();
let mut words = vec![];
for row in db_result {
words.push(row.get::<String, _>("word"));
}
let bk_tree = self.bk_tree.lock();
if bk_tree.is_err() {
tracing::error!("Error while getting bk tree lock: {:?}", bk_tree.err());
return Err(SearchError::InternalError);
}
let mut bk_tree = bk_tree.unwrap();
// @TODO-ZM: clean the tree before adding new words
for word in words {
bk_tree.add(word);
}
Ok(())
}
pub async fn index_posts(
&self,
posts: Vec<Post>,
tags: Vec<CompactTag>,
posters: Vec<CompactAccount>,
) -> Result<(), SearchError> {
let mut word_indexes: Vec<WordIndex> = vec![];
for post in posts {
// @TODO-ZM: use regex \d to split the string
get_words(&post.title).for_each(|word| {
let word = word.to_lowercase();
word_indexes.push(WordIndex {
word,
model_id: post.id,
appear_in: "post_title".to_string(),
});
});
get_words(&post.description).for_each(|word| {
let word = word.to_lowercase();
word_indexes.push(WordIndex {
word,
model_id: post.id,
appear_in: "post_description".to_string(),
});
});
for tag_id in post.tag_ids {
let tag = tags
.iter()
.find(|tag| tag.id == tag_id)
.map(|tag| tag.clone());
if tag.is_none() {
tracing::error!("Failed to find the tag by id {}", tag_id,);
return Err(SearchError::InternalError);
};
let tag = tag.unwrap();
get_words(&tag.name).for_each(|word| {
let word = word.to_lowercase();
word_indexes.push(WordIndex {
word,
model_id: post.id,
appear_in: "post_tag_name".to_string(),
});
});
}
let poster = posters.iter().find(|poster| poster.id == post.poster_id);
if poster.is_none() {
tracing::error!("Failed to find the poster");
return Err(SearchError::InternalError);
}
let poster = poster.unwrap();
get_words(&poster.get_display_name()).for_each(|word| {
let word = word.to_lowercase();
word_indexes.push(WordIndex {
word,
model_id: post.id,
appear_in: "post_poster_display_name".to_string(),
});
});
}
let conn = self.search_sql_db.acquire().await;
if conn.is_err() {
tracing::error!("Error while getting sql connection to index: {:?}", conn);
return Err(SearchError::InternalError);
}
let mut conn = conn.unwrap();
let mut query_builder =
QueryBuilder::new("INSERT INTO word (word, model_type, model_id, appear_in) ");
query_builder.push_values(word_indexes, |mut b, new_word_index| {
b.push_bind(new_word_index.word)
.push_bind("post")
.push_bind(new_word_index.model_id)
.push_bind(new_word_index.appear_in);
});
let db_result = query_builder.build().execute(&mut *conn).await;
if db_result.is_err() {
tracing::error!("Error while indexing posts: {:?}", db_result);
return Err(SearchError::InternalError);
}
Ok(())
}
fn get_corrected_queries(&self, query: &String, max_suggestions: u8) -> Vec<String> {
let query_words = get_searchable_words(query);
let bk_tree = self.bk_tree.lock().unwrap();
let mut corrected_words_in_queries = vec![];
for query_word in &query_words {
let mut corrected_words_with_distance = vec![];
let tolerance = query_word.len() / 2;
bk_tree
.find(query_word, tolerance as u32)
.for_each(|(distance, corrected_word)| {
corrected_words_with_distance.push((distance, corrected_word));
});
corrected_words_with_distance.sort_by_key(|k| k.0);
corrected_words_in_queries.push(
corrected_words_with_distance
.iter()
.map(|(_, corrected_word)| corrected_word)
.map(|corrected_word| escape_double_quote(corrected_word))
.collect::<Vec<String>>(),
);
}
let mut corrected_queries = vec![];
for index in 0..max_suggestions {
let mut corrected_query_words = vec![];
for query_word_index in 0..query_words.len() {
let corrected_word = corrected_words_in_queries
.get(query_word_index)
.unwrap()
.get(index as usize);
match corrected_word {
Some(corrected_word) => corrected_query_words.push(corrected_word.as_str()),
None => corrected_query_words.push({
match query_words.get(query_word_index) {
Some(query_word) => query_word,
None => "",
}
}),
}
}
corrected_queries.push(corrected_query_words.join(" "));
}
// filter out the original query
let corrected_queries = corrected_queries
.iter()
.filter(|corrected_query| *corrected_query != query)
.map(|corrected_query| corrected_query.to_string())
.collect::<Vec<String>>();
corrected_queries
}
// @TODO-ZM: add pagination
pub async fn search_posts(&self, query: &String) -> Result<Vec<u32>, SearchError> {
let conn = self.search_sql_db.acquire().await;
if conn.is_err() {
tracing::error!("Error while getting sql connection to search: {:?}", conn);
return Err(SearchError::InternalError);
}
let mut conn = conn.unwrap();
let mut search_queries = self.get_corrected_queries(query, 3);
search_queries.insert(0, query.clone());
let search_queries_count = search_queries.len();
let query = search_queries
.iter()
.enumerate()
.map(|(index, search_query)| {
format!(
r#"
SELECT model_id, SUM(count * weight * {}) AS score
FROM (
SELECT id, word, model_type, model_id, appear_in, count(*) AS count,
CASE
WHEN appear_in = 'post_title' THEN 100
WHEN appear_in = 'post_poster_display_name' THEN 50
WHEN appear_in = 'post_short_description' THEN 25
WHEN appear_in = 'post_tag_name' THEN 5
ELSE 1
END AS weight
FROM word
WHERE word In ({})
GROUP BY word, model_type, model_id, appear_in
) AS sub
GROUP BY model_id
ORDER BY score DESC;
"#,
search_queries_count - index,
// @TODO-ZM: Potential SQL injection vulnerability!
search_query
.split(" ")
.map(|word| format!("'{}'", word))
.join(", "),
)
})
.collect::<Vec<String>>()
.join("\n");
let db_results = sqlx::query(&query).fetch_all(&mut *conn).await;
if db_results.is_err() {
tracing::error!("Error while searching posts: {:?}", db_results.err());
return Err(SearchError::InternalError);
}
let db_results = db_results.unwrap();
let mut model_ids_with_scores = vec![];
for row in db_results {
model_ids_with_scores.push((row.get::<u32, _>("model_id"), row.get::<i64, _>("score")));
}
// aggregate the scores for the same model_id
let mut model_ids_with_scores = model_ids_with_scores
.into_iter()
.sorted_by_key(|(model_id, _)| *model_id)
.group_by(|(model_id, _)| *model_id)
.into_iter()
.map(|(model_id, group)| {
let mut score = 0;
for (_, group_score) in group {
score += group_score;
}
(model_id, score)
})
.collect::<Vec<(u32, i64)>>();
model_ids_with_scores.sort_by_key(|(_, score)| -score);
let model_ids_sorted = model_ids_with_scores
.iter()
.map(|(model_id, _)| *model_id)
.collect::<Vec<u32>>();
Ok(model_ids_sorted)
}
}
| true |
986a472f3ca3a8045c72926b4e00aab47bcbb4b0
|
Rust
|
Kryod/rustacean
|
/src/commands/versions.rs
|
UTF-8
| 1,180 | 2.703125 | 3 |
[] |
no_license
|
use serenity::{
prelude::Context,
model::channel::Message,
framework::standard::{ CommandResult, macros::command },
};
#[command]
#[aliases("version", "ver")]
fn versions(ctx: &mut Context, msg: &Message) -> CommandResult {
let data = ctx.data.read();
let lang_manager = data.get::<crate::LangManager>().unwrap().lock().unwrap();
let mut fields: Vec<(String, String, bool)> = Vec::new();
for boxed_lang in lang_manager.get_languages().values() {
if lang_manager.is_language_available(&(*boxed_lang)) {
let version = lang_manager.get_language_version(&(*boxed_lang));
let version_str = match version {
Some(version) => version,
None => String::from("Not Available")
};
fields.push((
boxed_lang.get_lang_name(),
version_str,
true
));
}
}
fields.sort();
let _ = msg.channel_id.send_message(&ctx, |m| m
.embed(|e| e
.title("Versions")
.description("A list of versions of languages available.")
.fields(fields)
)
)?;
Ok(())
}
| true |
43f563519a373f2b18aee6425970b68a12a7fa38
|
Rust
|
justahero/ok-sudoku
|
/src/parser.rs
|
UTF-8
| 1,736 | 2.953125 | 3 |
[] |
no_license
|
use peg::parser;
use crate::sudoku::{GridError, Sudoku};
parser! {
grammar sudoku_parser() for str {
rule empty() -> u8
= $(['-' | '.' | '0' ]) { 0 }
rule number() -> u8
= n:$(['0'..='9']) { str::parse::<u8>(n).unwrap() }
rule _ = [' ' | '\n' | '\r' | '\t']*
rule field() -> u8
= _ n:number() _ { n }
/ _ e:empty() _ { e }
rule numbers() -> Vec<u8>
= n:field() * { n }
pub(crate) rule parse() -> Sudoku
= numbers:numbers() { Sudoku::new(numbers).unwrap() }
}
}
pub fn parse_sudoku(grid: &str) -> Result<Sudoku, GridError> {
sudoku_parser::parse(grid)
.map_err(|e| GridError::ParseError(e.to_string()))
}
#[cfg(test)]
mod test {
use crate::Sudoku;
use crate::parser::parse_sudoku;
#[test]
fn test_parse_sudoku() {
let input = r"
000 --- 984
4.. 8.. 25.
.8. .49 ..3
9.6 157 8.2
... ... .4.
... .8. 196
.34 928 56.
6.2 .15 37.
..5 .6. ...
";
let expected = vec![
0, 0, 0, 0, 0, 0, 9, 8, 4,
4, 0, 0, 8, 0, 0, 2, 5, 0,
0, 8, 0, 0, 4, 9, 0, 0, 3,
9, 0, 6, 1, 5, 7, 8, 0, 2,
0, 0, 0, 0, 0, 0, 0, 4, 0,
0, 0, 0, 0, 8, 0, 1, 9, 6,
0, 3, 4, 9, 2, 8, 5, 6, 0,
6, 0, 2, 0, 1, 5, 3, 7, 0,
0, 0, 5, 0, 6, 0, 0, 0, 0,
];
let expected = Sudoku::new(expected).unwrap();
let result = parse_sudoku(input);
assert!(result.is_ok());
let actual = result.unwrap();
assert_eq!(expected, actual);
}
}
| true |
bf703aabaffb29e5b1c2b7de658ef48ecb2498b2
|
Rust
|
Orca-bit/DataStructureAndAlgorithm
|
/src/union_find/_399_evaluate_division.rs
|
UTF-8
| 3,025 | 3.328125 | 3 |
[] |
no_license
|
use std::collections::HashMap;
struct Solution;
impl Solution {
pub fn calc_equation(
equations: Vec<Vec<String>>,
values: Vec<f64>,
queries: Vec<Vec<String>>,
) -> Vec<f64> {
let n = equations.len();
let mut union_find = UnionFind::new(n * 2);
let mut map = HashMap::with_capacity(n * 2);
let mut id = 0;
for (i, eq) in equations.iter().enumerate() {
let var1 = eq[0].clone();
let var2 = eq[1].clone();
if !map.contains_key(&var1) {
map.insert(var1.clone(), id);
id += 1;
}
if !map.contains_key(&var2) {
map.insert(var2.clone(), id);
id += 1;
}
union_find.union(
*map.get(&var1).unwrap(),
*map.get(&var2).unwrap(),
values[i],
);
}
let mut res = vec![0.; queries.len()];
for (i, que) in queries.iter().enumerate() {
let var1 = que[0].clone();
let var2 = que[1].clone();
let id1 = map.get(&var1);
let id2 = map.get(&var2);
if id1.is_none() || id2.is_none() {
res[i] = -1.;
} else {
res[i] = union_find.connect(*id1.unwrap(), *id2.unwrap());
}
}
res
}
}
struct UnionFind {
parent: Vec<usize>,
weights: Vec<f64>,
}
impl UnionFind {
fn new(n: usize) -> Self {
Self {
parent: (0..n).collect(),
weights: vec![1.; n],
}
}
fn find(&mut self, i: usize) -> usize {
let j = self.parent[i];
if i == j {
i
} else {
let k = self.find(j);
self.parent[i] = k;
self.weights[i] *= self.weights[j];
k
}
}
fn union(&mut self, i: usize, j: usize, value: f64) {
let root_i = self.find(i);
let root_j = self.find(j);
if root_i == root_j {
return;
}
self.parent[root_i] = root_j;
self.weights[root_i] = value * self.weights[j] / self.weights[i];
}
fn connect(&mut self, i: usize, j: usize) -> f64 {
let root_i = self.find(i);
let root_j = self.find(j);
if root_i == root_j {
self.weights[i] / self.weights[j]
} else {
-1.
}
}
}
#[test]
fn test() {
let equations = vec![
vec!["a".to_string(), "b".to_string()],
vec!["b".to_string(), "c".to_string()],
];
let values = vec![2.0, 3.0];
let queries = vec![
vec!["a".to_string(), "c".to_string()],
vec!["b".to_string(), "a".to_string()],
vec!["a".to_string(), "e".to_string()],
vec!["a".to_string(), "a".to_string()],
vec!["x".to_string(), "x".to_string()],
];
let res = vec![6.0, 0.5, -1.0, 1.0, -1.0];
assert_eq!(Solution::calc_equation(equations, values, queries), res);
}
| true |
692f51b552cfa5659c3273eef2b8525903aed930
|
Rust
|
shioyama18/apue
|
/example/ch04_files_and_directories/e06_cp.rs
|
UTF-8
| 1,152 | 2.625 | 3 |
[
"MIT"
] |
permissive
|
use anyhow::Result;
use apue::c_void;
use apue::constants::FILE_MODE;
use apue::result::NumericResult;
use libc::{creat, lseek, open, read, write, O_RDONLY, SEEK_CUR};
use std::ffi::CString;
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
struct Opt {
#[structopt(parse(try_from_str = CString::new))]
source: CString,
#[structopt(parse(try_from_str = CString::new))]
target: CString,
}
const BUFFSIZE: usize = 1;
fn main() -> Result<()> {
let Opt { source, target } = Opt::from_args();
unsafe {
let src_fd = open(source.as_ptr(), O_RDONLY).non_negative()?;
let tgt_fd = creat(target.as_ptr(), FILE_MODE);
let buf = [0; BUFFSIZE];
while let Ok(n) = read(src_fd, c_void!(buf), BUFFSIZE).positive() {
// Mac OS X writes '0' byte for hole
if buf[0] == 0 {
lseek(tgt_fd, 1, SEEK_CUR).non_negative()?;
} else {
assert_eq!(
write(tgt_fd, c_void!(buf), n as usize),
n,
"Failed writing to target file."
);
}
}
}
Ok(())
}
| true |
c32a678a55708b0d79627c744d79635bcb816aa1
|
Rust
|
rodrimati1992/abi_stable_crates
|
/abi_stable/src/abi_stability/extra_checks.rs
|
UTF-8
| 28,321 | 2.890625 | 3 |
[
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] |
permissive
|
//! Contains items for adding checks to individual types.
//!
//! # Implementing and using ExtraChecks
//!
//! To add extra checks to a type follow these steps:
//!
//! - Create some type and implement ExtraChecks for it,
//!
//! - Apply the `#[sabi(extra_checks = const expression that implements ExtraChecks)]`
//! attribute to a type that uses `#[derive(StableAbi)]`.
//!
//! # Combination
//!
//! This is how an ExtraChecks can be combined across all
//! dynamic libraries to ensure some property(which can be relied on for safety).
//!
//! This is a very similar process to how abi_stable ensures that
//! vtables and modules are consistent across dynamic libraries.
//!
//! ### Failure
//!
//! Loading many libraries that contain ExtraChecks trait objects that need
//! to be combined can fail if the representative version of the trait objects
//! are incompatible with those of the library,
//! even if both the library and the binary are otherwise compatible.
//!
//! The graphs below uses the `LIBRARY( ExtraChecks trait object )` format,
//! where the trait object is compatible only if the one in the binary
//! is a prefix of the string in the library,
//! and all the libraries have a prefix of the same string.
//!
//! This is fine:
//!
//! ```text
//! A("ab")<---B("abc")
//! \__________C("abcd")
//! ```
//!
//! This is not fine
//!
//! ```text
//! __________D("abe")
//! /
//! A("ab")<---B("abc")
//! \__________C("abcd")
//! ```
//!
//! The case that is not fine happens when the `ExtraChecks_TO::combine` method returned an error.
//!
//!
//! ### Example
//!
//! ```
//!
//! use abi_stable::{
//! abi_stability::{
//! check_layout_compatibility,
//! extra_checks::{
//! ExtraChecks, ExtraChecksBox, ExtraChecksError, ExtraChecksRef,
//! ExtraChecksStaticRef, ForExtraChecksImplementor, TypeCheckerMut,
//! },
//! },
//! marker_type::UnsafeIgnoredType,
//! sabi_extern_fn,
//! sabi_trait::prelude::TD_Opaque,
//! std_types::{RCow, RCowSlice, ROption, RResult, RSome, RStr},
//! type_layout::TypeLayout,
//! GetStaticEquivalent, StableAbi,
//! };
//!
//! use std::fmt::{self, Display};
//!
//! const LAYOUT0: &'static TypeLayout = <WithConstant<V1_0> as StableAbi>::LAYOUT;
//! const LAYOUT1: &'static TypeLayout = <WithConstant<V1_1> as StableAbi>::LAYOUT;
//! const LAYOUT1B: &'static TypeLayout =
//! <WithConstant<V1_1_Incompatible> as StableAbi>::LAYOUT;
//! const LAYOUT2: &'static TypeLayout = <WithConstant<V1_2> as StableAbi>::LAYOUT;
//!
//! fn main() {
//! // Compared LAYOUT0 to LAYOUT1B,
//! // then stored LAYOUT0.extra_checks as the ExtraChecks associated with both layouts.
//! check_layout_compatibility(LAYOUT0, LAYOUT1B).unwrap();
//!
//! // Compared LAYOUT1 to LAYOUT2,
//! // then stored LAYOUT2.extra_checks as the ExtraChecks associated with both layouts.
//! check_layout_compatibility(LAYOUT1, LAYOUT2).unwrap();
//!
//! // Compared LAYOUT0 to LAYOUT2:
//! // - the comparison succeeded,
//! // - then both are combined.
//! // - The combined trait object is attempted to be combined with the
//! // ExtraChecks in the global map associated to both LAYOUT0 and LAYOUT2,
//! // which are LAYOUT1B.extra_checks and LAYOUT2.extra_checks respectively.
//! // - Combining the trait objects with the ones in the global map fails because
//! // the one from LAYOUT1B is incompatible with the one from LAYOUT2.
//! check_layout_compatibility(LAYOUT0, LAYOUT2).unwrap_err();
//! }
//!
//! //////////////////////////////////////////////////////////////////////////////////
//!
//! #[repr(C)]
//! #[derive(StableAbi)]
//! #[sabi(
//! // Replaces the C:StableAbi constraint with `C:GetStaticEquivalent`
//! // (a supertrait of StableAbi).
//! not_stableabi(C),
//! bound(C: GetConstant),
//! extra_checks = Self::CHECKER
//! )]
//! struct WithConstant<C> {
//! // UnsafeIgnoredType is equivalent to PhantomData,
//! // except that all `UnsafeIgnoredType` are considered the same type by `StableAbi`.
//! _marker: UnsafeIgnoredType<C>,
//! }
//!
//! impl<C> WithConstant<C> {
//! const NEW: Self = Self {
//! _marker: UnsafeIgnoredType::NEW,
//! };
//! }
//!
//! impl<C> WithConstant<C>
//! where
//! C: GetConstant,
//! {
//! const CHECKER: ConstChecker = ConstChecker {
//! chars: RStr::from_str(C::CHARS),
//! };
//! }
//!
//! trait GetConstant {
//! const CHARS: &'static str;
//! }
//!
//! use self::constants::*;
//!
//! #[allow(non_camel_case_types)]
//! mod constants {
//! use super::*;
//!
//! #[derive(GetStaticEquivalent)]
//! pub struct V1_0;
//!
//! impl GetConstant for V1_0 {
//! const CHARS: &'static str = "ab";
//! }
//!
//! #[derive(GetStaticEquivalent)]
//! pub struct V1_1;
//!
//! impl GetConstant for V1_1 {
//! const CHARS: &'static str = "abc";
//! }
//!
//! #[derive(GetStaticEquivalent)]
//! pub struct V1_1_Incompatible;
//!
//! impl GetConstant for V1_1_Incompatible {
//! const CHARS: &'static str = "abd";
//! }
//!
//! #[derive(GetStaticEquivalent)]
//! pub struct V1_2;
//!
//! impl GetConstant for V1_2 {
//! const CHARS: &'static str = "abcd";
//! }
//! }
//!
//! /////////////////////////////////////////
//!
//! #[repr(C)]
//! #[derive(Debug, Clone, StableAbi)]
//! pub struct ConstChecker {
//! chars: RStr<'static>,
//! }
//!
//! impl Display for ConstChecker {
//! fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
//! writeln!(
//! f,
//! "ConstChecker: \
//! Checks that the associated constant for \
//! the other type is compatible with:\n{}\n.\
//! ",
//! self.chars
//! )
//! }
//! }
//!
//! impl ConstChecker {
//! fn check_compatible_inner(
//! &self,
//! other: &ConstChecker,
//! ) -> Result<(), UnequalConstError> {
//! if other.chars.starts_with(&*self.chars) {
//! Ok(())
//! } else {
//! Err(UnequalConstError {
//! expected: self.chars,
//! found: other.chars,
//! })
//! }
//! }
//! }
//! unsafe impl ExtraChecks for ConstChecker {
//! fn type_layout(&self) -> &'static TypeLayout {
//! <Self as StableAbi>::LAYOUT
//! }
//!
//! fn check_compatibility(
//! &self,
//! _layout_containing_self: &'static TypeLayout,
//! layout_containing_other: &'static TypeLayout,
//! checker: TypeCheckerMut<'_>,
//! ) -> RResult<(), ExtraChecksError> {
//! Self::downcast_with_layout(layout_containing_other, checker, |other, _| {
//! self.check_compatible_inner(other)
//! })
//! }
//!
//! fn nested_type_layouts(&self) -> RCowSlice<'_, &'static TypeLayout> {
//! RCow::from_slice(&[])
//! }
//!
//! fn combine(
//! &self,
//! other: ExtraChecksRef<'_>,
//! checker: TypeCheckerMut<'_>,
//! ) -> RResult<ROption<ExtraChecksBox>, ExtraChecksError> {
//! Self::downcast_with_object(other, checker, |other, _| {
//! let (min, max) = min_max_by(self, other, |x| x.chars.len());
//! min.check_compatible_inner(max)
//! .map(|_| RSome(ExtraChecksBox::from_value(max.clone(), TD_Opaque)))
//! })
//! }
//! }
//!
//! #[derive(Debug, Clone)]
//! pub struct UnequalConstError {
//! expected: RStr<'static>,
//! found: RStr<'static>,
//! }
//!
//! impl Display for UnequalConstError {
//! fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
//! writeln!(
//! f,
//! "Expected the `GetConstant::CHARS` associated constant to be compatible with:\
//! \n {}\
//! \nFound:\
//! \n {}\
//! ",
//! self.expected,
//! self.found,
//! )
//! }
//! }
//!
//! impl std::error::Error for UnequalConstError {}
//!
//! pub(crate) fn min_max_by<T, F, K>(l: T, r: T, mut f: F) -> (T, T)
//! where
//! F: FnMut(&T) -> K,
//! K: Ord,
//! {
//! if f(&l) < f(&r) {
//! (l, r)
//! } else {
//! (r, l)
//! }
//! }
//!
//!
//! ```
//!
//!
//! # Examples
//!
//! ### Alphabetic.
//!
//! This defines an ExtraChecks which checks that fields are alphabetically sorted
//!
//! ```
//! use abi_stable::{
//! abi_stability::{
//! check_layout_compatibility,
//! extra_checks::{
//! ExtraChecks, ExtraChecksError, ExtraChecksStaticRef,
//! ForExtraChecksImplementor, TypeCheckerMut,
//! },
//! },
//! sabi_extern_fn,
//! sabi_trait::prelude::TD_Opaque,
//! std_types::{RCow, RCowSlice, RDuration, ROption, RResult, RStr, RString},
//! type_layout::TypeLayout,
//! StableAbi,
//! };
//!
//! use std::fmt::{self, Display};
//!
//! fn main() {
//! let rect_layout = <Rectangle as StableAbi>::LAYOUT;
//! let person_layout = <Person as StableAbi>::LAYOUT;
//!
//! // This passes because the fields are in order
//! check_layout_compatibility(rect_layout, rect_layout)
//! .unwrap_or_else(|e| panic!("{}", e));
//!
//! // This errors because the struct's fields aren't in order
//! check_layout_compatibility(person_layout, person_layout).unwrap_err();
//! }
//!
//! #[repr(C)]
//! #[derive(StableAbi)]
//! #[sabi(extra_checks = InOrderChecker)]
//! struct Rectangle {
//! x: u32,
//! y: u32,
//! z: u32,
//! }
//!
//! #[repr(C)]
//! #[derive(StableAbi)]
//! #[sabi(extra_checks = InOrderChecker)]
//! struct Person {
//! name: RString,
//! surname: RString,
//! age: RDuration,
//! }
//!
//! /////////////////////////////////////////
//!
//! #[repr(C)]
//! #[derive(Debug, Clone, StableAbi)]
//! pub struct InOrderChecker;
//!
//! impl Display for InOrderChecker {
//! fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
//! f.write_str(
//! "InOrderChecker: Checks that field names are sorted alphabetically.",
//! )
//! }
//! }
//!
//! unsafe impl ExtraChecks for InOrderChecker {
//! fn type_layout(&self) -> &'static TypeLayout {
//! <Self as StableAbi>::LAYOUT
//! }
//!
//! fn check_compatibility(
//! &self,
//! layout_containing_self: &'static TypeLayout,
//! layout_containing_other: &'static TypeLayout,
//! checker: TypeCheckerMut<'_>,
//! ) -> RResult<(), ExtraChecksError> {
//! Self::downcast_with_layout(layout_containing_other, checker, |_, _| {
//! let fields = match layout_containing_self.get_fields() {
//! Some(fields) if !fields.is_empty() => fields,
//! _ => return Ok(()),
//! };
//!
//! let mut prev = fields.iter().next().unwrap();
//! for curr in fields {
//! if prev.name() > curr.name() {
//! return Err(OutOfOrderError {
//! previous_one: prev.name(),
//! first_one: curr.name(),
//! });
//! }
//! prev = curr;
//! }
//! Ok(())
//! })
//! }
//!
//! fn nested_type_layouts(&self) -> RCowSlice<'_, &'static TypeLayout> {
//! RCow::from_slice(&[])
//! }
//! }
//!
//! #[derive(Debug, Clone)]
//! pub struct OutOfOrderError {
//! previous_one: &'static str,
//!
//! /// The first field that is out of order.
//! first_one: &'static str,
//! }
//!
//! impl Display for OutOfOrderError {
//! fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
//! writeln!(
//! f,
//! "Expected fields to be alphabetically sorted.\n\
//! Found field '{}' before '{}'\
//! ",
//! self.previous_one, self.first_one,
//! )
//! }
//! }
//!
//! impl std::error::Error for OutOfOrderError {}
//!
//!
//! ```
//!
//! ### Associated Constant.
//!
//! This defines an ExtraChecks which checks that an associated constant is
//! the same for both types.
//!
//! ```
//! use abi_stable::{
//! abi_stability::{
//! check_layout_compatibility,
//! extra_checks::{
//! ExtraChecks, ExtraChecksError, ExtraChecksStaticRef,
//! ForExtraChecksImplementor, TypeCheckerMut,
//! },
//! },
//! marker_type::UnsafeIgnoredType,
//! sabi_extern_fn,
//! sabi_trait::prelude::TD_Opaque,
//! std_types::{RCow, RCowSlice, RDuration, RResult, RStr, RString},
//! type_layout::TypeLayout,
//! GetStaticEquivalent, StableAbi,
//! };
//!
//! use std::fmt::{self, Display};
//!
//! fn main() {
//! let const0 = <WithConstant<N0> as StableAbi>::LAYOUT;
//! let const_second_0 = <WithConstant<SecondN0> as StableAbi>::LAYOUT;
//! let const1 = <WithConstant<N1> as StableAbi>::LAYOUT;
//! let const2 = <WithConstant<N2> as StableAbi>::LAYOUT;
//!
//! check_layout_compatibility(const0, const0).unwrap();
//! check_layout_compatibility(const_second_0, const_second_0).unwrap();
//! check_layout_compatibility(const1, const1).unwrap();
//! check_layout_compatibility(const2, const2).unwrap();
//!
//! ////////////
//! // WithConstant<SecondN0> and WithConstant<N0> are compatible with each other
//! // because their `GetConstant::NUMBER` associated constant is the same value.
//! check_layout_compatibility(const0, const_second_0).unwrap();
//! check_layout_compatibility(const_second_0, const0).unwrap();
//!
//! ////////////
//! // None of the lines below are compatible because their
//! // `GetConstant::NUMBER` associated constant isn't the same value.
//! check_layout_compatibility(const0, const1).unwrap_err();
//! check_layout_compatibility(const0, const2).unwrap_err();
//!
//! check_layout_compatibility(const1, const0).unwrap_err();
//! check_layout_compatibility(const1, const2).unwrap_err();
//!
//! check_layout_compatibility(const2, const0).unwrap_err();
//! check_layout_compatibility(const2, const1).unwrap_err();
//! }
//!
//! #[repr(C)]
//! #[derive(StableAbi)]
//! #[sabi(
//! // Replaces the C:StableAbi constraint with `C:GetStaticEquivalent`
//! // (a supertrait of StableAbi).
//! not_stableabi(C),
//! bound(C:GetConstant),
//! extra_checks = Self::CHECKER,
//! )]
//! struct WithConstant<C> {
//! // UnsafeIgnoredType is equivalent to PhantomData,
//! // except that all `UnsafeIgnoredType` are considered the same type by `StableAbi`.
//! _marker: UnsafeIgnoredType<C>,
//! }
//!
//! impl<C> WithConstant<C> {
//! const NEW: Self = Self {
//! _marker: UnsafeIgnoredType::NEW,
//! };
//! }
//!
//! impl<C> WithConstant<C>
//! where
//! C: GetConstant,
//! {
//! const CHECKER: ConstChecker = ConstChecker { number: C::NUMBER };
//! }
//!
//! trait GetConstant {
//! const NUMBER: u64;
//! }
//!
//! #[derive(GetStaticEquivalent)]
//! struct N0;
//! impl GetConstant for N0 {
//! const NUMBER: u64 = 0;
//! }
//!
//! #[derive(GetStaticEquivalent)]
//! struct SecondN0;
//! impl GetConstant for SecondN0 {
//! const NUMBER: u64 = 0;
//! }
//!
//! #[derive(GetStaticEquivalent)]
//! struct N1;
//! impl GetConstant for N1 {
//! const NUMBER: u64 = 1;
//! }
//!
//! #[derive(GetStaticEquivalent)]
//! struct N2;
//! impl GetConstant for N2 {
//! const NUMBER: u64 = 2;
//! }
//!
//! /////////////////////////////////////////
//!
//! #[repr(C)]
//! #[derive(Debug, Clone, StableAbi)]
//! pub struct ConstChecker {
//! number: u64,
//! }
//!
//! impl Display for ConstChecker {
//! fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
//! writeln!(
//! f,
//! "ConstChecker: \
//! Checks that the associated constant for \
//! for the other type is {}.\
//! ",
//! self.number
//! )
//! }
//! }
//!
//! unsafe impl ExtraChecks for ConstChecker {
//! fn type_layout(&self) -> &'static TypeLayout {
//! <Self as StableAbi>::LAYOUT
//! }
//!
//! fn check_compatibility(
//! &self,
//! layout_containing_self: &'static TypeLayout,
//! layout_containing_other: &'static TypeLayout,
//! checker: TypeCheckerMut<'_>,
//! ) -> RResult<(), ExtraChecksError> {
//! Self::downcast_with_layout(layout_containing_other, checker, |other, _| {
//! if self.number == other.number {
//! Ok(())
//! } else {
//! Err(UnequalConstError {
//! expected: self.number,
//! found: other.number,
//! })
//! }
//! })
//! }
//!
//! fn nested_type_layouts(&self) -> RCowSlice<'_, &'static TypeLayout> {
//! RCow::from_slice(&[])
//! }
//! }
//!
//! #[derive(Debug, Clone)]
//! pub struct UnequalConstError {
//! expected: u64,
//! found: u64,
//! }
//!
//! impl Display for UnequalConstError {
//! fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
//! writeln!(
//! f,
//! "Expected the `GetConstant::NUMBER` associated constant to be:\
//! \n {}\
//! \nFound:\
//! \n {}\
//! ",
//! self.expected, self.found,
//! )
//! }
//! }
//!
//! impl std::error::Error for UnequalConstError {}
//!
//!
//! ```
//!
use crate::{
rtry, sabi_trait,
sabi_types::{RMut, RRef},
std_types::{RBox, RBoxError, RCowSlice, RNone, ROk, ROption, RResult},
traits::IntoReprC,
type_layout::TypeLayout,
StableAbi,
};
use std::{
error::Error as ErrorTrait,
fmt::{self, Display},
};
use core_extensions::SelfOps;
#[sabi_trait]
/// This checks that the layout of types coming from dynamic libraries
/// are compatible with those of the binary/dynlib that loads them.
///
/// # Safety
///
/// This trait must not be implemented outside of `abi_stable`.
///
#[sabi(no_trait_impl)]
// #[sabi(debug_print_trait)]
// #[sabi(debug_print)]
pub unsafe trait TypeChecker: 'static + Send + Sync {
/// Checks that `ìnterface` is compatible with `implementation.`
///
/// This is equivalent to `check_layout_compatibility`,
/// except that it can also be called re-entrantly
/// (while `check_layout_compatibility` cannot be called re-entrantly)
///
/// # Errors
///
/// When calling the implementation of this trait used in `check_layout_compatibility`,
/// the errors detected in this method are always propagated by the free function,
/// to prevent the propagation of errors call the `local_check_compatibility` method.
///
fn check_compatibility(
&mut self,
interface: &'static TypeLayout,
implementation: &'static TypeLayout,
) -> RResult<(), ExtraChecksError>;
/// Checks that `ìnterface` is compatible with `implementation.`
///
/// This is equivalent to the `check_compatibility` method,
/// except that it does not propagate errors automatically,
/// they must be returned as part of the error of the `ExtraChecks` that calls this.
#[sabi(last_prefix_field)]
fn local_check_compatibility(
&mut self,
interface: &'static TypeLayout,
implementation: &'static TypeLayout,
) -> RResult<(), ExtraChecksError>;
}
/// An ffi-safe equivalent of &'b mut dyn TypeChecker
pub type TypeCheckerMut<'b> = TypeChecker_TO<RMut<'b, ()>>;
#[sabi_trait]
/// Allows defining extra checks for a type.
///
/// Look at the
/// [module level documentation](./index.html)
/// for more details.
///
/// # Safety
///
/// The `type_layout` method must be defined as `<Self as ::abi_stable::StableAbi>::LAYOUT`,
/// or equivalent.
///
/// All of the methods must be deterministic,
/// always returning the same value with the same arguments.
///
#[sabi(no_trait_impl)]
// #[sabi(debug_print_trait)]
// #[sabi(debug_print)]
pub unsafe trait ExtraChecks: 'static + Debug + Display + Clone + Send + Sync {
/// Gets the type layout of `Self`(the type that implements ExtraChecks)
///
/// This is used to downcast the trait object in
/// `ForExtraChecksImplementor::downcast_*` methods,
/// by ensuring that its type layout is
/// compatible with that of another ExtraChecks trait object
///
/// It can't use `UTypeId`s to check compatibility of trait objects
/// from different dynamic libraries,
/// because `UTypeId`s from different dynamic libraries are incompatible.
fn type_layout(&self) -> &'static TypeLayout;
/// Checks that `self` is compatible another type which implements ExtraChecks.
///
/// Calling `check_layout_compatibility` from here will immediately return an error,
/// prefer doing `checker.check_compatibility(...)` instead.
///
/// # Parameters
///
/// `layout_containing_self`:
/// The TypeLayout that contains this `ExtraChecks` trait object in the extra_checks field.
///
/// `layout_containing_other`:
/// The TypeLayout that contains the `other` `ExtraChecks` trait object in the extra_checks field,
/// which `self` is compared to.
///
/// `checker`:
/// The type checker,which allows this function to check type layouts.
///
///
fn check_compatibility(
&self,
layout_containing_self: &'static TypeLayout,
layout_containing_other: &'static TypeLayout,
checker: TypeCheckerMut<'_>,
) -> RResult<(), ExtraChecksError>;
/// Returns the `TypeLayout`s owned or referenced by `self`.
///
/// This is necessary for the Debug implementation of `TypeLayout`.
fn nested_type_layouts(&self) -> RCowSlice<'_, &'static TypeLayout>;
/// Combines this ExtraChecks trait object with another one.
///
/// To guarantee that the `extra_checks`
/// associated with a type (inside `<TheType as StableAbi>::LAYOUT.extra_cheks` )
/// has a single representative value across all dynamic libraries,
/// you must override this method,
/// and return `ROk(RSome(_))` by combining `self` and `other` in some way.
///
///
/// # Parameters
///
/// `other`:
/// The other ExtraChecks trait object that this is combined with..
///
/// `checker`:
/// The trait object of the type checker,which allows this function to check type layouts.
///
///
/// # Return value
///
/// This returns:
///
/// - `ROk(RNone)`:
/// If `self` doesn't need to be unified across all dynamic libraries,
/// or the representative version doesn't need to be updated.
///
/// - `ROk(RSome(_))`:
/// If `self` needs to be unified across all dynamic libraries,
/// returning the combined `self` and `other`.
///
/// - `RErr(_)`: If there was a problem unifying `self` and `other`.
///
#[sabi(last_prefix_field)]
fn combine(
&self,
_other: ExtraChecksRef<'_>,
_checker: TypeCheckerMut<'_>,
) -> RResult<ROption<ExtraChecksBox>, ExtraChecksError> {
ROk(RNone)
}
}
/// The version of `ExtraChecks` that is stored in `TypeLayout`.
pub type StoredExtraChecks = ExtraChecks_CTO<'static>;
/// An ffi-safe equivalent of `&'static dyn ExtraChecks`.
pub type ExtraChecksStaticRef = ExtraChecks_TO<RRef<'static, ()>>;
/// An ffi-safe equivalent of `&'a dyn ExtraChecks`.
pub type ExtraChecksRef<'a> = ExtraChecks_TO<RRef<'a, ()>>;
/// An ffi-safe equivalent of `Box<dyn ExtraChecks>`.
pub type ExtraChecksBox = ExtraChecks_TO<RBox<()>>;
/// An extension trait for `ExtraChecks` implementors.
pub trait ForExtraChecksImplementor: StableAbi + ExtraChecks {
/// Accesses the `ExtraChecks` field in `layout_containing_other`, downcasted into `Self`.
///
/// If the closure returns an `ExtraChecksError`,it'll be returned unmodified and unwrapped.
///
/// # Returns
///
/// - ROk(_):
/// If `other` was downcasted to `Self`,and `f` did not return any errors.
///
/// - RErr(ExtraChecksError::NoneExtraChecks):
/// If`layout_containing_other` does not contain an ExtraChecks trait object.
///
/// - RErr(ExtraChecksError::TypeChecker):
/// If there is an error while type checking.
///
/// - RErr(ExtraChecksError::ExtraChecks(_)):
/// If there is an custom error within the function.
///
fn downcast_with_layout<F, R, E>(
layout_containing_other: &'static TypeLayout,
checker: TypeCheckerMut<'_>,
f: F,
) -> RResult<R, ExtraChecksError>
where
Self: 'static,
F: FnOnce(&Self, TypeCheckerMut<'_>) -> Result<R, E>,
E: Send + Sync + ErrorTrait + 'static,
{
let other = rtry!(layout_containing_other
.extra_checks()
.ok_or(ExtraChecksError::NoneExtraChecks));
Self::downcast_with_object(other, checker, f)
}
/// Allows one to access `other` downcast into `Self`.
///
/// If the closure returns an `ExtraChecksError`,it'll be returned unmodified and unwrapped.
///
/// # Returns
///
/// - ROk(_):
/// If `other` could be downcasted to `Self`,and `f` did not return any errors.
///
/// - RErr(ExtraChecksError::TypeChecker):
/// If there is an error while type checking.
///
/// - RErr(ExtraChecksError::ExtraChecks(_)):
/// If there is an custom error within the function.
fn downcast_with_object<F, R, E>(
other: ExtraChecksRef<'_>,
mut checker: TypeCheckerMut<'_>,
f: F,
) -> RResult<R, ExtraChecksError>
where
F: FnOnce(&Self, TypeCheckerMut<'_>) -> Result<R, E>,
E: Send + Sync + ErrorTrait + 'static,
{
// This checks that the layouts of `this` and `other` are compatible,
// so that calling the `unchecked_downcast_into` method is sound.
rtry!(checker.check_compatibility(<Self as StableAbi>::LAYOUT, other.type_layout()));
let other_ue = unsafe { other.obj.unchecked_downcast_into::<Self>() };
f(other_ue.get(), checker)
.map_err(|e| match RBoxError::new(e).downcast::<ExtraChecksError>() {
Ok(x) => x.piped(RBox::into_inner),
Err(e) => ExtraChecksError::from_extra_checks(e),
})
.into_c()
}
}
impl<This> ForExtraChecksImplementor for This where This: ?Sized + StableAbi + ExtraChecks {}
///////////////////////////////////////////////////////////////////////////////
/// The errors returned from `ExtraChecks` and `ForExtraChecksImplementor` methods.
#[repr(u8)]
#[derive(Debug, StableAbi)]
pub enum ExtraChecksError {
/// When a type checking error happens within `TypeChecker`.
TypeChecker,
/// Errors returned from `TypeChecker::local_check_compatibility`
TypeCheckerErrors(RBoxError),
/// When trying to get a ExtraChecks trait object from `TypeLayout.extra_checks==None` .
NoneExtraChecks,
/// A custom error returned by the ExtraChecker or
/// the closures in `ForExtraChecksImplementor::downcast_*`.
ExtraChecks(RBoxError),
}
impl ExtraChecksError {
/// Constructs a `ExtraChecksError::ExtraChecks` from an error.
pub fn from_extra_checks<E>(err: E) -> ExtraChecksError
where
E: Send + Sync + ErrorTrait + 'static,
{
let x = RBoxError::new(err);
ExtraChecksError::ExtraChecks(x)
}
}
impl Display for ExtraChecksError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ExtraChecksError::TypeChecker => Display::fmt("A type checker error happened.", f),
ExtraChecksError::TypeCheckerErrors(e) => {
writeln!(f, "Errors that happened during type checking:\n{}", e)
}
ExtraChecksError::NoneExtraChecks => {
Display::fmt("No `ExtraChecks` in the implementation.", f)
}
ExtraChecksError::ExtraChecks(e) => Display::fmt(e, f),
}
}
}
impl std::error::Error for ExtraChecksError {}
| true |
7fd2001e3f2bedd9dd66fefb4e6078c44aa29b47
|
Rust
|
marco-c/gecko-dev-wordified
|
/third_party/rust/rusqlite/src/backup.rs
|
UTF-8
| 13,214 | 2.546875 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"LicenseRef-scancode-public-domain"
] |
permissive
|
/
/
!
Online
SQLite
backup
API
.
/
/
!
/
/
!
To
create
a
[
Backup
]
you
must
have
two
distinct
[
Connection
]
s
-
one
/
/
!
for
the
source
(
which
can
be
used
while
the
backup
is
running
)
and
one
for
/
/
!
the
destination
(
which
cannot
)
.
A
[
Backup
]
handle
exposes
three
methods
:
/
/
!
[
step
]
(
Backup
:
:
step
)
will
attempt
to
back
up
a
specified
number
of
pages
/
/
!
[
progress
]
(
Backup
:
:
progress
)
gets
the
current
progress
of
the
backup
as
of
/
/
!
the
last
call
to
[
step
]
(
Backup
:
:
step
)
and
/
/
!
[
run_to_completion
]
(
Backup
:
:
run_to_completion
)
will
attempt
to
back
up
the
/
/
!
entire
source
database
allowing
you
to
specify
how
many
pages
are
backed
up
/
/
!
at
a
time
and
how
long
the
thread
should
sleep
between
chunks
of
pages
.
/
/
!
/
/
!
The
following
example
is
equivalent
to
"
Example
2
:
Online
Backup
of
a
/
/
!
Running
Database
"
from
[
SQLite
'
s
Online
Backup
API
/
/
!
documentation
]
(
https
:
/
/
www
.
sqlite
.
org
/
backup
.
html
)
.
/
/
!
/
/
!
rust
no_run
/
/
!
#
use
rusqlite
:
:
{
backup
Connection
Result
}
;
/
/
!
#
use
std
:
:
path
:
:
Path
;
/
/
!
#
use
std
:
:
time
;
/
/
!
/
/
!
fn
backup_db
<
P
:
AsRef
<
Path
>
>
(
/
/
!
src
:
&
Connection
/
/
!
dst
:
P
/
/
!
progress
:
fn
(
backup
:
:
Progress
)
/
/
!
)
-
>
Result
<
(
)
>
{
/
/
!
let
mut
dst
=
Connection
:
:
open
(
dst
)
?
;
/
/
!
let
backup
=
backup
:
:
Backup
:
:
new
(
src
&
mut
dst
)
?
;
/
/
!
backup
.
run_to_completion
(
5
time
:
:
Duration
:
:
from_millis
(
250
)
Some
(
progress
)
)
/
/
!
}
/
/
!
use
std
:
:
marker
:
:
PhantomData
;
use
std
:
:
path
:
:
Path
;
use
std
:
:
ptr
;
use
std
:
:
os
:
:
raw
:
:
c_int
;
use
std
:
:
thread
;
use
std
:
:
time
:
:
Duration
;
use
crate
:
:
ffi
;
use
crate
:
:
error
:
:
error_from_handle
;
use
crate
:
:
{
Connection
DatabaseName
Result
}
;
impl
Connection
{
/
/
/
Back
up
the
name
database
to
the
given
/
/
/
destination
path
.
/
/
/
/
/
/
If
progress
is
not
None
it
will
be
called
periodically
/
/
/
until
the
backup
completes
.
/
/
/
/
/
/
For
more
fine
-
grained
control
over
the
backup
process
(
e
.
g
.
/
/
/
to
sleep
periodically
during
the
backup
or
to
back
up
to
an
/
/
/
already
-
open
database
connection
)
see
the
backup
module
.
/
/
/
/
/
/
#
Failure
/
/
/
/
/
/
Will
return
Err
if
the
destination
path
cannot
be
opened
/
/
/
or
if
the
backup
fails
.
pub
fn
backup
<
P
:
AsRef
<
Path
>
>
(
&
self
name
:
DatabaseName
<
'
_
>
dst_path
:
P
progress
:
Option
<
fn
(
Progress
)
>
)
-
>
Result
<
(
)
>
{
use
self
:
:
StepResult
:
:
{
Busy
Done
Locked
More
}
;
let
mut
dst
=
Connection
:
:
open
(
dst_path
)
?
;
let
backup
=
Backup
:
:
new_with_names
(
self
name
&
mut
dst
DatabaseName
:
:
Main
)
?
;
let
mut
r
=
More
;
while
r
=
=
More
{
r
=
backup
.
step
(
100
)
?
;
if
let
Some
(
f
)
=
progress
{
f
(
backup
.
progress
(
)
)
;
}
}
match
r
{
Done
=
>
Ok
(
(
)
)
Busy
=
>
Err
(
unsafe
{
error_from_handle
(
ptr
:
:
null_mut
(
)
ffi
:
:
SQLITE_BUSY
)
}
)
Locked
=
>
Err
(
unsafe
{
error_from_handle
(
ptr
:
:
null_mut
(
)
ffi
:
:
SQLITE_LOCKED
)
}
)
More
=
>
unreachable
!
(
)
}
}
/
/
/
Restore
the
given
source
path
into
the
/
/
/
name
database
.
If
progress
is
not
None
it
will
be
/
/
/
called
periodically
until
the
restore
completes
.
/
/
/
/
/
/
For
more
fine
-
grained
control
over
the
restore
process
(
e
.
g
.
/
/
/
to
sleep
periodically
during
the
restore
or
to
restore
from
an
/
/
/
already
-
open
database
connection
)
see
the
backup
module
.
/
/
/
/
/
/
#
Failure
/
/
/
/
/
/
Will
return
Err
if
the
destination
path
cannot
be
opened
/
/
/
or
if
the
restore
fails
.
pub
fn
restore
<
P
:
AsRef
<
Path
>
F
:
Fn
(
Progress
)
>
(
&
mut
self
name
:
DatabaseName
<
'
_
>
src_path
:
P
progress
:
Option
<
F
>
)
-
>
Result
<
(
)
>
{
use
self
:
:
StepResult
:
:
{
Busy
Done
Locked
More
}
;
let
src
=
Connection
:
:
open
(
src_path
)
?
;
let
restore
=
Backup
:
:
new_with_names
(
&
src
DatabaseName
:
:
Main
self
name
)
?
;
let
mut
r
=
More
;
let
mut
busy_count
=
0_i32
;
'
restore_loop
:
while
r
=
=
More
|
|
r
=
=
Busy
{
r
=
restore
.
step
(
100
)
?
;
if
let
Some
(
ref
f
)
=
progress
{
f
(
restore
.
progress
(
)
)
;
}
if
r
=
=
Busy
{
busy_count
+
=
1
;
if
busy_count
>
=
3
{
break
'
restore_loop
;
}
thread
:
:
sleep
(
Duration
:
:
from_millis
(
100
)
)
;
}
}
match
r
{
Done
=
>
Ok
(
(
)
)
Busy
=
>
Err
(
unsafe
{
error_from_handle
(
ptr
:
:
null_mut
(
)
ffi
:
:
SQLITE_BUSY
)
}
)
Locked
=
>
Err
(
unsafe
{
error_from_handle
(
ptr
:
:
null_mut
(
)
ffi
:
:
SQLITE_LOCKED
)
}
)
More
=
>
unreachable
!
(
)
}
}
}
/
/
/
Possible
successful
results
of
calling
/
/
/
[
Backup
:
:
step
]
.
#
[
derive
(
Copy
Clone
Debug
PartialEq
Eq
)
]
#
[
non_exhaustive
]
pub
enum
StepResult
{
/
/
/
The
backup
is
complete
.
Done
/
/
/
The
step
was
successful
but
there
are
still
more
pages
that
need
to
be
/
/
/
backed
up
.
More
/
/
/
The
step
failed
because
appropriate
locks
could
not
be
acquired
.
This
is
/
/
/
not
a
fatal
error
-
the
step
can
be
retried
.
Busy
/
/
/
The
step
failed
because
the
source
connection
was
writing
to
the
/
/
/
database
.
This
is
not
a
fatal
error
-
the
step
can
be
retried
.
Locked
}
/
/
/
Struct
specifying
the
progress
of
a
backup
.
The
/
/
/
percentage
completion
can
be
calculated
as
(
pagecount
-
remaining
)
/
/
/
/
pagecount
.
The
progress
of
a
backup
is
as
of
the
last
call
to
/
/
/
[
step
]
(
Backup
:
:
step
)
-
if
the
source
database
is
modified
after
a
call
to
/
/
/
[
step
]
(
Backup
:
:
step
)
the
progress
value
will
become
outdated
and
/
/
/
potentially
incorrect
.
#
[
derive
(
Copy
Clone
Debug
)
]
pub
struct
Progress
{
/
/
/
Number
of
pages
in
the
source
database
that
still
need
to
be
backed
up
.
pub
remaining
:
c_int
/
/
/
Total
number
of
pages
in
the
source
database
.
pub
pagecount
:
c_int
}
/
/
/
A
handle
to
an
online
backup
.
pub
struct
Backup
<
'
a
'
b
>
{
phantom_from
:
PhantomData
<
&
'
a
Connection
>
to
:
&
'
b
Connection
b
:
*
mut
ffi
:
:
sqlite3_backup
}
impl
Backup
<
'
_
'
_
>
{
/
/
/
Attempt
to
create
a
new
handle
that
will
allow
backups
from
from
to
/
/
/
to
.
Note
that
to
is
a
&
mut
-
this
is
because
SQLite
forbids
any
/
/
/
API
calls
on
the
destination
of
a
backup
while
the
backup
is
taking
/
/
/
place
.
/
/
/
/
/
/
#
Failure
/
/
/
/
/
/
Will
return
Err
if
the
underlying
sqlite3_backup_init
call
returns
/
/
/
NULL
.
#
[
inline
]
pub
fn
new
<
'
a
'
b
>
(
from
:
&
'
a
Connection
to
:
&
'
b
mut
Connection
)
-
>
Result
<
Backup
<
'
a
'
b
>
>
{
Backup
:
:
new_with_names
(
from
DatabaseName
:
:
Main
to
DatabaseName
:
:
Main
)
}
/
/
/
Attempt
to
create
a
new
handle
that
will
allow
backups
from
the
/
/
/
from_name
database
of
from
to
the
to_name
database
of
to
.
Note
/
/
/
that
to
is
a
&
mut
-
this
is
because
SQLite
forbids
any
API
calls
on
/
/
/
the
destination
of
a
backup
while
the
backup
is
taking
place
.
/
/
/
/
/
/
#
Failure
/
/
/
/
/
/
Will
return
Err
if
the
underlying
sqlite3_backup_init
call
returns
/
/
/
NULL
.
pub
fn
new_with_names
<
'
a
'
b
>
(
from
:
&
'
a
Connection
from_name
:
DatabaseName
<
'
_
>
to
:
&
'
b
mut
Connection
to_name
:
DatabaseName
<
'
_
>
)
-
>
Result
<
Backup
<
'
a
'
b
>
>
{
let
to_name
=
to_name
.
as_cstring
(
)
?
;
let
from_name
=
from_name
.
as_cstring
(
)
?
;
let
to_db
=
to
.
db
.
borrow_mut
(
)
.
db
;
let
b
=
unsafe
{
let
b
=
ffi
:
:
sqlite3_backup_init
(
to_db
to_name
.
as_ptr
(
)
from
.
db
.
borrow_mut
(
)
.
db
from_name
.
as_ptr
(
)
)
;
if
b
.
is_null
(
)
{
return
Err
(
error_from_handle
(
to_db
ffi
:
:
sqlite3_errcode
(
to_db
)
)
)
;
}
b
}
;
Ok
(
Backup
{
phantom_from
:
PhantomData
to
b
}
)
}
/
/
/
Gets
the
progress
of
the
backup
as
of
the
last
call
to
/
/
/
[
step
]
(
Backup
:
:
step
)
.
#
[
inline
]
#
[
must_use
]
pub
fn
progress
(
&
self
)
-
>
Progress
{
unsafe
{
Progress
{
remaining
:
ffi
:
:
sqlite3_backup_remaining
(
self
.
b
)
pagecount
:
ffi
:
:
sqlite3_backup_pagecount
(
self
.
b
)
}
}
}
/
/
/
Attempts
to
back
up
the
given
number
of
pages
.
If
num_pages
is
/
/
/
negative
will
attempt
to
back
up
all
remaining
pages
.
This
will
hold
a
/
/
/
lock
on
the
source
database
for
the
duration
so
it
is
probably
not
/
/
/
what
you
want
for
databases
that
are
currently
active
(
see
/
/
/
[
run_to_completion
]
(
Backup
:
:
run_to_completion
)
for
a
better
/
/
/
alternative
)
.
/
/
/
/
/
/
#
Failure
/
/
/
/
/
/
Will
return
Err
if
the
underlying
sqlite3_backup_step
call
returns
/
/
/
an
error
code
other
than
DONE
OK
BUSY
or
LOCKED
.
BUSY
and
/
/
/
LOCKED
are
transient
errors
and
are
therefore
returned
as
possible
/
/
/
Ok
values
.
#
[
inline
]
pub
fn
step
(
&
self
num_pages
:
c_int
)
-
>
Result
<
StepResult
>
{
use
self
:
:
StepResult
:
:
{
Busy
Done
Locked
More
}
;
let
rc
=
unsafe
{
ffi
:
:
sqlite3_backup_step
(
self
.
b
num_pages
)
}
;
match
rc
{
ffi
:
:
SQLITE_DONE
=
>
Ok
(
Done
)
ffi
:
:
SQLITE_OK
=
>
Ok
(
More
)
ffi
:
:
SQLITE_BUSY
=
>
Ok
(
Busy
)
ffi
:
:
SQLITE_LOCKED
=
>
Ok
(
Locked
)
_
=
>
self
.
to
.
decode_result
(
rc
)
.
map
(
|
_
|
More
)
}
}
/
/
/
Attempts
to
run
the
entire
backup
.
Will
call
/
/
/
[
step
(
pages_per_step
)
]
(
Backup
:
:
step
)
as
many
times
as
necessary
/
/
/
sleeping
for
pause_between_pages
between
each
call
to
give
the
/
/
/
source
database
time
to
process
any
pending
queries
.
This
is
a
/
/
/
direct
implementation
of
"
Example
2
:
Online
Backup
of
a
Running
/
/
/
Database
"
from
[
SQLite
'
s
Online
Backup
API
documentation
]
(
https
:
/
/
www
.
sqlite
.
org
/
backup
.
html
)
.
/
/
/
/
/
/
If
progress
is
not
None
it
will
be
called
after
each
step
with
the
/
/
/
current
progress
of
the
backup
.
Note
that
is
possible
the
progress
may
/
/
/
not
change
if
the
step
returns
Busy
or
Locked
even
though
the
/
/
/
backup
is
still
running
.
/
/
/
/
/
/
#
Failure
/
/
/
/
/
/
Will
return
Err
if
any
of
the
calls
to
[
step
]
(
Backup
:
:
step
)
return
/
/
/
Err
.
pub
fn
run_to_completion
(
&
self
pages_per_step
:
c_int
pause_between_pages
:
Duration
progress
:
Option
<
fn
(
Progress
)
>
)
-
>
Result
<
(
)
>
{
use
self
:
:
StepResult
:
:
{
Busy
Done
Locked
More
}
;
assert
!
(
pages_per_step
>
0
"
pages_per_step
must
be
positive
"
)
;
loop
{
let
r
=
self
.
step
(
pages_per_step
)
?
;
if
let
Some
(
progress
)
=
progress
{
progress
(
self
.
progress
(
)
)
;
}
match
r
{
More
|
Busy
|
Locked
=
>
thread
:
:
sleep
(
pause_between_pages
)
Done
=
>
return
Ok
(
(
)
)
}
}
}
}
impl
Drop
for
Backup
<
'
_
'
_
>
{
#
[
inline
]
fn
drop
(
&
mut
self
)
{
unsafe
{
ffi
:
:
sqlite3_backup_finish
(
self
.
b
)
}
;
}
}
#
[
cfg
(
test
)
]
mod
test
{
use
super
:
:
Backup
;
use
crate
:
:
{
Connection
DatabaseName
Result
}
;
use
std
:
:
time
:
:
Duration
;
#
[
test
]
fn
test_backup
(
)
-
>
Result
<
(
)
>
{
let
src
=
Connection
:
:
open_in_memory
(
)
?
;
let
sql
=
"
BEGIN
;
CREATE
TABLE
foo
(
x
INTEGER
)
;
INSERT
INTO
foo
VALUES
(
42
)
;
END
;
"
;
src
.
execute_batch
(
sql
)
?
;
let
mut
dst
=
Connection
:
:
open_in_memory
(
)
?
;
{
let
backup
=
Backup
:
:
new
(
&
src
&
mut
dst
)
?
;
backup
.
step
(
-
1
)
?
;
}
let
the_answer
:
i64
=
dst
.
one_column
(
"
SELECT
x
FROM
foo
"
)
?
;
assert_eq
!
(
42
the_answer
)
;
src
.
execute_batch
(
"
INSERT
INTO
foo
VALUES
(
43
)
"
)
?
;
{
let
backup
=
Backup
:
:
new
(
&
src
&
mut
dst
)
?
;
backup
.
run_to_completion
(
5
Duration
:
:
from_millis
(
250
)
None
)
?
;
}
let
the_answer
:
i64
=
dst
.
one_column
(
"
SELECT
SUM
(
x
)
FROM
foo
"
)
?
;
assert_eq
!
(
42
+
43
the_answer
)
;
Ok
(
(
)
)
}
#
[
test
]
fn
test_backup_temp
(
)
-
>
Result
<
(
)
>
{
let
src
=
Connection
:
:
open_in_memory
(
)
?
;
let
sql
=
"
BEGIN
;
CREATE
TEMPORARY
TABLE
foo
(
x
INTEGER
)
;
INSERT
INTO
foo
VALUES
(
42
)
;
END
;
"
;
src
.
execute_batch
(
sql
)
?
;
let
mut
dst
=
Connection
:
:
open_in_memory
(
)
?
;
{
let
backup
=
Backup
:
:
new_with_names
(
&
src
DatabaseName
:
:
Temp
&
mut
dst
DatabaseName
:
:
Main
)
?
;
backup
.
step
(
-
1
)
?
;
}
let
the_answer
:
i64
=
dst
.
one_column
(
"
SELECT
x
FROM
foo
"
)
?
;
assert_eq
!
(
42
the_answer
)
;
src
.
execute_batch
(
"
INSERT
INTO
foo
VALUES
(
43
)
"
)
?
;
{
let
backup
=
Backup
:
:
new_with_names
(
&
src
DatabaseName
:
:
Temp
&
mut
dst
DatabaseName
:
:
Main
)
?
;
backup
.
run_to_completion
(
5
Duration
:
:
from_millis
(
250
)
None
)
?
;
}
let
the_answer
:
i64
=
dst
.
one_column
(
"
SELECT
SUM
(
x
)
FROM
foo
"
)
?
;
assert_eq
!
(
42
+
43
the_answer
)
;
Ok
(
(
)
)
}
#
[
test
]
fn
test_backup_attached
(
)
-
>
Result
<
(
)
>
{
let
src
=
Connection
:
:
open_in_memory
(
)
?
;
let
sql
=
"
ATTACH
DATABASE
'
:
memory
:
'
AS
my_attached
;
BEGIN
;
CREATE
TABLE
my_attached
.
foo
(
x
INTEGER
)
;
INSERT
INTO
my_attached
.
foo
VALUES
(
42
)
;
END
;
"
;
src
.
execute_batch
(
sql
)
?
;
let
mut
dst
=
Connection
:
:
open_in_memory
(
)
?
;
{
let
backup
=
Backup
:
:
new_with_names
(
&
src
DatabaseName
:
:
Attached
(
"
my_attached
"
)
&
mut
dst
DatabaseName
:
:
Main
)
?
;
backup
.
step
(
-
1
)
?
;
}
let
the_answer
:
i64
=
dst
.
one_column
(
"
SELECT
x
FROM
foo
"
)
?
;
assert_eq
!
(
42
the_answer
)
;
src
.
execute_batch
(
"
INSERT
INTO
foo
VALUES
(
43
)
"
)
?
;
{
let
backup
=
Backup
:
:
new_with_names
(
&
src
DatabaseName
:
:
Attached
(
"
my_attached
"
)
&
mut
dst
DatabaseName
:
:
Main
)
?
;
backup
.
run_to_completion
(
5
Duration
:
:
from_millis
(
250
)
None
)
?
;
}
let
the_answer
:
i64
=
dst
.
one_column
(
"
SELECT
SUM
(
x
)
FROM
foo
"
)
?
;
assert_eq
!
(
42
+
43
the_answer
)
;
Ok
(
(
)
)
}
}
| true |
b3939be07a256ce1b0474b92bfdd3d5681998402
|
Rust
|
facebook/hermes
|
/unsupported/juno/crates/juno_support/src/timer.rs
|
UTF-8
| 2,825 | 2.96875 | 3 |
[
"MIT"
] |
permissive
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use std::fmt::Display;
use std::fmt::Formatter;
use std::time::Duration;
use std::time::Instant;
type Mark = (&'static str, Duration);
/// A convenience utility to measure execution time of sections.
#[derive(Debug)]
pub struct Timer {
start_time: Instant,
last_update: Duration,
marks: Vec<Mark>,
}
impl Default for Timer {
fn default() -> Self {
Timer {
start_time: Instant::now(),
last_update: Default::default(),
marks: vec![],
}
}
}
impl Timer {
pub fn new() -> Self {
Default::default()
}
/// Record the duration of the just completed section.
pub fn mark(&mut self, name: &'static str) {
let new_upd = self.start_time.elapsed();
let duration = new_upd - self.last_update;
self.last_update = new_upd;
self.marks.push((name, duration));
}
}
impl Display for Timer {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
// In "alternate" mode, pretty print the result in aligned table form.
// In "normal mode", just dump the marks using debug formatting (JSON-like).
if f.alternate() {
let max_name_width = self
.marks
.iter()
.fold(0usize, |accum, m| accum.max(m.0.len()));
// Determine the number of decimal places and scale.
let mut dec = 1;
let mut scale = 0;
let mut dur = self.last_update.as_secs_f64();
for i in 0..=3 {
scale = i;
if dur >= 1.0 {
dec = f64::log10(dur).trunc() as usize + 1;
break;
} else if i < 3 {
dur *= 1e3;
}
}
const SCALES: [&str; 4] = ["s", "ms", "us", "ns"];
let mult = f64::powf(1e3, scale as f64);
let mut fmt = |m: &Mark| {
writeln!(
f,
"{0:1$}: {2:>3$.4$} {5}",
m.0,
max_name_width,
m.1.as_secs_f64() * mult,
dec + 4,
3,
SCALES[scale]
)
};
for m in &self.marks {
fmt(m)?;
}
fmt(&("Total", self.last_update))?;
} else {
let mut map = f.debug_map();
for m in &self.marks {
map.entry(&m.0, &m.1);
}
map.entry(&"Total", &self.last_update);
map.finish()?;
}
Ok(())
}
}
| true |
5333af0a7f730cc983522d3c3c0cf7861db7cab6
|
Rust
|
nvzqz/userutils
|
/src/bin/id.rs
|
UTF-8
| 6,512 | 2.75 | 3 |
[
"MIT"
] |
permissive
|
extern crate arg_parser;
extern crate extra;
extern crate redox_users;
use std::borrow::Borrow;
use std::hash::Hash;
use std::env;
use std::io::{self, Write, Stderr, StdoutLock};
use std::process::exit;
use extra::io::fail;
use extra::option::OptionalExt;
use arg_parser::{ArgParser, Param};
use redox_users::{get_egid, get_gid, get_euid, get_uid, AllUsers, AllGroups};
const HELP_INFO: &'static str = "Try ‘id --help’ for more information.\n";
const MAN_PAGE: &'static str = /* @MANSTART{id} */ r#"
NAME
id - display user identity
SYNOPSIS
id
id -g [-nr]
id -u [-nr]
id [ -h | --help ]
DESCRIPTION
The id utility displays the user and group names and numeric IDs, of
the calling process, to the standard output.
OPTIONS
-G
Display the different group IDs (effective and real) as white-space
separated numbers, in no particular order.
-g
Display the effective group ID as a number.
-n Display the name of the user or group ID for the -g and -u options
instead of the number.
-u
Display the effective user ID as a number.
-a
Ignored for compatibility with other id implementations.
-r
Display the real ID for the -g and -u options instead of the effective ID.
-h
--help
Display this help and exit.
EXIT STATUS
The whoami utility exits 0 on success, and >0 if an error occurs.
AUTHOR
Written by Jose Narvaez.
"#; /* @MANEND */
pub fn main() {
let stdout = io::stdout();
let mut stdout = stdout.lock();
let mut stderr = io::stderr();
let mut parser = ArgParser::new(1)
.add_flag(&["h", "help"])
.add_flag(&["a"])
.add_flag(&["G"])
.add_flag(&["g"])
.add_flag(&["u"])
.add_flag(&["n"])
.add_flag(&["r"]);
parser.parse(env::args());
// Shows the help
if parser.found("help") {
print_msg(MAN_PAGE, &mut stdout, &mut stderr);
exit(0);
}
// Unrecognized flags
if let Err(err) = parser.found_invalid() {
stderr.write_all(err.as_bytes()).try(&mut stderr);
print_msg(HELP_INFO, &mut stdout, &mut stderr);
exit(1);
}
let groups = AllGroups::new().unwrap_or_exit(1);
let users = AllUsers::new().unwrap_or_exit(1);
// Display the different group IDs (effective and real)
// as white-space separated numbers, in no particular order.
if parser.found(&'G') {
if any_of_found(&parser, &[&'g', &'u']) {
let msg = "id: -G option must be used without others\n";
print_msg(msg, &mut stdout, &mut stderr);
print_msg(HELP_INFO, &mut stdout, &mut stderr);
exit(1);
}
let egid = get_egid().unwrap_or_exit(1);
let gid = get_gid().unwrap_or_exit(1);
print_msg(&format!("{} {}\n", egid, gid), &mut stdout, &mut stderr);
exit(0);
}
// Check if people passed both -g -u which are mutually exclusive
if parser.found(&'u') && parser.found(&'g') {
let msg = "id: specify either -u or -g but not both\n";
print_msg(msg, &mut stdout, &mut stderr);
print_msg(HELP_INFO, &mut stdout, &mut stderr);
exit(1);
}
// Display effective/real process user ID UNIX user name
if parser.found(&'u') && parser.found(&'n') {
// Did they pass -r? F so, we show the real
let uid_result = if parser.found(&'r') {
get_uid()
} else {
get_euid()
};
let uid = uid_result.unwrap_or_exit(1);
let user = users.get_by_id(uid).unwrap_or_exit(1);
print_msg(&format!("{}\n", user.user), &mut stdout, &mut stderr);
exit(0);
}
// Display real user ID
if parser.found(&'u') && parser.found(&'r') {
let uid = get_uid().unwrap_or_exit(1);
print_msg(&format!("{}\n", uid), &mut stdout, &mut stderr);
exit(0);
}
// Display effective user ID
if parser.found(&'u') {
let euid = get_euid().unwrap_or_exit(1);
print_msg(&format!("{}\n", euid), &mut stdout, &mut stderr);
exit(0);
}
// Display effective/real process group ID UNIX group name
if parser.found(&'g') && parser.found(&'n') {
// Did they pass -r? If so we show the real one
let gid_result = if parser.found(&'r') {
get_gid()
} else {
get_egid()
};
let gid = gid_result.unwrap_or_exit(1);
let groups = AllGroups::new().unwrap_or_exit(1);
let group = groups.get_by_id(gid).unwrap_or_exit(1);
print_msg(&format!("{}\n", group.group), &mut stdout, &mut stderr);
exit(0);
}
// Display the real group ID
if parser.found(&'g') && parser.found(&'r') {
let gid = get_gid().unwrap_or_exit(1);
print_msg(&format!("{}\n", gid), &mut stdout, &mut stderr);
exit(0);
}
// Display effective group ID
if parser.found(&'g') {
let egid = get_egid().unwrap_or_exit(1);
print_msg(&format!("{}\n", egid), &mut stdout, &mut stderr);
exit(0);
}
// -n does not apply if there is no -u or -g
if parser.found(&'n') && none_of_found(&parser, &[&'u', &'g']) {
let msg = "id: the -n option must be used with either -u or -g\n";
fail(msg, &mut stderr);
}
// -r does not apply if there is no -u or -g
if parser.found(&'r') && none_of_found(&parser, &[&'u', &'g']) {
let msg = "id: the -r option must be used with either -u or -g\n";
fail(msg, &mut stderr);
}
// We get everything we can and show
let euid = get_euid().unwrap_or_exit(1);
let egid = get_egid().unwrap_or_exit(1);
let user = users.get_by_id(euid).unwrap_or_exit(1);
let group = groups.get_by_id(egid).unwrap_or_exit(1);
let msg = format!("uid={}({}) gid={}({})\n", euid, user.user, egid, group.group);
print_msg(&msg, &mut stdout, &mut stderr);
exit(0);
}
pub fn any_of_found<P: Hash + Eq + ?Sized>(parser: &ArgParser, flags: &[&P]) -> bool
where Param: Borrow<P>
{
for flag in flags {
if parser.found(*flag) { return true }
}
false
}
fn none_of_found<P: Hash + Eq + ?Sized>(parser: &ArgParser, flags: &[&P]) -> bool
where Param: Borrow<P>
{
!any_of_found(parser, flags)
}
fn print_msg(msg: &str, stdout: &mut StdoutLock, stderr: &mut Stderr) {
stdout.write_all(msg.as_bytes()).try(stderr);
stdout.flush().try(stderr);
}
| true |
fd9696e9c57f3d533f09efc4cdbe3e389c523875
|
Rust
|
CosmicSyntax/minmaxheap
|
/src/main.rs
|
UTF-8
| 308 | 2.78125 | 3 |
[] |
no_license
|
use minmaxheap::Heap;
fn main() {
let mut heap = Heap::new("max", 10).expect("Something did not work");
heap.add(20);
heap.add(10);
heap.add(5);
heap.add(100);
heap.add(2);
heap.add(40);
heap.add(40);
println!("{}", heap);
heap.invert();
println!("{}", heap);
}
| true |
181b0270d3e1b5997964b83a6df8abc5a7211865
|
Rust
|
dat2/rtags
|
/src/tag.rs
|
UTF-8
| 885 | 3.28125 | 3 |
[] |
no_license
|
use std::fmt;
#[derive(Debug, PartialEq, Eq)]
pub enum ExCmd {
GCmd(String),
QPattern(String),
LineNo(usize),
}
impl fmt::Display for ExCmd {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
ExCmd::GCmd(p) => write!(f, "/{}/;\"", p),
ExCmd::QPattern(p) => write!(f, "?{}?", p),
ExCmd::LineNo(line) => write!(f, "{}", line),
}
}
}
#[derive(Debug, PartialEq, Eq)]
pub struct Tag {
pub name: String,
pub filename: String,
pub excmd: ExCmd,
}
impl fmt::Display for Tag {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}\t{}\t{}", self.name, self.filename, self.excmd)
}
}
pub fn stringify_tags(tags: &[Tag]) -> String {
let mut result = String::new();
for tag in tags {
result.push_str(&format!("{}\n", tag));
}
result
}
| true |
88f1fad0c3c169549a586975b12d90f3a85a2ce1
|
Rust
|
usagi/usagi-rust-reference
|
/チュートリアルから得られること/.src/array_slice.rs
|
UTF-8
| 713 | 3.421875 | 3 |
[
"MIT"
] |
permissive
|
fn main()
{
let a = [ 1u, 2, 3, 4, 5 ];
// array は C++ でいう std::valarray のように
// slice によってスライス(slice)を生成できる。
// スライスの型は &[T] となる。
let first_index = 1u;
let last_index = 4u;
let s: &[uint] = a.slice( first_index, last_index );
print!( "s: " );
for v in s.iter() { print!( "{} ", v ); }
println!( "" );
let mut b = [ 2u, 4, 6, 8, 10 ];
// mut_slice を使うと mut なスライスを生成できる
// このとき、 let mut t とする必要はないようだ。
let t = b.mut_slice( first_index, last_index );
t[1] = 9;
print!( "t: " );
for v in t.iter() { print!( "{} ", v ); }
println!( "" );
}
| true |
362ee0844474fa40ac7e63aaf54d22561d9c7e86
|
Rust
|
hannobraun/cargo-task
|
/.cargo-task/setup.ct.rs
|
UTF-8
| 2,503 | 2.5625 | 3 |
[
"Apache-2.0"
] |
permissive
|
/*
# always run this setup task before any other tasks
@ct-bootstrap@ true @@
# error if cargo-task client binary is not new enough
@ct-min-version@ 0.0.7 @@
@ct-help@ Rebuild tasks if cargo_task_util.rs is updated. @@
@ct-cargo-deps@
num_cpus = "1"
@@
*/
use std::path::Path;
use cargo_task_util::*;
fn mtime<P: AsRef<Path>>(p: P) -> Result<std::time::SystemTime, ()> {
Ok(std::fs::metadata(p.as_ref())
.map_err(|_| ())?
.modified()
.map_err(|_| ())?)
}
fn main() {
let env = ct_env();
// first, set some job env vars : )
let cpu_count = format!("{}", num_cpus::get());
env.set_env("CARGO_BUILD_JOBS", &cpu_count);
env.set_env("NUM_JOBS", &cpu_count);
env.set_env("MY_TEST_KEY", "MY_TEST_VAL");
let root_time = std::fs::metadata("src/_cargo_task_util.rs")
.unwrap()
.modified()
.unwrap();
// In this particular crate - when testing ourselves -
// the task binaries can get cached with an old cargo_task_util.rs
// so if that file has been updated we need to touch the task file.
for task in std::fs::read_dir(".cargo-task").unwrap() {
if let Ok(task) = task {
if task.file_name() == "target"
|| task.file_name() == "cargo_task_util"
{
continue;
}
if task.file_type().unwrap().is_dir() {
let name = task.file_name();
let mut a_path = std::path::PathBuf::from("./.cargo-task/target/release");
a_path.push(&name);
let a_time = match mtime(&a_path) {
Err(_) => std::time::SystemTime::UNIX_EPOCH,
Ok(t) => t,
};
if a_time < root_time {
let mut c_path = task.path();
c_path.push("Cargo.toml");
ct_info!("touching {:?}", &c_path);
let mut u_path = c_path.clone();
u_path.pop();
u_path.push("Cargo.toml2");
// just opening the file does not update the
// modified time - using copy/rename for now
// if anyone has a better idea, open a PR!
ct_check_fatal!(std::fs::copy(&c_path, &u_path));
ct_check_fatal!(std::fs::remove_file(&c_path));
ct_check_fatal!(std::fs::rename(&u_path, &c_path));
}
}
}
}
}
| true |
b6356f9c1fb4d224fc849e35c3921567f6b92c18
|
Rust
|
dmvict/wTools
|
/rust/impl/meta/mod_interface/meta/use_tree.rs
|
UTF-8
| 1,514 | 2.828125 | 3 |
[
"MIT"
] |
permissive
|
/// Internal namespace.
pub( crate ) mod private
{
use proc_macro_tools::prelude::*;
#[ derive( Debug, PartialEq, Eq, Clone ) ]
pub struct UseTree
{
pub leading_colon : Option< syn::token::Colon2 >,
pub tree : syn::UseTree,
}
impl UseTree
{
/// Is adding prefix to the tree path required?
pub fn to_add_prefix( &self ) -> bool
{
use syn::UseTree::*;
if self.leading_colon.is_some()
{
return false;
}
match &self.tree
{
Path( e ) => e.ident != "super" && e.ident != "crate",
Rename( e ) => e.ident != "super" && e.ident != "crate",
_ => true,
}
}
}
impl syn::parse::Parse for UseTree
{
fn parse( input : ParseStream< '_ > ) -> Result< Self >
{
Ok( Self
{
leading_colon : input.parse()?,
tree : input.parse()?,
})
}
}
impl quote::ToTokens for UseTree
{
fn to_tokens( &self, tokens : &mut proc_macro2::TokenStream )
{
self.leading_colon.to_tokens( tokens );
self.tree.to_tokens( tokens );
}
}
}
/// Protected namespace of the module.
pub mod protected
{
pub use super::orphan::*;
}
pub use protected::*;
/// Parented namespace of the module.
pub mod orphan
{
pub use super::exposed::*;
}
/// Exposed namespace of the module.
pub mod exposed
{
pub use super::prelude::*;
pub use super::private::
{
UseTree,
};
}
/// Prelude to use essentials: `use my_module::prelude::*`.
pub mod prelude
{
}
| true |
2d1d2c7b834714b0c3e56e2e6767ab81c5a99f0a
|
Rust
|
LiveSplit/livesplit-core
|
/src/settings/image/shrinking.rs
|
UTF-8
| 4,090 | 2.875 | 3 |
[
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
use alloc::borrow::Cow;
use bytemuck_derive::{Pod, Zeroable};
use image::{
codecs::{bmp, farbfeld, hdr, ico, jpeg, pnm, tga, tiff, webp},
guess_format, load_from_memory_with_format, ImageDecoder, ImageEncoder, ImageFormat,
};
use std::io::Cursor;
use crate::util::byte_parsing::{big_endian::U32, strip_pod};
fn shrink_inner(data: &[u8], max_dim: u32) -> Option<Cow<'_, [u8]>> {
let format = guess_format(data).ok()?;
let (width, height) = match format {
ImageFormat::Png => {
// We encounter a lot of PNG images in splits files and decoding
// them with image's PNG decoder seems to decode way more than
// necessary. We really just need to find the width and height. The
// specification is here:
// https://www.w3.org/TR/2003/REC-PNG-20031110/
//
// And it says the following:
//
// "A valid PNG datastream shall begin with a PNG signature,
// immediately followed by an IHDR chunk".
//
// Each chunk is encoded as a length and type and then its chunk
// encoding. An IHDR chunk immediately starts with the width and
// height. This means we can model the beginning of a PNG file as
// follows:
#[derive(Copy, Clone, Pod, Zeroable)]
#[repr(C)]
struct BeginningOfPng {
// 5.2 PNG signature
png_signature: [u8; 8],
// 5.3 Chunk layout
chunk_len: [u8; 4],
// 11.2.2 IHDR Image header
chunk_type: [u8; 4],
width: U32,
height: U32,
}
// This improves parsing speed of entire splits files by up to 30%.
let beginning_of_png: &BeginningOfPng = strip_pod(&mut &*data)?;
(beginning_of_png.width.get(), beginning_of_png.height.get())
}
ImageFormat::Jpeg => jpeg::JpegDecoder::new(data).ok()?.dimensions(),
ImageFormat::WebP => webp::WebPDecoder::new(data).ok()?.dimensions(),
ImageFormat::Pnm => pnm::PnmDecoder::new(data).ok()?.dimensions(),
ImageFormat::Tiff => tiff::TiffDecoder::new(Cursor::new(data)).ok()?.dimensions(),
ImageFormat::Tga => tga::TgaDecoder::new(Cursor::new(data)).ok()?.dimensions(),
ImageFormat::Bmp => bmp::BmpDecoder::new(Cursor::new(data)).ok()?.dimensions(),
ImageFormat::Ico => ico::IcoDecoder::new(Cursor::new(data)).ok()?.dimensions(),
ImageFormat::Hdr => hdr::HdrAdapter::new(data).ok()?.dimensions(),
ImageFormat::Farbfeld => farbfeld::FarbfeldDecoder::new(data).ok()?.dimensions(),
// FIXME: For GIF we would need to properly shrink the whole animation.
// The image crate can't properly handle this at this point in time.
// Some properties are not translated over properly it seems. We could
// shrink GIFs that are a single frame, but we also can't tell how many
// frames there are.
// DDS isn't a format we really care for.
// AVIF uses C bindings, so it's not portable.
// The OpenEXR code in the image crate doesn't compile on Big Endian targets.
// And the image format is non-exhaustive.
_ => return Some(data.into()),
};
let is_too_large = width > max_dim || height > max_dim;
Some(if is_too_large || format == ImageFormat::Bmp {
let mut image = load_from_memory_with_format(data, format).ok()?;
if is_too_large {
image = image.thumbnail(max_dim, max_dim);
}
let mut data = Vec::new();
image::codecs::png::PngEncoder::new(&mut data)
.write_image(
image.as_bytes(),
image.width(),
image.height(),
image.color(),
)
.ok()?;
data.into()
} else {
data.into()
})
}
pub fn shrink(data: &[u8], max_dim: u32) -> Cow<'_, [u8]> {
shrink_inner(data, max_dim).unwrap_or_else(|| data.into())
}
| true |
4b5a04e616920696744a0a7f5891d4442e51267f
|
Rust
|
maxtnuk/gluesql
|
/test-suite/src/validate/unique.rs
|
UTF-8
| 2,590 | 2.703125 | 3 |
[
"Apache-2.0"
] |
permissive
|
use {
crate::*,
gluesql_core::{executor::ValidateError, prelude::Value},
};
test_case!(unique, async move {
run!(
r#"
CREATE TABLE TestA (
id INTEGER UNIQUE,
num INT
)"#
);
run!(
r#"
CREATE TABLE TestB (
id INTEGER UNIQUE,
num INT UNIQUE
)"#
);
run!(
r#"
CREATE TABLE TestC (
id INTEGER NULL UNIQUE,
num INT
)"#
);
run!("INSERT INTO TestA VALUES (1, 1)");
run!("INSERT INTO TestA VALUES (2, 1), (3, 1)");
run!("INSERT INTO TestB VALUES (1, 1)");
run!("INSERT INTO TestB VALUES (2, 2), (3, 3)");
run!("INSERT INTO TestC VALUES (NULL, 1)");
run!("INSERT INTO TestC VALUES (2, 2), (NULL, 3)");
run!("UPDATE TestC SET id = 1 WHERE num = 1");
run!("UPDATE TestC SET id = NULL WHERE num = 1");
let error_cases = [
(
"INSERT INTO TestA VALUES (2, 2)",
ValidateError::DuplicateEntryOnUniqueField(Value::I64(2), "id".to_owned()).into(),
),
(
"INSERT INTO TestA VALUES (4, 4), (4, 5)",
ValidateError::DuplicateEntryOnUniqueField(Value::I64(4), "id".to_owned()).into(),
),
(
"UPDATE TestA SET id = 2 WHERE id = 1",
ValidateError::DuplicateEntryOnUniqueField(Value::I64(2), "id".to_owned()).into(),
),
(
"INSERT INTO TestB VALUES (1, 3)",
ValidateError::DuplicateEntryOnUniqueField(Value::I64(1), "id".to_owned()).into(),
),
(
"INSERT INTO TestB VALUES (4, 2)",
ValidateError::DuplicateEntryOnUniqueField(Value::I64(2), "num".to_owned()).into(),
),
(
"INSERT INTO TestB VALUES (5, 5), (6, 5)",
ValidateError::DuplicateEntryOnUniqueField(Value::I64(5), "num".to_owned()).into(),
),
(
"UPDATE TestB SET num = 2 WHERE id = 1",
ValidateError::DuplicateEntryOnUniqueField(Value::I64(2), "num".to_owned()).into(),
),
(
"INSERT INTO TestC VALUES (2, 4)",
ValidateError::DuplicateEntryOnUniqueField(Value::I64(2), "id".to_owned()).into(),
),
(
"INSERT INTO TestC VALUES (NULL, 5), (3, 5), (3, 6)",
ValidateError::DuplicateEntryOnUniqueField(Value::I64(3), "id".to_owned()).into(),
),
(
"UPDATE TestC SET id = 1",
ValidateError::DuplicateEntryOnUniqueField(Value::I64(1), "id".to_owned()).into(),
),
];
for (sql, error) in error_cases {
test!(sql, Err(error));
}
});
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.