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 |
---|---|---|---|---|---|---|---|---|---|---|---|
ffa2c1ca503c7e38ebd59f7c66accdd64f9766f7
|
Rust
|
milesgranger/baggie
|
/src/baggie.rs
|
UTF-8
| 2,169 | 3.75 | 4 |
[
"MIT"
] |
permissive
|
use std::collections::{HashMap, hash_map::Keys};
use std::any::Any;
use std::hash::Hash;
use std::borrow::Borrow;
/// struct for collecting values of any type with a string key
#[derive(Default, Debug)]
pub struct Baggie<K>
where K: Eq + Hash
{
data: HashMap<K, Box<Any>>
}
impl<K> Baggie<K>
where K: Eq + Hash + Default
{
/// Initialize an empty `Baggie`
pub fn new() -> Self {
Default::default()
}
/// Insert a value into the baggie.
pub fn insert<T: 'static>(&mut self, key: K, value: T) {
let value = Box::new(value);
self.data.insert(key.into(), value);
}
/// Get a reference to something in the baggie
pub fn get<T: 'static, Q: ?Sized>(&self, key: &Q) -> Option<&T>
where K: Borrow<Q>,
Q: Eq + Hash
{
self.data.get(key)?.downcast_ref::<T>()
}
/// Get a mutable reference to something in the baggie
pub fn get_mut<T: 'static, Q: ?Sized>(&mut self, key: &Q) -> Option<&mut T>
where K: Borrow<Q>,
Q: Eq + Hash
{
self.data.get_mut(key)?.downcast_mut::<T>()
}
/// An iterator visiting all keys in arbitrary order.
pub fn keys(&self) -> Keys<'_, K, Box<dyn Any>> {
self.data.keys()
}
/// Number of elements in the map
pub fn len(&self) -> usize {
self.data.len()
}
/// Clear the map of all key value pairs; but maintains allocated memory
pub fn clear(&mut self) {
self.data.clear()
}
/// Determine if the Baggie is empty
pub fn is_empty(&self) -> bool {
self.data.is_empty()
}
/// Returns true if the map contains a value for the given key.
pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool
where K: Borrow<Q>,
Q: Eq + Hash
{
self.data.contains_key(key)
}
/// Remove a key-value pair from the Baggie by key.
/// if the key value pair existed, the raw [`Box<dyn Any>`] value will be returned
pub fn remove<Q: ?Sized>(&mut self, key: &Q) -> Option<Box<dyn Any>>
where K: Borrow<Q>,
Q: Eq + Hash
{
self.data.remove(key)
}
}
| true |
71eefc3037321f0fe354ba73dd0c145bc69bf4b6
|
Rust
|
neon64/proc-macro-testcase
|
/src/lib.rs
|
UTF-8
| 2,640 | 2.8125 | 3 |
[] |
no_license
|
#![feature(proc_macro)]
extern crate proc_macro;
extern crate proc_macro2;
extern crate syn;
#[macro_use]
extern crate quote;
use proc_macro::TokenStream;
use syn::fold::{Folder, noop_fold_expr};
use syn::{parse, Expr, ExprKind, TokenTree};
#[proc_macro]
pub fn fold_mac(input: TokenStream) -> TokenStream {
let mut item: Expr = parse(input).unwrap();
match item.node {
ExprKind::Mac(ref mut mac) => {
/// First of all, these next 20 lines seem extremely convoluted, but they are
/// the only way I could work out (from the `proc_macro`, `syn`, and `proc_macro2`
/// public apis) how to convert the `Vec<TokenTree>` of a `Mac` into an `Expr`
/// and back again.
let stream: proc_macro::TokenStream = {
let tts = &mac.tokens;
let tokens = quote! { #(#tts)* };
tokens.into()
};
let maybe_expr = parse::<Expr>(stream.clone());
let new_tokens_stream: proc_macro::TokenStream = if let Ok(expr) = maybe_expr {
println!("Successfully parsed macro contents as expr: {:?}", expr);
let new_expr = (BasicFolder).fold_expr(expr);
let new_tokens = quote! { #new_expr };
println!("Output: {}", new_tokens);
new_tokens.into()
} else {
stream
};
let new_token_stream: proc_macro2::TokenStream = new_tokens_stream.into();
let tts: Vec<TokenTree> = new_token_stream.into_iter().map(|tt| TokenTree(tt)).collect();
mac.tokens = tts;
},
_ => {
}
}
let tokens = quote! { #item };
tokens.into()
}
/// I found this macro really useful throughout my codebase.
/// I guess `proc_macro` and `syn` are relatively new, however are
/// there already idioms/timesavers that are emerging?
macro_rules! ast {
($($tt:tt)+) => ({
let tokens = quote! {
$($tt)+
};
::syn::parse(tokens.into()).expect("failed to parse again")
});
}
struct BasicFolder;
impl Folder for BasicFolder {
/// This implements the most basic transform to trigger a test compile error.
fn fold_expr(&mut self, expr: Expr) -> Expr {
let expr = noop_fold_expr(self, expr);
match expr.node {
ExprKind::Field(ref data) => {
let obj = &data.expr;
let field = data.field;
return ast! {
*(#obj.#field)
};
},
_ => {}
}
expr
}
}
| true |
09637526a7827642d4d481bd3697a125140d6a94
|
Rust
|
isgasho/pgpass
|
/src/bin/read-pgpass.rs
|
UTF-8
| 5,116 | 2.875 | 3 |
[] |
no_license
|
extern crate regex;
use std::error::Error;
use std::fs::File;
use std::path::Path;
use std::path::PathBuf;
use std::env;
use std::io::prelude::*;
use regex::Regex;
use std::fs;
#[derive(Debug, Clone)]
struct PgPassEntry {
username: String,
hostname: String,
port: String,
database: String,
password: String
}
impl PgPassEntry {
pub fn to_string(&self) -> String {
format!("postgresql://user@hostname:port/{}", self.database)
}
}
fn main() {
let pgpass_file = env::args().nth(1).unwrap();
//let user = env::args().nth(2).unwrap();
let connect_str = env::args().nth(2).unwrap();
println!("{} {}", pgpass_file, connect_str);
match env::args().last() {
Some(arg) => {
println!("arg {}", arg);
//let pgpass_entry_match = read_pgpass_file(&pgpass_file, &user, "dbcore.dev.porch.com", "5434", "application_data");
match get_path_to_pgpass() {
Ok(path_to_pgpass) => {
let pgpass_entry_match = read_pgpass_file(&path_to_pgpass.as_path(), &connect_str);
println!("pgpass_entry_match {:?}", pgpass_entry_match);
},
Err(e) => println!("uh oh {}", e)
}
},
_ => {
println!("missing required command line arguments.")
}
}
}
pub fn find_matching_pgpass_entry(connect_str: String, pgpass_path_override: String) {
match get_path_to_pgpass() {
Ok(path_to_pgpass) => {
let pgpass_entry_match = read_pgpass_file(&path_to_pgpass.as_path(), &connect_str);
println!("pgpass_entry_match {:?}", pgpass_entry_match);
},
Err(e) => println!("uh oh {}", e)
}
}
fn get_path_to_pgpass() -> Result<PathBuf, String> {
let home_dir = env::home_dir().expect("unable to exract home environment variable.");
println!("home_dir {:?}", home_dir);
let mut path_to_pgpass = PathBuf::from(home_dir);
path_to_pgpass.push(".pgpass");
println!("path_to_pg_pass {:?}", path_to_pgpass);
match fs::metadata(&path_to_pgpass) {
Ok(md) => {
println!("metdata {}", md.is_file());
//let path_to_pgpass_as_path = &path_to_pgpass.as_path();
Ok(path_to_pgpass)
},
Err(e) => {
println!("{}", e);
Err("unable to read .pgpass file".to_string())
}
}
}
//fn read_pgpass_file(path_to_pgpass: &str, username: &str, hostname: &str, port: &str, database: &str) -> Option<PgPassEntry> {
fn read_pgpass_file(path_to_pgpass: &Path, connection_string: &str) -> Option<PgPassEntry> {
let path = Path::new(path_to_pgpass);
let display = path.display();
println!("display {}", display);
// Open the path in read-only mode, returns `io::Result<File>`
let mut file = match File::open(&path) {
// The `description` method of `io::Error` returns a string that
// describes the error
Err(why) => panic!("couldn't open {}: {}, {}", display,
Error::description(&why), why),
Ok(file) => file,
};
let mut pgpass_entries: Vec<PgPassEntry> = Vec::new();
let mut reader = std::io::BufReader::new(&file);
let re = Regex::new(r":").unwrap();
for line in reader.lines() {
println!("line {:?}", line);
match line {
Ok(ref l) => {
let mut parts = re.split(l);
let host = parts.next().unwrap();
println!("parts[0] {:?}", host);
let port = parts.next().unwrap();
println!("parts[1] {:?}", port);
let database = parts.next().unwrap();
println!("parts[2] {:?}", database);
let username = parts.next().unwrap();
println!("parts[3] {:?}", username);
let password = parts.next().unwrap();
println!("parts[4] {:?}", password);
let mut parts_vec = re.split(l).collect::<Vec<&str>>();
println!("parts_vec {:?}", parts_vec);
pgpass_entries.push(PgPassEntry{
hostname: String::from(host),
port: String::from(port),
username: String::from(username),
database: String::from(database),
password: String::from(password)});
},
Err(e) => println!("no matching line {}", e)
}
}
//println!("pgpass_entries {:?}", pgpass_entries);
// pgpass_entries.into_iter().find(|x| x.hostname == hostname
// && x.database == database
// && x.port == port
// && x.username == username)
pgpass_entries.into_iter().find(|x|
format!("postgresql://{}@{}:{}/{}", x.username, x.hostname, x.port, x.database) == connection_string)
}
| true |
1d3d408846d682acec64fc8bd0924e0caac163cd
|
Rust
|
Ainevsia/Leetcode-Rust
|
/198. House Robber/src/main.rs
|
UTF-8
| 732 | 3.46875 | 3 |
[
"BSD-2-Clause"
] |
permissive
|
fn main() {
assert_eq!(Solution::rob(vec![1,2,3,1]), 4);
}
struct Solution {}
impl Solution {
// 1 dp
pub fn rob(nums: Vec<i32>) -> i32 {
if nums.len() == 0 { return 0 }
if nums.len() <= 1 { return nums[0] }
let mut dp = vec![0; nums.len()];
dp[0] = nums[0];
dp[1] = std::cmp::max(nums[0], nums[1]);
for i in 2..nums.len() {
dp[i] = std::cmp::max(dp[i-1], dp[i-2] + nums[i]);
}
dp[nums.len() - 1]
}
}
#[cfg(test)]
mod test {
use crate::*;
#[test]
fn basic() {
assert_eq!(Solution::rob(vec![1,2,3,1]), 4);
assert_eq!(Solution::rob(vec![2,7,9,3,1]), 12);
assert_eq!(Solution::rob(vec![4]), 4);
}
}
| true |
f0c24cec1080be4c18d221a01f8f29bb560259d7
|
Rust
|
langzime/sunflower
|
/src/connection.rs
|
UTF-8
| 3,726 | 2.53125 | 3 |
[] |
no_license
|
use std::thread;
use std::result::Result;
use std::net::ToSocketAddrs;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::rc::Rc;
use std::io::{self, Write};
use std::io::ErrorKind::WouldBlock;
use std::error::Error;
use std::io::Read;
use std::fmt::{self, Formatter};
use std::convert::From;
use std::net::Shutdown;
use mio::net::{TcpListener, TcpStream};
use mio::deprecated::TryRead;
use mio::channel::{self, Receiver, Sender};
use mio::{Token, Ready, PollOpt, Poll, Events, Event, Evented};
use util::threadpool::Pool;
use stream_data::StreamData;
use server::Handle;
pub enum ConnEvent {
Write(Token),
Read(Token),
}
pub struct Connection {
pub tcp_stream: TcpStream,
pub token: Token,
pub stream_data: Arc<Mutex<StreamData>>,
pub closing: bool,
tx: Sender<ConnEvent>,
thread_pool: Rc<Pool>,
handle: Arc<Handle>,
}
impl Connection {
pub fn new(token: Token, tcp_stream: TcpStream, tx: Sender<ConnEvent>, thread_pool: Rc<Pool>, handle: Arc<Handle>,) -> Connection {
Connection {
tcp_stream: tcp_stream,
token: token,
stream_data: Arc::new(Mutex::new(StreamData::new(Vec::with_capacity(1024), Vec::with_capacity(1024)))),
closing: false,
tx: tx,
thread_pool: thread_pool,
handle: handle,
}
}
pub fn reader(&mut self) {
let mut stream_data = self.stream_data.lock().unwrap();
loop {
let mut buf = [0; 1024];
match self.tcp_stream.read(&mut buf) {
Ok(size) => {
if size == 0 {
self.closing = true;
return;
} else {
stream_data.reader.extend_from_slice(&buf[0..size]);
if size < 1024 {
break;
}
}
}
Err(err) => {
//todo 会有这个错吗
if let WouldBlock = err.kind() {
break;
} else {
self.closing = true;
return;
}
}
}
}
stream_data.remote_addr = self.tcp_stream.peer_addr().unwrap();
let tx = self.tx.clone();
let token = self.token.clone();
let handle = self.handle.clone();
let stream_data = self.stream_data.clone();
self.thread_pool.execute(move || {
handle(stream_data);
tx.send(ConnEvent::Write(token)).is_ok();
});
}
pub fn writer(&mut self) {
let ref mut writer = self.stream_data.lock().unwrap().writer;
match self.tcp_stream.write(writer) {
Ok(size) => { ;
if size == 0 {
self.closing = true;
return;
}
writer.clear();
},
Err(_) => {
self.closing = true;
return;
}
}
self.tx.send(ConnEvent::Read(self.token)).is_ok();
}
}
impl Evented for Connection {
fn register(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt)
-> io::Result<()>
{
self.tcp_stream.register(poll, token, interest, opts)
}
fn reregister(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt)
-> io::Result<()>
{
self.tcp_stream.reregister(poll, token, interest, opts)
}
fn deregister(&self, poll: &Poll) -> io::Result<()> {
self.tcp_stream.deregister(poll)
}
}
| true |
ac4ee2734228c7239b04438cc0c3746250907353
|
Rust
|
sensecollective/valora
|
/src/geom/ellipse.rs
|
UTF-8
| 1,968 | 3.390625 | 3 |
[
"MIT"
] |
permissive
|
use geom::Point;
use lyon::math::Radians;
use properties::{Centered, Path};
use transforms::{Place, Scale, Translate};
#[derive(Debug, Clone)]
pub struct Ellipse {
pub center: Point,
pub width: f32,
pub height: Option<f32>,
pub rotation: Radians<f32>,
pub tolerance: Option<f32>,
}
impl Ellipse {
pub fn circle(center: Point, radius: f32) -> Self {
Ellipse {
center,
width: radius,
height: None,
rotation: Radians::new(0.0),
tolerance: None,
}
}
pub fn circumpoint(&self, angle: f32) -> Point {
Point {
x: self.center.x + angle.cos() * self.width,
y: self.center.y + angle.sin() * self.height.unwrap_or(self.width),
}
}
pub fn circumpoints(&self, resolution: usize, phase: f32) -> Vec<Point> {
use std::f32;
let interval = (f32::consts::PI * 2.0) / (resolution as f32);
(0..resolution)
.into_iter()
.map(|i| (i as f32) * interval + phase)
.map(|a| self.circumpoint(a))
.collect()
}
pub fn path(self, phase: f32) -> EllipsePath { EllipsePath { ellipse: self, phase } }
}
pub struct EllipsePath {
ellipse: Ellipse,
phase: f32,
}
impl Path for EllipsePath {
fn path(&self, completion: f32) -> Point {
use std::f32;
let angle = completion * (f32::consts::PI * 2.0);
self.ellipse.circumpoint(angle + self.phase)
}
}
impl Scale for Ellipse {
fn scale(self, scale: f32) -> Self {
Self { width: self.width * scale, height: self.height.map(|h| h * scale), ..self }
}
}
impl Centered for Ellipse {
fn centroid(&self) -> Point { self.center }
}
impl Place for Ellipse {
fn place(self, dest: Point) -> Self { Self { center: dest, ..self } }
}
impl Translate for Ellipse {
fn translate(self, delta: Point) -> Self { Self { center: self.center + delta, ..self } }
}
| true |
48938233a025a3bcb5580f6133e3fb2074917da6
|
Rust
|
ivanceras/memenhancer
|
/src/lib.rs
|
UTF-8
| 18,705 | 3 | 3 |
[] |
no_license
|
#![deny(warnings)]
extern crate unicode_width;
extern crate svg;
use unicode_width::UnicodeWidthStr;
use unicode_width::UnicodeWidthChar;
use svg::node::element::Circle as SvgCircle;
use svg::node::element::Text as SvgText;
use svg::Node;
use svg::node::element::SVG;
use svg::node::element::Style;
use svg::node::Text as TextNode;
struct Settings {
text_width: f32,
text_height: f32,
}
impl Settings{
fn offset(&self)->(f32, f32){
//(self.text_width * 1.0, self.text_height * 2.0)
(0.0, 0.0)
}
}
impl Default for Settings {
fn default() -> Settings {
Settings {
text_width: 8.0,
text_height: 16.0,
}
}
}
enum Anchor{
Start,
Middle,
End
}
#[derive(Debug)]
struct Body{
memes: Vec<Meme>,
rest_str: Vec<(usize, String)>
}
impl Body {
fn has_memes(&self) -> bool{
!self.memes.is_empty()
}
fn get_svg_elements(&self, y: usize, settings: &Settings) -> Vec<Box<Node>>{
let mut svg:Vec<Box<Node>> = vec![];
for meme in &self.memes{
svg.extend(meme.get_svg_elements(y, settings));
}
svg
}
// build the rest text in 1 string
fn unify_rest_text(&self) -> String{
let mut unify = String::new();
for &(sx, ref word) in &self.rest_str{
let lacks = sx - unify.width();
if lacks > 0{
for _ in 0..lacks{
unify.push(' ')
}
}
unify.push_str(word);
}
unify
}
}
/// The whole meme body
///
#[derive(Clone,Debug)]
struct Meme{
/// location to the left until a space is encountered
start_position: usize,
head: Head,
/// location to the right until a space is encoutered
end_position: usize,
/// string at the left
left_side: String,
/// string at the right
right_side: String
}
impl Meme{
fn get_svg_elements(&self, y: usize, settings: &Settings) -> Vec<Box<Node>>{
let mut elements:Vec<Box<Node>> = vec![];
let left_text = to_svg_text(&self.left_side, self.head.startx, y, settings, Anchor::End);
elements.push(Box::new(left_text));
elements.extend(self.head.get_svg_elements(y, settings));
let right_text = to_svg_text(&self.right_side, self.head.endx, y, settings, Anchor::Start);
elements.push(Box::new(right_text));
elements
}
}
fn to_svg_text(s: &str, x: usize, y: usize, settings: &Settings, anchor: Anchor) -> SvgText {
let px = x as f32 * settings.text_width;
let py = y as f32 * settings.text_height;
to_svg_text_pixel(s, px, py, settings, anchor)
}
fn to_svg_text_pixel(s: &str, x: f32, y: f32, settings: &Settings, anchor: Anchor) -> SvgText {
to_svg_text_pixel_escaped(&escape_str(s), x, y, settings, anchor)
}
fn to_svg_text_pixel_escaped(s: &str, x: f32, y: f32, settings: &Settings, anchor: Anchor) -> SvgText {
let (offsetx, offsety) = settings.offset();
let sx = x + offsetx;
let sy = y + settings.text_height * 3.0 / 4.0 + offsety;
let mut svg_text = SvgText::new()
.set("x", sx)
.set("y", sy);
match anchor{
Anchor::Start => {
svg_text.assign("text-anchor", "start");
}
Anchor::Middle => {
svg_text.assign("text-anchor", "middle");
}
Anchor::End => {
svg_text.assign("text-anchor", "end");
}
};
let text_node = TextNode::new(s);
svg_text.append(text_node);
svg_text
}
/// The head of the meme
/// the face is the string in between
/// used in detecting if it's a valid meme or not
#[derive(Clone,Debug)]
struct Head{
// character position
start_position: usize,
// left x location x1
startx: usize,
face: String,
// right x location x2
endx: usize,
// end position
end_position: usize
}
impl Head{
fn distance(&self) -> usize {
self.endx - self.startx
}
fn get_svg_elements(&self, y: usize, settings:&Settings) -> Vec<Box<Node>> {
let mut elements: Vec<Box<Node>> = vec![];
elements.push(Box::new(self.get_circle(y, settings)));
elements.push(Box::new(self.get_face_text(y, settings)));
elements
}
fn get_face_text(&self, y:usize, settings: &Settings) -> SvgText{
let c = self.calc_circle(y, settings);
let sy = y as f32 * settings.text_height;
let face = format!("<tspan class='head'>(</tspan>{}<tspan class='head'>)</tspan>", escape_str(&self.face));
to_svg_text_pixel_escaped(&face, c.cx, sy, settings, Anchor::Middle)
}
fn calc_circle(&self, y:usize, settings: &Settings) -> Circle {
let text_width = settings.text_width;
let text_height = settings.text_height;
let radius = self.distance() as f32 / 2.0;
let center = self. startx as f32 + radius;
let cx = center * text_width;
let cy = y as f32 * text_height + text_height / 2.0;
let cr = radius * text_width;
Circle{
cx: cx,
cy: cy,
r: cr
}
}
fn get_circle(&self, y: usize, settings: &Settings)-> SvgCircle{
let c = self.calc_circle(y, settings);
let (offsetx, offsety) = settings.offset();
SvgCircle::new()
.set("cx",c.cx + offsetx)
.set("cy", c.cy + offsety)
.set("class", "donger")
.set("r", c.r)
}
}
#[derive(Debug)]
struct Circle{
cx: f32,
cy: f32,
r: f32,
}
/// detect whether the series of string could be a meme
/// has at least 1 full width character (width = 2)
/// has at least 1 zero sized width character (width = 0)
/// has at least 1 character that has more than 1 byte in size
/// unicode value is way up high
fn is_meme(ch: &str) -> bool{
let total_bytes = ch.len();
let total_width = ch.width();
let mut gte_bytes2 = 0;
let mut gte_width2 = 0;
let mut zero_width = 0;
let mut gte_unicode_1k = 0;
for c in ch.chars(){
if c as u32 >= 1000{
gte_unicode_1k += 1;
}
if c.len_utf8() >= 2{
gte_bytes2 += 1;
}
if let Some(uw) = c.width(){
if uw >= 2 {
gte_width2 += 1;
}
if uw == 0 {
zero_width += 1;
}
}
}
/*
println!("total_bytes: {}", total_bytes);
println!("gte_bytes2: {}", gte_bytes2);
println!("gte_width2: {}", gte_width2);
println!("zero_width: {}", zero_width);
println!("gte_unicode_1k {}", gte_unicode_1k);
println!("total_width: {}", total_width);
println!("");
*/
total_width <= 10 && // must be at most 10 character face
(gte_bytes2 > 0 || gte_width2 > 0
|| zero_width > 0 || gte_unicode_1k > 0
|| total_bytes > total_width
|| !is_expression(ch)
)
}
fn calc_dimension(s: &str) -> (usize, usize) {
let mut longest = 0;
for line in s.lines(){
let line_width = line.width();
if line_width > longest{
longest = line_width
}
}
let line_count = s.lines().count();
(longest, line_count)
}
/// return an SVG document base from the text infor string
pub fn to_svg(s: &str, text_width: f32, text_height: f32) -> SVG {
let settings = &Settings{
text_width: text_width,
text_height: text_height,
};
let mut svg = SVG::new()
.set("font-size", 14)
.set("font-family", "arial");
svg.append(get_styles());
let nodes = to_svg_lines(s,settings);
for elm in nodes{
let text_node = TextNode::new(elm.to_string());
svg.append(text_node);
}
let (offsetx, offsety) = settings.offset();
let (wide, high) = calc_dimension(s);
let width = wide as f32 * text_width + offsetx;
let height = (high + 2 ) as f32 * text_height + offsety;
svg.assign("width", width);
svg.assign("height", height);
svg
}
fn get_styles() -> Style {
let style = r#"
line, path {
stroke: black;
stroke-width: 2;
stroke-opacity: 1;
fill-opacity: 1;
stroke-linecap: round;
stroke-linejoin: miter;
}
circle {
stroke: black;
stroke-width: 2;
stroke-opacity: 1;
fill-opacity: 1;
stroke-linecap: round;
stroke-linejoin: miter;
fill:white;
}
circle.donger{
stroke-width: 1;
fill: white;
}
tspan.head{
fill: none;
stroke: none;
}
"#;
Style::new(style)
}
/// process and parses each line
fn to_svg_lines(s: &str, settings: &Settings) -> Vec<Box<Node>> {
let mut elements = vec![];
let mut y = 0;
for line in s.lines(){
let line_elm = get_svg_elements(y, line, settings);
elements.extend(line_elm);
y += 1;
}
elements
}
/// process only 1 line
fn get_svg_elements(y: usize, s: &str, settings: &Settings) -> Vec<Box<Node>> {
let body = parse_memes(s);
body.get_svg_elements(y, &settings)
}
/// return the SVG nodes per line and all the assembled rest of the string that is not a part of the memes
pub fn get_meme_svg(input: &str, text_width: f32, text_height: f32) -> (Vec<Box<Node>>, String, Style) {
let settings = &Settings{
text_width: text_width,
text_height: text_height,
};
let mut svg_elements:Vec<Box<Node + 'static>> = vec![];
let mut relines = String::new();
let mut y = 0;
for line in input.lines(){
match line_to_svg_with_excess_str(y, line, settings){
Some((svg_elm, rest_text)) => {
relines.push_str(&rest_text);
relines.push('\n');
svg_elements.extend(svg_elm);
},
None => {
relines.push_str(line);
relines.push('\n');
}
}
y += 1;
}
(svg_elements, relines, get_styles())
}
/// parse the memes and return the svg together with the unmatched strings
fn line_to_svg_with_excess_str(y: usize, s: &str, settings:&Settings) -> Option<(Vec<Box<Node>>, String)>{
let body = parse_memes(s);
if body.has_memes(){
let nodes = body.get_svg_elements(y, settings);
Some((nodes, body.unify_rest_text()))
}else{
None
}
}
#[test]
fn test_1line(){
let meme = "";
let nodes = get_svg_elements(0, meme, &Settings::default());
assert_eq!(nodes.len(), 0);
}
/// TODO: include parsing the rest of the unused text
fn parse_memes(s: &str) -> Body{
let mut memes = vec![];
let mut paren_opened = false;
let mut meme_face = String::new();
let mut index = 0;
let mut total_width = 0;
let mut face_markers:Vec<Head> = vec![];
let mut startx = 0;
let mut start_position = 0;
let mut meme_start = 0;
let mut meme_body = String::new();
let mut meme_left_side = String::new();
let mut meme_right_side = String::new();
let mut meme_head = None;
let total_chars = s.chars().count();
let mut rest_text:Vec<(usize, String)> = vec![];
for ch in s.chars(){
let last_char = index == total_chars - 1;
if meme_head.is_some(){
meme_right_side.push(ch);
}
if paren_opened && ch == ')'{ //if paren_opened and encountered a closing
paren_opened = false;
if is_meme(&meme_face){
let head = Head{
start_position: start_position,
startx: startx,
face: meme_face.clone(),
end_position: index,
endx: total_width,
};
meme_head = Some(head.clone());
face_markers.push(head);
meme_face.clear();
}
}
if paren_opened{
meme_face.push(ch);
}
if ch == '('{
paren_opened = true;
startx = total_width;
start_position = index;
meme_left_side = meme_body.clone();
meme_face.clear();
}
if meme_head.is_none() && (ch == ' ' || last_char){
meme_start = index + 1;
if !paren_opened{
let mut rest_word = meme_body.clone();
let rest_start = total_width - rest_word.width();
if last_char{
rest_word.push(ch);
rest_word.push_str(&meme_face);//the head is unmatched
}
rest_text.push((rest_start, rest_word));
}
meme_body.clear();
}
if meme_head.is_some() && (ch == ' ' || last_char){
let meme = Meme{
start_position: meme_start,
head: meme_head.clone().unwrap(),
end_position: index,
left_side: meme_left_side.clone(),
right_side: meme_right_side.clone(),
};
memes.push(meme);
meme_right_side.clear();
meme_left_side.clear();
meme_body.clear();
meme_head = None;
}
meme_body.push(ch);
if let Some(uw) = ch.width(){
total_width += uw;
}
index += 1;
}
Body{
memes: memes,
rest_str: regroup_rest_text(&rest_text)
}
}
fn regroup_rest_text(rest_text: &Vec<(usize, String)>)->Vec<(usize, String)>{
let mut new_group = vec![];
//println!("regrouping text..");
for &(start,ref rest) in rest_text{
if new_group.is_empty(){
new_group.push((start, rest.clone()));
}else{
if let Some((lastx, last_rest)) = new_group.pop(){
if lastx + last_rest.width() == start{
let mut merged = String::new();
merged.push_str(&last_rest);
merged.push_str(rest);
new_group.push((lastx, merged));
}else{
new_group.push((lastx, last_rest));
new_group.push((start, rest.clone()));
}
}
}
}
//println!("new_group: {:#?}", new_group);
new_group
}
#[test]
fn test_meme() {
assert!(is_meme(" ͡° ͜ʖ ͡°"));
assert!(is_meme("⌐■_■"));
assert!(is_meme("ツ"));
assert!(!is_meme("svgbobg"));
assert!(!is_meme("not a meme in space"));
assert!(is_meme(" -_- "));
assert!(is_meme("-_-"));
assert!(!is_meme(" "));
}
#[test]
fn test_expression(){
assert!(is_meme("^_^"));
assert!(is_meme("x_x"));
assert!(!is_meme("+"));
assert!(!is_meme("x+y"));
assert!(!is_meme("x^2*y^2"));
assert!(!is_meme("x^2 * y^2"));
}
#[test]
fn test_bound(){
let meme = "(♥_♥)";
let memes = parse_memes(meme);
for m in memes.memes{
let b = m.head;
println!("bound {:?} d:{} ", b , b.distance());
assert_eq!(4, b.distance());
}
}
fn escape_str(s: &str) -> String{
let mut escaped = String::new();
for c in s.chars(){
escaped.push_str(&escape_char(&c));
}
escaped
}
fn escape_char(ch: &char) -> String {
let escs = [('"', """), ('\'', "'"), ('<', "<"), ('>', ">"), ('&', "&")];
let quote_match: Option<&(char, &str)> = escs.iter()
.find(|pair| {
let &(e, _) = *pair;
e == *ch
});
let quoted: String = match quote_match {
Some(&(_, quoted)) => String::from(quoted),
None => {
let mut s = String::new();
s.push(*ch);
s
}
};
quoted
}
fn is_operator(c: char) -> bool{
c == '+' || c == '-' || c == '*' || c == '/'
|| c == '^' || c == '%' || c == '!' || c == ','
|| c == '.' || c == '=' || c == '|' || c == '&'
}
#[test]
fn test_operator(){
assert!(!is_expression("^_^"));
assert!(is_operator('+'));
assert!(is_expression("+"));
assert!(is_expression("x+y"));
assert!(is_expression("x^2*y^2"));
assert!(is_expression("x^2 * y^2"));
}
//TODO: alternate alphanumeric_space and operator
fn is_expression(ch: &str) -> bool{
is_alphanumeric_space_operator(ch)
}
fn is_alphanumeric_space_operator(ch:&str) -> bool{
ch.chars().all(|c| c.is_alphanumeric() || c == ' ' || c == '_' || is_operator(c))
}
#[test]
fn test_body(){
let meme = "( ^_^)ノ";
println!("{}", meme);
let bodies = parse_memes(meme);
for b in &bodies.memes{
println!("{:#?}",b);
}
assert_eq!(1, bodies.memes.len());
}
#[test]
fn test_body2(){
let meme = "ヘ( ^_^)ノ \(^_^ )Gimme Five";
println!("{}", meme);
let bodies = parse_memes(meme);
for b in &bodies.memes{
println!("{:#?}",b);
}
assert_eq!(2, bodies.memes.len());
}
#[test]
fn test_rest_of_text(){
let meme = r#"The rest of 凸(•̀_•́)凸❤️ ( ͡° ͜ʖ ͡°) \(°□°)/层∀ the text is here"#;
println!("{}", meme);
let bodies = parse_memes(meme);
println!("{:#?}",bodies);
assert_eq!(3, bodies.memes.len());
assert_eq!(2, bodies.rest_str.len());
}
#[test]
fn test_unify_rest_of_text(){
let meme = r#"The rest of 凸(•̀_•́)凸❤️ ( ͡° ͜ʖ ͡°) \(°□°)/层∀ the text is here"#;
let resi = r#"The rest of the text is here"#;
println!("{}", meme);
let bodies = parse_memes(meme);
println!("{:#?}",bodies);
assert_eq!(3, bodies.memes.len());
assert_eq!(2, bodies.rest_str.len());
assert_eq!(meme.width(), bodies.unify_rest_text().width());
println!("residue: {} meme: {} rest_text:{}", resi.width(), meme.width(), bodies.unify_rest_text().width());
assert_eq!(resi.to_string(), bodies.unify_rest_text());
}
#[test]
fn test_meme_equation(){
let meme= r#"Equations are not rendered? ( -_- ) __(x+y)__ (^_^) (x^2+y^2)x"#;
println!("{}", meme);
let bodies = parse_memes(meme);
println!("{:#?}",bodies);
assert_eq!(2, bodies.memes.len());
assert_eq!(3, bodies.rest_str.len());
}
#[test]
fn test_meme_equation2(){
let meme= r#"( -_- ) __(x+y)__ (^_^) (x^2+y^2)"#;
println!("{}", meme);
let bodies = parse_memes(meme);
println!("{:#?}",bodies);
assert_eq!(2, bodies.memes.len());
assert_eq!(2, bodies.rest_str.len());
}
#[test]
fn test_meme_unmatched_face(){
let meme= r#"(╯°□°] ╯︵ ┬─┻"#;
println!("{}", meme);
let bodies = parse_memes(meme);
println!("{:#?}",bodies);
assert_eq!(0, bodies.memes.len());
assert_eq!(1, bodies.rest_str.len());
}
| true |
b82fd028a860df88fa7a6ba9d94139e4e58506ee
|
Rust
|
GEDJr/simdjson-rs
|
/src/parsed_json_iterator.rs
|
UTF-8
| 3,480 | 3.0625 | 3 |
[] |
no_license
|
use super::parsed_json::{ParsedJson, JSON_VALUE_MASK};
struct ScopeIndex {
start_of_scope: usize,
scope_type: u8,
}
impl Default for ScopeIndex {
fn default() -> ScopeIndex {
ScopeIndex {
start_of_scope: 0,
scope_type: 0,
}
}
}
pub struct ParsedJsonIterator<'a> {
pj: &'a ParsedJson,
depth: usize,
location: usize,
tape_length: usize,
current_type: u8,
current_val: u64,
depth_index: Vec<ScopeIndex>,
}
impl<'a> ParsedJsonIterator<'a> {
pub fn new(pj: &'a ParsedJson) -> ParsedJsonIterator<'a> {
let mut depth = 0;
let mut location = 0;
let mut tape_length = 0;
let mut current_type = 0;
let mut current_val = 0;
if pj.is_valid() {
let mut depth_index = Vec::with_capacity(pj.depth_capacity());
if depth_index.capacity() == 0 {
return ParsedJsonIterator {
pj,
depth,
location,
tape_length,
current_type,
current_val,
depth_index,
};
}
let mut scope_index = ScopeIndex::default();
scope_index.start_of_scope = location;
current_val = pj.tape[location];
location += 1;
current_type = current_val.overflowing_shr(56).0 as u8;
scope_index.scope_type = current_type;
depth_index.push(scope_index);
if current_type == b'r' {
tape_length = (current_val & JSON_VALUE_MASK) as usize;
if location < tape_length {
current_val = pj.tape[location];
current_type = current_val.overflowing_shr(56).0 as u8;
depth += 1;
depth_index[depth].start_of_scope = location;
depth_index[depth].scope_type = current_type;
}
}
return ParsedJsonIterator {
pj,
depth,
location,
tape_length,
current_type,
current_val,
depth_index,
};
} else {
panic!("Json is invalid");
}
}
pub fn is_ok(&self) -> bool {
self.location < self.tape_length
}
// useful for debuging purposes
pub fn get_tape_location(&self) -> usize {
self.location
}
// useful for debuging purposes
pub fn get_tape_length(&self) -> usize {
self.tape_length
}
/// returns the current depth (start at 1 with 0 reserved for the fictitious root node)
pub fn get_depth(&self) -> usize {
self.depth
}
pub fn get_scope_type(&self) -> u8 {
self.depth_index[self.depth].scope_type
}
pub fn move_forward(&mut self) -> bool {
if self.location + 1 >= self.tape_length {
return false;
}
if self.current_type == b'[' || self.current_type == b'{' {
self.depth += 1;
self.depth_index[self.depth].start_of_scope = self.location;
self.depth_index[self.depth].scope_type = self.current_type;
}
self.location += 1;
// [TODO]
true
}
}
// impl<'a> From<&ParsedJsonIterator<>> for ParsedJsonIterator
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {}
}
| true |
4535d4213c85288b0ec515adebc63016352856d1
|
Rust
|
Inky-developer/mc_utils
|
/mc_utils/rcon/src/de/mod.rs
|
UTF-8
| 1,405 | 3.015625 | 3 |
[
"MIT"
] |
permissive
|
use byteorder::{LittleEndian, ReadBytesExt};
use std::io::Cursor;
use std::io::Read;
use crate::{Error, Result};
/// Response of the minecraft server after a command was sent
#[derive(Debug)]
pub struct PacketResponse {
/// The id of the packet. Useless right now
pub packet_id: i32,
/// The response message
pub payload: String,
}
impl PacketResponse {
pub fn from_reader(reader: &mut impl Read) -> Result<PacketResponse> {
let length = reader.read_i32::<LittleEndian>()? as usize;
let mut buffer = Cursor::new(vec![0; length]);
reader.read_exact(buffer.get_mut())?;
let id = buffer.read_i32::<LittleEndian>()?;
let typ = buffer.read_i32::<LittleEndian>()?;
let string_length = buffer.get_ref().len() - buffer.position() as usize - 2; // one byte used to end the string and one byte used for padding
let mut string_buf = vec![0; string_length];
buffer.read_exact(&mut string_buf)?;
let string = String::from_utf8(string_buf).map_err(|_error| {
Error::IoError(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"Could not decode string",
))
})?;
if typ == 2 && id == -1 {
return Err(Error::LoginFailed);
}
Ok(PacketResponse {
payload: string,
packet_id: id,
})
}
}
| true |
2e96e722793f9e25ff2f9fbfdaddd45decd80464
|
Rust
|
JonasOlson/i8080
|
/src/pointer.rs
|
UTF-8
| 509 | 3.171875 | 3 |
[
"Apache-2.0",
"MIT"
] |
permissive
|
#[derive(Clone, Copy)]
pub struct Pointer(pub u16);
impl Default for Pointer {
fn default() -> Self {
Pointer(0)
}
}
impl From<u16> for Pointer {
fn from(from: u16) -> Self {
Pointer(from)
}
}
impl From<u8> for Pointer {
fn from(from: u8) -> Self {
Pointer(from as u16)
}
}
impl From<Pointer> for u16 {
fn from(from: Pointer) -> Self {
from.0
}
}
impl From<Pointer> for u8 {
fn from(from: Pointer) -> Self {
from.0 as u8
}
}
| true |
083bc343a655fa94e6d84afe29e41095825232c0
|
Rust
|
zmilan/tinychain
|
/prototype/scalar/value/number/instance.rs
|
UTF-8
| 45,777 | 2.984375 | 3 |
[
"Apache-2.0"
] |
permissive
|
use std::cmp::Ordering;
use std::convert::{TryFrom, TryInto};
use std::fmt;
use std::ops::{Add, Mul, Sub};
use serde::ser::{Serialize, SerializeMap, Serializer};
use crate::class::Instance;
use crate::error;
use crate::handler::{Handler, Route};
use crate::scalar::{Link, MethodType, PathSegment, ScalarInstance, ValueInstance};
use crate::{CastFrom, CastInto, TCResult};
use super::class::{BooleanType, ComplexType, FloatType, IntType, NumberType, UIntType};
use super::class::{NumberClass, NumberInstance};
#[derive(Clone, Copy, PartialEq, PartialOrd)]
pub struct Boolean(bool);
impl Instance for Boolean {
type Class = BooleanType;
fn class(&self) -> BooleanType {
BooleanType
}
}
impl ScalarInstance for Boolean {
type Class = BooleanType;
}
impl ValueInstance for Boolean {
type Class = BooleanType;
}
impl NumberInstance for Boolean {
type Abs = Self;
type Class = BooleanType;
fn into_type(self, _dtype: BooleanType) -> Boolean {
self
}
fn abs(self) -> Self {
self
}
fn and(self, other: Self) -> Self {
Boolean(self.0 && other.0)
}
fn not(self) -> Self {
Boolean(!self.0)
}
fn or(self, other: Self) -> Self {
Boolean(self.0 || other.0)
}
fn xor(self, other: Self) -> Self {
Boolean(self.0 ^ other.0)
}
}
impl Route for Boolean {
fn route(&'_ self, method: MethodType, path: &[PathSegment]) -> Option<Box<dyn Handler + '_>> {
super::handlers::route(self, method, path)
}
}
impl Default for Boolean {
fn default() -> Boolean {
Boolean(false)
}
}
impl From<bool> for Boolean {
fn from(b: bool) -> Boolean {
Boolean(b)
}
}
impl From<Boolean> for bool {
fn from(b: Boolean) -> bool {
b.0
}
}
impl From<&Boolean> for bool {
fn from(b: &Boolean) -> bool {
b.0
}
}
impl Eq for Boolean {}
impl Add for Boolean {
type Output = Self;
fn add(self, other: Boolean) -> Self::Output {
match (self, other) {
(Boolean(false), Boolean(false)) => Boolean(false),
_ => Boolean(true),
}
}
}
impl Mul for Boolean {
type Output = Self;
fn mul(self, other: Boolean) -> Self {
match (self, other) {
(Boolean(true), Boolean(true)) => Boolean(true),
_ => Boolean(false),
}
}
}
impl Sub for Boolean {
type Output = Self;
fn sub(self, other: Boolean) -> Self::Output {
match (self, other) {
(left, Boolean(false)) => left,
_ => Boolean(false),
}
}
}
impl CastFrom<Boolean> for u64 {
fn cast_from(b: Boolean) -> u64 {
UInt::from(b).into()
}
}
impl fmt::Display for Boolean {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl Serialize for Boolean {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.serialize_bool(self.0)
}
}
#[derive(Clone, Copy)]
pub enum Complex {
C32(num::Complex<f32>),
C64(num::Complex<f64>),
}
impl Instance for Complex {
type Class = ComplexType;
fn class(&self) -> ComplexType {
match self {
Complex::C32(_) => ComplexType::C32,
Complex::C64(_) => ComplexType::C64,
}
}
}
impl ScalarInstance for Complex {
type Class = ComplexType;
}
impl ValueInstance for Complex {
type Class = ComplexType;
}
impl NumberInstance for Complex {
type Abs = Float;
type Class = ComplexType;
fn into_type(self, dtype: ComplexType) -> Complex {
use ComplexType::*;
match dtype {
C32 => match self {
Self::C64(c) => Self::C32(num::Complex::new(c.re as f32, c.im as f32)),
this => this,
},
C64 => match self {
Self::C32(c) => Self::C64(num::Complex::new(c.re as f64, c.im as f64)),
this => this,
},
}
}
fn abs(self) -> Float {
match self {
Self::C32(c) => Float::F32(c.norm_sqr()),
Self::C64(c) => Float::F64(c.norm_sqr()),
}
}
}
impl Route for Complex {
fn route(&'_ self, method: MethodType, path: &[PathSegment]) -> Option<Box<dyn Handler + '_>> {
super::handlers::route(self, method, path)
}
}
impl CastFrom<Number> for Complex {
fn cast_from(number: Number) -> Complex {
use Number::*;
match number {
Number::Bool(b) => Self::cast_from(b),
Complex(c) => c,
Float(f) => Self::cast_from(f),
Int(i) => Self::cast_from(i),
UInt(u) => Self::cast_from(u),
}
}
}
impl CastFrom<Complex> for Boolean {
fn cast_from(c: Complex) -> Self {
match c {
Complex::C32(c) if c.norm_sqr() == 0f32 => Boolean(false),
Complex::C64(c) if c.norm_sqr() == 0f64 => Boolean(false),
_ => Boolean(true),
}
}
}
impl CastFrom<Complex> for num::Complex<f32> {
fn cast_from(c: Complex) -> Self {
match c {
Complex::C32(c) => c,
Complex::C64(num::Complex { re, im }) => num::Complex::new(re as f32, im as f32),
}
}
}
// impl CastFrom<Complex> for num::Complex<f64> {
// fn cast_from(c: Complex) -> Self {
// match c {
// Self::C32(num::Complex { re, im }) => num::Complex::new(re as f64, im as f64),
// Self::C64(c) => c,
// }
// }
// }
impl Add for Complex {
type Output = Self;
fn add(self, other: Complex) -> Self {
match (self, other) {
(Self::C32(l), Self::C32(r)) => Self::C32(l + r),
(Self::C64(l), Self::C64(r)) => Self::C64(l + r),
(Self::C64(l), r) => {
let r: num::Complex<f64> = r.into();
Self::C64(l + r)
}
(l, r) => r + l,
}
}
}
impl Mul for Complex {
type Output = Self;
fn mul(self, other: Complex) -> Self {
match (self, other) {
(Self::C32(l), Self::C32(r)) => Self::C32(l * r),
(Self::C64(l), Self::C64(r)) => Self::C64(l * r),
(Self::C64(l), r) => {
let r: num::Complex<f64> = r.into();
Self::C64(l * r)
}
(l, r) => r * l,
}
}
}
impl Sub for Complex {
type Output = Self;
fn sub(self, other: Complex) -> Self {
match (self, other) {
(Self::C32(l), Self::C32(r)) => Self::C32(l - r),
(l, r) => {
let l: num::Complex<f64> = l.into();
let r: num::Complex<f64> = r.into();
Self::C64(l - r)
}
}
}
}
impl PartialEq for Complex {
fn eq(&self, other: &Self) -> bool {
type Max = num::complex::Complex<f64>;
match (self, other) {
(Self::C32(l), Self::C32(r)) => l.eq(r),
(Self::C64(l), Self::C64(r)) => l.eq(r),
(l, r) => Max::from(*l).eq(&Max::from(*r)),
}
}
}
impl Eq for Complex {}
impl PartialOrd for Complex {
fn partial_cmp(&self, other: &Complex) -> Option<Ordering> {
match (self, other) {
(Complex::C32(l), Complex::C32(r)) => l.norm_sqr().partial_cmp(&r.norm_sqr()),
(Complex::C64(l), Complex::C64(r)) => l.norm_sqr().partial_cmp(&r.norm_sqr()),
_ => None,
}
}
}
impl Default for Complex {
fn default() -> Complex {
Complex::C32(num::Complex::<f32>::default())
}
}
impl From<Complex> for num::Complex<f64> {
fn from(c: Complex) -> Self {
match c {
Complex::C32(c) => num::Complex::new(c.re as f64, c.im as f64),
Complex::C64(c64) => c64,
}
}
}
impl From<Float> for Complex {
fn from(f: Float) -> Self {
match f {
Float::F64(f) => Self::C64(num::Complex::new(f, 0.0f64)),
Float::F32(f) => Self::C32(num::Complex::new(f, 0.0f32)),
}
}
}
impl From<Int> for Complex {
fn from(i: Int) -> Self {
match i {
Int::I64(i) => Self::C64(num::Complex::new(i as f64, 0.0f64)),
Int::I32(i) => Self::C32(num::Complex::new(i as f32, 0.0f32)),
Int::I16(i) => Self::C32(num::Complex::new(i as f32, 0.0f32)),
}
}
}
impl From<UInt> for Complex {
fn from(u: UInt) -> Self {
match u {
UInt::U64(u) => Self::C64(num::Complex::new(u as f64, 0.0f64)),
UInt::U32(u) => Self::C32(num::Complex::new(u as f32, 0.0f32)),
UInt::U16(u) => Self::C32(num::Complex::new(u as f32, 0.0f32)),
UInt::U8(u) => Self::C32(num::Complex::new(u as f32, 0.0f32)),
}
}
}
impl From<Boolean> for Complex {
fn from(b: Boolean) -> Self {
match b {
Boolean(true) => Self::C32(num::Complex::new(1.0f32, 0.0f32)),
Boolean(false) => Self::C32(num::Complex::new(1.0f32, 0.0f32)),
}
}
}
impl From<num::Complex<f32>> for Complex {
fn from(c: num::Complex<f32>) -> Complex {
Complex::C32(c)
}
}
impl From<num::Complex<f64>> for Complex {
fn from(c: num::Complex<f64>) -> Complex {
Complex::C64(c)
}
}
impl TryFrom<Complex> for num::Complex<f32> {
type Error = error::TCError;
fn try_from(c: Complex) -> TCResult<num::Complex<f32>> {
match c {
Complex::C32(c) => Ok(c),
other => Err(error::bad_request("Expected C32 but found", other)),
}
}
}
impl Serialize for Complex {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
match self {
Complex::C32(c) => {
let mut map = s.serialize_map(Some(1))?;
map.serialize_entry(&Link::from(self.class()).to_string(), &[c.re, c.im])?;
map.end()
}
Complex::C64(c) => {
let mut map = s.serialize_map(Some(1))?;
map.serialize_entry(&Link::from(self.class()).to_string(), &[c.re, c.im])?;
map.end()
}
}
}
}
impl fmt::Display for Complex {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Complex::C32(c) => write!(f, "C32({})", c),
Complex::C64(c) => write!(f, "C64({})", c),
}
}
}
#[derive(Clone, Copy)]
pub enum Float {
F32(f32),
F64(f64),
}
impl Instance for Float {
type Class = FloatType;
fn class(&self) -> FloatType {
match self {
Float::F32(_) => FloatType::F32,
Float::F64(_) => FloatType::F64,
}
}
}
impl ScalarInstance for Float {
type Class = FloatType;
}
impl ValueInstance for Float {
type Class = FloatType;
}
impl NumberInstance for Float {
type Abs = Float;
type Class = FloatType;
fn into_type(self, dtype: FloatType) -> Float {
use FloatType::*;
match dtype {
F32 => match self {
Self::F64(f) => Self::F32(f as f32),
this => this,
},
F64 => match self {
Self::F32(f) => Self::F64(f as f64),
this => this,
},
}
}
fn abs(self) -> Float {
match self {
Self::F32(f) => Self::F32(f.abs()),
Self::F64(f) => Self::F64(f.abs()),
}
}
}
impl Route for Float {
fn route(&'_ self, method: MethodType, path: &[PathSegment]) -> Option<Box<dyn Handler + '_>> {
super::handlers::route(self, method, path)
}
}
impl CastFrom<Complex> for Float {
fn cast_from(c: Complex) -> Float {
use Complex::*;
match c {
C32(c) => Self::F32(c.re),
C64(c) => Self::F64(c.re),
}
}
}
impl CastFrom<Float> for Boolean {
fn cast_from(f: Float) -> Boolean {
use Float::*;
let b = match f {
F32(f) if f == 0f32 => false,
F64(f) if f == 0f64 => false,
_ => true,
};
Boolean(b)
}
}
impl CastFrom<Float> for f32 {
fn cast_from(f: Float) -> f32 {
match f {
Float::F32(f) => f,
Float::F64(f) => f as f32,
}
}
}
impl Eq for Float {}
impl Add for Float {
type Output = Self;
fn add(self, other: Float) -> Self {
match (self, other) {
(Self::F32(l), Self::F32(r)) => Self::F32(l + r),
(Self::F64(l), Self::F64(r)) => Self::F64(l + r),
(Self::F64(l), Self::F32(r)) => Self::F64(l + r as f64),
(l, r) => (r + l),
}
}
}
impl Mul for Float {
type Output = Self;
fn mul(self, other: Float) -> Self {
match (self, other) {
(Self::F32(l), Self::F32(r)) => Self::F32(l * r),
(Self::F64(l), Self::F64(r)) => Self::F64(l * r),
(Self::F64(l), Self::F32(r)) => Self::F64(l * r as f64),
(l, r) => (r * l),
}
}
}
impl Sub for Float {
type Output = Self;
fn sub(self, other: Float) -> Self {
match (self, other) {
(Self::F32(l), Self::F32(r)) => Self::F32(l - r),
(l, r) => {
let l: f64 = l.into();
let r: f64 = r.into();
Self::F64(l - r)
}
}
}
}
impl PartialEq for Float {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Self::F32(l), Self::F32(r)) => l.eq(r),
(Self::F64(l), Self::F64(r)) => l.eq(r),
(l, r) => f64::from(*l).eq(&f64::from(*r)),
}
}
}
impl PartialOrd for Float {
fn partial_cmp(&self, other: &Float) -> Option<Ordering> {
match (self, other) {
(Float::F32(l), Float::F32(r)) => l.partial_cmp(r),
(Float::F64(l), Float::F64(r)) => l.partial_cmp(r),
_ => None,
}
}
}
impl Default for Float {
fn default() -> Float {
Float::F32(f32::default())
}
}
impl From<Boolean> for Float {
fn from(b: Boolean) -> Self {
match b {
Boolean(true) => Self::F32(1.0f32),
Boolean(false) => Self::F32(0.0f32),
}
}
}
impl From<f32> for Float {
fn from(f: f32) -> Self {
Self::F32(f)
}
}
impl From<f64> for Float {
fn from(f: f64) -> Self {
Self::F64(f)
}
}
impl From<Int> for Float {
fn from(i: Int) -> Self {
match i {
Int::I64(i) => Self::F64(i as f64),
Int::I32(i) => Self::F32(i as f32),
Int::I16(i) => Self::F32(i as f32),
}
}
}
impl From<UInt> for Float {
fn from(u: UInt) -> Self {
match u {
UInt::U64(u) => Self::F64(u as f64),
UInt::U32(u) => Self::F32(u as f32),
UInt::U16(u) => Self::F32(u as f32),
UInt::U8(u) => Self::F32(u as f32),
}
}
}
impl TryFrom<Float> for f32 {
type Error = error::TCError;
fn try_from(f: Float) -> TCResult<f32> {
match f {
Float::F32(f) => Ok(f),
other => Err(error::bad_request("Expected F32 but found", other)),
}
}
}
impl From<Float> for f64 {
fn from(f: Float) -> f64 {
match f {
Float::F32(f) => f as f64,
Float::F64(f) => f,
}
}
}
impl Serialize for Float {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
match self {
Float::F32(f) => s.serialize_f32(*f),
Float::F64(f) => s.serialize_f64(*f),
}
}
}
impl fmt::Display for Float {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Float::F32(i) => write!(f, "F32({})", i),
Float::F64(i) => write!(f, "F64({})", i),
}
}
}
#[derive(Clone, Copy)]
pub enum Int {
I16(i16),
I32(i32),
I64(i64),
}
impl Instance for Int {
type Class = IntType;
fn class(&self) -> IntType {
match self {
Int::I16(_) => IntType::I16,
Int::I32(_) => IntType::I32,
Int::I64(_) => IntType::I64,
}
}
}
impl ScalarInstance for Int {
type Class = IntType;
}
impl ValueInstance for Int {
type Class = IntType;
}
impl NumberInstance for Int {
type Abs = Self;
type Class = IntType;
fn into_type(self, dtype: IntType) -> Int {
use IntType::*;
match dtype {
I16 => match self {
Self::I32(i) => Self::I16(i as i16),
Self::I64(i) => Self::I16(i as i16),
this => this,
},
I32 => match self {
Self::I16(i) => Self::I32(i as i32),
Self::I64(i) => Self::I32(i as i32),
this => this,
},
I64 => match self {
Self::I16(i) => Self::I64(i as i64),
Self::I32(i) => Self::I64(i as i64),
this => this,
},
}
}
fn abs(self) -> Self {
match self {
Self::I16(i) => Int::I16(i.abs()),
Self::I32(i) => Int::I32(i.abs()),
Self::I64(i) => Int::I64(i.abs()),
}
}
}
impl Route for Int {
fn route(&'_ self, method: MethodType, path: &[PathSegment]) -> Option<Box<dyn Handler + '_>> {
super::handlers::route(self, method, path)
}
}
impl CastFrom<Complex> for Int {
fn cast_from(c: Complex) -> Int {
use Complex::*;
match c {
C32(c) => Self::I32(c.re as i32),
C64(c) => Self::I64(c.re as i64),
}
}
}
impl CastFrom<Float> for Int {
fn cast_from(f: Float) -> Int {
use Float::*;
match f {
F32(f) => Self::I32(f as i32),
F64(f) => Self::I64(f as i64),
}
}
}
impl CastFrom<Int> for Boolean {
fn cast_from(i: Int) -> Boolean {
use Int::*;
let b = match i {
I16(i) if i == 0i16 => false,
I32(i) if i == 0i32 => false,
I64(i) if i == 0i64 => false,
_ => true,
};
Boolean(b)
}
}
impl CastFrom<Int> for i16 {
fn cast_from(i: Int) -> i16 {
match i {
Int::I16(i) => i,
Int::I32(i) => i as i16,
Int::I64(i) => i as i16,
}
}
}
impl CastFrom<Int> for i32 {
fn cast_from(i: Int) -> i32 {
match i {
Int::I16(i) => i as i32,
Int::I32(i) => i,
Int::I64(i) => i as i32,
}
}
}
impl Eq for Int {}
impl Add for Int {
type Output = Self;
fn add(self, other: Int) -> Self {
match (self, other) {
(Self::I64(l), Self::I64(r)) => Self::I64(l + r),
(Self::I64(l), Self::I32(r)) => Self::I64(l + r as i64),
(Self::I64(l), Self::I16(r)) => Self::I64(l + r as i64),
(Self::I32(l), Self::I32(r)) => Self::I32(l + r),
(Self::I32(l), Self::I16(r)) => Self::I32(l + r as i32),
(Self::I16(l), Self::I16(r)) => Self::I16(l + r),
(l, r) => r + l,
}
}
}
impl Mul for Int {
type Output = Self;
fn mul(self, other: Int) -> Self {
match (self, other) {
(Self::I64(l), Self::I64(r)) => Self::I64(l * r),
(Self::I64(l), Self::I32(r)) => Self::I64(l * r as i64),
(Self::I64(l), Self::I16(r)) => Self::I64(l * r as i64),
(Self::I32(l), Self::I32(r)) => Self::I32(l * r),
(Self::I32(l), Self::I16(r)) => Self::I32(l * r as i32),
(Self::I16(l), Self::I16(r)) => Self::I16(l * r),
(l, r) => r * l,
}
}
}
impl Sub for Int {
type Output = Self;
fn sub(self, other: Int) -> Self {
match (self, other) {
(Self::I64(l), Self::I64(r)) => Self::I64(l - r),
(Self::I64(l), Self::I32(r)) => Self::I64(l - r as i64),
(Self::I64(l), Self::I16(r)) => Self::I64(l - r as i64),
(Self::I32(l), Self::I32(r)) => Self::I32(l - r),
(Self::I32(l), Self::I16(r)) => Self::I32(l - r as i32),
(Self::I16(l), Self::I16(r)) => Self::I16(l - r),
(Self::I16(l), Self::I32(r)) => Self::I32(l as i32 - r),
(Self::I16(l), Self::I64(r)) => Self::I64(l as i64 - r),
(Self::I32(l), Self::I64(r)) => Self::I64(l as i64 - r),
}
}
}
impl PartialEq for Int {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Self::I16(l), Self::I16(r)) => l.eq(r),
(Self::I32(l), Self::I32(r)) => l.eq(r),
(Self::I64(l), Self::I64(r)) => l.eq(r),
(Self::I64(l), r) => l.eq(&i64::from(*r)),
(l, r) => i64::from(*l).eq(&i64::from(*r)),
}
}
}
impl PartialOrd for Int {
fn partial_cmp(&self, other: &Int) -> Option<Ordering> {
match (self, other) {
(Int::I16(l), Int::I16(r)) => l.partial_cmp(r),
(Int::I32(l), Int::I32(r)) => l.partial_cmp(r),
(Int::I64(l), Int::I64(r)) => l.partial_cmp(r),
_ => None,
}
}
}
impl Default for Int {
fn default() -> Int {
Int::I16(i16::default())
}
}
impl From<i16> for Int {
fn from(i: i16) -> Int {
Int::I16(i)
}
}
impl From<i32> for Int {
fn from(i: i32) -> Int {
Int::I32(i)
}
}
impl From<i64> for Int {
fn from(i: i64) -> Int {
Int::I64(i)
}
}
impl From<UInt> for Int {
fn from(u: UInt) -> Int {
match u {
UInt::U64(u) => Int::I64(u as i64),
UInt::U32(u) => Int::I32(u as i32),
UInt::U16(u) => Int::I16(u as i16),
UInt::U8(u) => Int::I16(u as i16),
}
}
}
impl From<Boolean> for Int {
fn from(b: Boolean) -> Int {
match b {
Boolean(true) => Int::I16(1),
Boolean(false) => Int::I16(0),
}
}
}
impl TryFrom<Int> for i16 {
type Error = error::TCError;
fn try_from(i: Int) -> TCResult<i16> {
match i {
Int::I16(i) => Ok(i),
other => Err(error::bad_request("Expected I16 but found", other)),
}
}
}
impl TryFrom<Int> for i32 {
type Error = error::TCError;
fn try_from(i: Int) -> TCResult<i32> {
match i {
Int::I32(i) => Ok(i),
other => Err(error::bad_request("Expected I32 but found", other)),
}
}
}
impl From<Int> for i64 {
fn from(i: Int) -> i64 {
match i {
Int::I16(i) => i as i64,
Int::I32(i) => i as i64,
Int::I64(i) => i,
}
}
}
impl Serialize for Int {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
match self {
Int::I16(i) => s.serialize_i16(*i),
Int::I32(i) => s.serialize_i32(*i),
Int::I64(i) => s.serialize_i64(*i),
}
}
}
impl fmt::Display for Int {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Int::I16(i) => write!(f, "I16: {}", i),
Int::I32(i) => write!(f, "I32: {}", i),
Int::I64(i) => write!(f, "I64: {}", i),
}
}
}
#[derive(Clone, Copy)]
pub enum UInt {
U8(u8),
U16(u16),
U32(u32),
U64(u64),
}
impl Instance for UInt {
type Class = UIntType;
fn class(&self) -> UIntType {
match self {
UInt::U8(_) => UIntType::U8,
UInt::U16(_) => UIntType::U16,
UInt::U32(_) => UIntType::U32,
UInt::U64(_) => UIntType::U64,
}
}
}
impl ScalarInstance for UInt {
type Class = UIntType;
}
impl ValueInstance for UInt {
type Class = UIntType;
}
impl NumberInstance for UInt {
type Abs = Self;
type Class = UIntType;
fn into_type(self, dtype: UIntType) -> UInt {
use UIntType::*;
match dtype {
U8 => match self {
Self::U16(u) => Self::U8(u as u8),
Self::U32(u) => Self::U8(u as u8),
Self::U64(u) => Self::U8(u as u8),
this => this,
},
U16 => match self {
Self::U8(u) => Self::U16(u as u16),
Self::U32(u) => Self::U16(u as u16),
Self::U64(u) => Self::U16(u as u16),
this => this,
},
U32 => match self {
Self::U8(u) => Self::U32(u as u32),
Self::U16(u) => Self::U32(u as u32),
Self::U64(u) => Self::U32(u as u32),
this => this,
},
U64 => match self {
Self::U8(u) => Self::U64(u as u64),
Self::U16(u) => Self::U64(u as u64),
Self::U32(u) => Self::U64(u as u64),
this => this,
},
}
}
fn abs(self) -> UInt {
self
}
}
impl Route for UInt {
fn route(&'_ self, method: MethodType, path: &[PathSegment]) -> Option<Box<dyn Handler + '_>> {
super::handlers::route(self, method, path)
}
}
impl CastFrom<Complex> for UInt {
fn cast_from(c: Complex) -> UInt {
use Complex::*;
match c {
C32(c) => Self::U32(c.re as u32),
C64(c) => Self::U64(c.re as u64),
}
}
}
impl CastFrom<Float> for UInt {
fn cast_from(f: Float) -> UInt {
use Float::*;
match f {
F32(f) => Self::U32(f as u32),
F64(f) => Self::U64(f as u64),
}
}
}
impl CastFrom<Int> for UInt {
fn cast_from(i: Int) -> UInt {
use Int::*;
match i {
I16(i) => Self::U16(i as u16),
I32(i) => Self::U32(i as u32),
I64(i) => Self::U64(i as u64),
}
}
}
impl CastFrom<UInt> for bool {
fn cast_from(u: UInt) -> bool {
use UInt::*;
match u {
U8(u) if u == 0u8 => false,
U16(u) if u == 0u16 => false,
U32(u) if u == 0u32 => false,
U64(u) if u == 0u64 => false,
_ => true,
}
}
}
impl CastFrom<UInt> for u8 {
fn cast_from(u: UInt) -> u8 {
use UInt::*;
match u {
U8(u) => u,
U16(u) => u as u8,
U32(u) => u as u8,
U64(u) => u as u8,
}
}
}
impl CastFrom<UInt> for u16 {
fn cast_from(u: UInt) -> u16 {
use UInt::*;
match u {
U8(u) => u as u16,
U16(u) => u,
U32(u) => u as u16,
U64(u) => u as u16,
}
}
}
impl CastFrom<UInt> for u32 {
fn cast_from(u: UInt) -> u32 {
use UInt::*;
match u {
U8(u) => u as u32,
U16(u) => u as u32,
U32(u) => u,
U64(u) => u as u32,
}
}
}
impl Add for UInt {
type Output = Self;
fn add(self, other: UInt) -> Self {
match (self, other) {
(UInt::U64(l), UInt::U64(r)) => UInt::U64(l + r),
(UInt::U64(l), UInt::U32(r)) => UInt::U64(l + r as u64),
(UInt::U64(l), UInt::U16(r)) => UInt::U64(l + r as u64),
(UInt::U64(l), UInt::U8(r)) => UInt::U64(l + r as u64),
(UInt::U32(l), UInt::U32(r)) => UInt::U32(l + r),
(UInt::U32(l), UInt::U16(r)) => UInt::U32(l + r as u32),
(UInt::U32(l), UInt::U8(r)) => UInt::U32(l + r as u32),
(UInt::U16(l), UInt::U16(r)) => UInt::U16(l + r),
(UInt::U16(l), UInt::U8(r)) => UInt::U16(l + r as u16),
(UInt::U8(l), UInt::U8(r)) => UInt::U8(l + r),
(l, r) => r + l,
}
}
}
impl Mul for UInt {
type Output = Self;
fn mul(self, other: UInt) -> Self {
match (self, other) {
(UInt::U64(l), UInt::U64(r)) => UInt::U64(l * r),
(UInt::U64(l), UInt::U32(r)) => UInt::U64(l * r as u64),
(UInt::U64(l), UInt::U16(r)) => UInt::U64(l * r as u64),
(UInt::U64(l), UInt::U8(r)) => UInt::U64(l * r as u64),
(UInt::U32(l), UInt::U32(r)) => UInt::U32(l * r),
(UInt::U32(l), UInt::U16(r)) => UInt::U32(l * r as u32),
(UInt::U32(l), UInt::U8(r)) => UInt::U32(l * r as u32),
(UInt::U16(l), UInt::U16(r)) => UInt::U16(l * r),
(UInt::U16(l), UInt::U8(r)) => UInt::U16(l * r as u16),
(UInt::U8(l), UInt::U8(r)) => UInt::U8(l * r),
(l, r) => r * l,
}
}
}
impl Sub for UInt {
type Output = Self;
fn sub(self, other: UInt) -> Self {
match (self, other) {
(UInt::U64(l), UInt::U64(r)) => UInt::U64(l - r),
(UInt::U64(l), UInt::U32(r)) => UInt::U64(l - r as u64),
(UInt::U64(l), UInt::U16(r)) => UInt::U64(l - r as u64),
(UInt::U64(l), UInt::U8(r)) => UInt::U64(l - r as u64),
(UInt::U32(l), UInt::U32(r)) => UInt::U32(l - r),
(UInt::U32(l), UInt::U16(r)) => UInt::U32(l - r as u32),
(UInt::U32(l), UInt::U8(r)) => UInt::U32(l - r as u32),
(UInt::U16(l), UInt::U16(r)) => UInt::U16(l - r),
(UInt::U16(l), UInt::U8(r)) => UInt::U16(l - r as u16),
(UInt::U8(l), UInt::U8(r)) => UInt::U8(l - r),
(UInt::U8(l), UInt::U16(r)) => UInt::U16(l as u16 - r),
(UInt::U8(l), UInt::U32(r)) => UInt::U32(l as u32 - r),
(UInt::U8(l), UInt::U64(r)) => UInt::U64(l as u64 - r),
(UInt::U16(l), r) => {
let r: u64 = r.into();
UInt::U16(l - r as u16)
}
(UInt::U32(l), r) => {
let r: u64 = r.into();
UInt::U32(l - r as u32)
}
}
}
}
impl Eq for UInt {}
impl Ord for UInt {
fn cmp(&self, other: &UInt) -> Ordering {
match (self, other) {
(UInt::U64(l), UInt::U64(r)) => l.cmp(r),
(UInt::U64(l), UInt::U32(r)) => l.cmp(&r.clone().into()),
(UInt::U64(l), UInt::U16(r)) => l.cmp(&r.clone().into()),
(UInt::U64(l), UInt::U8(r)) => l.cmp(&r.clone().into()),
(UInt::U32(l), UInt::U32(r)) => l.cmp(r),
(UInt::U32(l), UInt::U16(r)) => l.cmp(&r.clone().into()),
(UInt::U32(l), UInt::U8(r)) => l.cmp(&r.clone().into()),
(UInt::U16(l), UInt::U16(r)) => l.cmp(r),
(UInt::U16(l), UInt::U8(r)) => l.cmp(&r.clone().into()),
(UInt::U8(l), UInt::U8(r)) => l.cmp(r),
(l, r) => match r.cmp(l) {
Ordering::Greater => Ordering::Less,
Ordering::Less => Ordering::Greater,
Ordering::Equal => Ordering::Equal,
},
}
}
}
impl PartialEq for UInt {
fn eq(&self, other: &UInt) -> bool {
match (self, other) {
(Self::U8(l), Self::U8(r)) => l.eq(r),
(Self::U16(l), Self::U16(r)) => l.eq(r),
(Self::U32(l), Self::U32(r)) => l.eq(r),
(Self::U64(l), Self::U64(r)) => l.eq(r),
(l, r) => u64::from(*l).eq(&u64::from(*r)),
}
}
}
impl PartialOrd for UInt {
fn partial_cmp(&self, other: &UInt) -> Option<Ordering> {
match (self, other) {
(Self::U8(l), Self::U8(r)) => l.partial_cmp(r),
(Self::U16(l), Self::U16(r)) => l.partial_cmp(r),
(Self::U32(l), Self::U32(r)) => l.partial_cmp(r),
(Self::U64(l), Self::U64(r)) => l.partial_cmp(r),
(l, r) => u64::from(*l).partial_cmp(&u64::from(*r)),
}
}
}
impl Default for UInt {
fn default() -> UInt {
UInt::U8(u8::default())
}
}
impl From<Boolean> for UInt {
fn from(b: Boolean) -> UInt {
match b {
Boolean(true) => UInt::U8(1),
Boolean(false) => UInt::U8(0),
}
}
}
impl From<u8> for UInt {
fn from(u: u8) -> UInt {
UInt::U8(u)
}
}
impl From<u16> for UInt {
fn from(u: u16) -> UInt {
UInt::U16(u)
}
}
impl From<u32> for UInt {
fn from(u: u32) -> UInt {
UInt::U32(u)
}
}
impl From<u64> for UInt {
fn from(u: u64) -> UInt {
UInt::U64(u)
}
}
impl TryFrom<UInt> for u8 {
type Error = error::TCError;
fn try_from(u: UInt) -> TCResult<u8> {
match u {
UInt::U8(u) => Ok(u),
other => Err(error::bad_request("Expected a UInt8 but found", other)),
}
}
}
impl TryFrom<UInt> for u16 {
type Error = error::TCError;
fn try_from(u: UInt) -> TCResult<u16> {
match u {
UInt::U16(u) => Ok(u),
other => Err(error::bad_request("Expected a UInt16 but found", other)),
}
}
}
impl TryFrom<UInt> for u32 {
type Error = error::TCError;
fn try_from(u: UInt) -> TCResult<u32> {
match u {
UInt::U32(u) => Ok(u),
other => Err(error::bad_request("Expected a UInt32 but found", other)),
}
}
}
impl From<UInt> for u64 {
fn from(u: UInt) -> u64 {
match u {
UInt::U64(u) => u,
UInt::U32(u) => u as u64,
UInt::U16(u) => u as u64,
UInt::U8(u) => u as u64,
}
}
}
impl From<UInt> for usize {
fn from(u: UInt) -> usize {
match u {
UInt::U64(u) => u as usize,
UInt::U32(u) => u as usize,
UInt::U16(u) => u as usize,
UInt::U8(u) => u as usize,
}
}
}
impl Serialize for UInt {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
match self {
UInt::U8(u) => s.serialize_u8(*u),
UInt::U16(u) => s.serialize_u16(*u),
UInt::U32(u) => s.serialize_u32(*u),
UInt::U64(u) => s.serialize_u64(*u),
}
}
}
impl fmt::Display for UInt {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
UInt::U8(u) => write!(f, "U8: {}", u),
UInt::U16(u) => write!(f, "UInt16: {}", u),
UInt::U32(u) => write!(f, "UInt32: {}", u),
UInt::U64(u) => write!(f, "UInt64: {}", u),
}
}
}
#[derive(Clone, Copy, Eq)]
pub enum Number {
Bool(Boolean),
Complex(Complex),
Float(Float),
Int(Int),
UInt(UInt),
}
impl Instance for Number {
type Class = NumberType;
fn class(&self) -> NumberType {
use NumberType::*;
match self {
Self::Bool(_) => Bool,
Self::Complex(c) => Complex(c.class()),
Self::Float(f) => Float(f.class()),
Self::Int(i) => Int(i.class()),
Self::UInt(u) => UInt(u.class()),
}
}
}
impl ScalarInstance for Number {
type Class = NumberType;
}
impl ValueInstance for Number {
type Class = NumberType;
}
impl NumberInstance for Number {
type Abs = Number;
type Class = NumberType;
fn into_type(self, dtype: NumberType) -> Number {
use NumberType as NT;
match dtype {
NT::Bool => {
let b: Boolean = self.cast_into();
b.into()
}
NT::Complex(ct) => {
let c: Complex = self.cast_into();
c.into_type(ct).into()
}
NT::Float(ft) => {
let f: Float = self.cast_into();
f.into_type(ft).into()
}
NT::Int(it) => {
let i: Int = self.cast_into();
i.into_type(it).into()
}
NT::UInt(ut) => {
let u: UInt = self.cast_into();
u.into_type(ut).into()
}
NT::Number => self,
}
}
fn abs(self) -> Number {
use Number::*;
match self {
Complex(c) => Float(c.abs()),
Float(f) => Float(f.abs()),
Int(i) => Int(i.abs()),
other => other,
}
}
}
impl Route for Number {
fn route(&'_ self, method: MethodType, path: &[PathSegment]) -> Option<Box<dyn Handler + '_>> {
super::handlers::route(self, method, path)
}
}
impl PartialEq for Number {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Self::Int(l), Self::Int(r)) => l.eq(r),
(Self::UInt(l), Self::UInt(r)) => l.eq(r),
(Self::Float(l), Self::Float(r)) => l.eq(r),
(Self::Bool(l), Self::Bool(r)) => l.eq(r),
(Self::Complex(l), Self::Complex(r)) => l.eq(r),
(Self::Complex(l), r) => l.eq(&Complex::cast_from(*r)),
(Self::Float(l), r) => l.eq(&Float::cast_from(*r)),
(Self::Int(l), r) => l.eq(&Int::cast_from(*r)),
(Self::UInt(l), r) => l.eq(&UInt::cast_from(*r)),
(l, r) => r.eq(l),
}
}
}
impl PartialOrd for Number {
fn partial_cmp(&self, other: &Number) -> Option<Ordering> {
match (self, other) {
(Self::Int(l), Self::Int(r)) => l.partial_cmp(r),
(Self::UInt(l), Self::UInt(r)) => l.partial_cmp(r),
(Self::Float(l), Self::Float(r)) => l.partial_cmp(r),
(Self::Bool(l), Self::Bool(r)) => l.partial_cmp(r),
(Self::Complex(l), Self::Complex(r)) => l.partial_cmp(r),
(Self::Complex(l), r) => l.partial_cmp(&Complex::cast_from(*r)),
(Self::Float(l), r) => l.partial_cmp(&Float::cast_from(*r)),
(Self::Int(l), r) => l.partial_cmp(&Int::cast_from(*r)),
(Self::UInt(l), r) => l.partial_cmp(&UInt::cast_from(*r)),
(l, r) => match r.partial_cmp(l) {
Some(ordering) => Some(match ordering {
Ordering::Less => Ordering::Greater,
Ordering::Equal => Ordering::Equal,
Ordering::Greater => Ordering::Less,
}),
None => None,
},
}
}
}
impl Add for Number {
type Output = Self;
fn add(self, other: Number) -> Self {
let dtype = Ord::max(self.class(), other.class());
use NumberType as NT;
match dtype {
NT::Bool => {
let this: Boolean = self.cast_into();
(this + other.cast_into()).into()
}
NT::Complex(_) => {
let this: Complex = self.cast_into();
(this + other.cast_into()).into()
}
NT::Float(_) => {
let this: Float = self.cast_into();
(this + other.cast_into()).into()
}
NT::Int(_) => {
let this: Int = self.cast_into();
(this + other.cast_into()).into()
}
NT::UInt(_) => {
let this: UInt = self.cast_into();
(this + other.cast_into()).into()
}
NT::Number => panic!("A number instance must have a specific type, not Number"),
}
}
}
impl Mul for Number {
type Output = Self;
fn mul(self, other: Number) -> Self {
let dtype = Ord::max(self.class(), other.class());
use NumberType as NT;
match dtype {
NT::Bool => {
let this: Boolean = self.cast_into();
(this * other.cast_into()).into()
}
NT::Complex(_) => {
let this: Complex = self.cast_into();
(this * other.cast_into()).into()
}
NT::Float(_) => {
let this: Float = self.cast_into();
(this * other.cast_into()).into()
}
NT::Int(_) => {
let this: Int = self.cast_into();
(this * other.cast_into()).into()
}
NT::UInt(_) => {
let this: UInt = self.cast_into();
(this * other.cast_into()).into()
}
NT::Number => panic!("A number instance must have a specific type, not Number"),
}
}
}
impl Sub for Number {
type Output = Self;
fn sub(self, other: Number) -> Self {
let dtype = Ord::max(self.class(), other.class());
use NumberType as NT;
match dtype {
NT::Bool => {
let this: Boolean = self.cast_into();
(this - other.cast_into()).into()
}
NT::Complex(_) => {
let this: Complex = self.cast_into();
(this - other.cast_into()).into()
}
NT::Float(_) => {
let this: Float = self.cast_into();
(this - other.cast_into()).into()
}
NT::Int(_) => {
let this: Int = self.cast_into();
(this - other.cast_into()).into()
}
NT::UInt(_) => {
let this: UInt = self.cast_into();
(this - other.cast_into()).into()
}
NT::Number => panic!("A number instance must have a specific type, not Number"),
}
}
}
impl Default for Number {
fn default() -> Number {
Number::Bool(Boolean::default())
}
}
impl From<bool> for Number {
fn from(b: bool) -> Number {
Number::Bool(b.into())
}
}
impl From<u64> for Number {
fn from(u: u64) -> Number {
Number::UInt(u.into())
}
}
impl From<Boolean> for Number {
fn from(b: Boolean) -> Number {
Number::Bool(b)
}
}
impl From<Complex> for Number {
fn from(c: Complex) -> Number {
Number::Complex(c)
}
}
impl From<Float> for Number {
fn from(f: Float) -> Number {
Number::Float(f)
}
}
impl From<Int> for Number {
fn from(i: Int) -> Number {
Number::Int(i)
}
}
impl From<UInt> for Number {
fn from(u: UInt) -> Number {
Number::UInt(u)
}
}
impl CastFrom<Number> for Boolean {
fn cast_from(number: Number) -> Boolean {
if number == number.class().zero() {
Boolean(false)
} else {
Boolean(true)
}
}
}
impl CastFrom<Number> for Float {
fn cast_from(number: Number) -> Float {
use Number::*;
match number {
Bool(b) => Self::cast_from(b),
Complex(c) => Self::cast_from(c),
Float(f) => f,
Int(i) => Self::cast_from(i),
UInt(u) => Self::cast_from(u),
}
}
}
impl CastFrom<Number> for Int {
fn cast_from(number: Number) -> Int {
use Number::*;
match number {
Bool(b) => Self::cast_from(b),
Complex(c) => Self::cast_from(c),
Float(f) => Self::cast_from(f),
Int(i) => i,
UInt(u) => Self::cast_from(u),
}
}
}
impl CastFrom<Number> for UInt {
fn cast_from(number: Number) -> UInt {
use Number::*;
match number {
Bool(b) => Self::cast_from(b),
Complex(c) => Self::cast_from(c),
Float(f) => Self::cast_from(f),
Int(i) => Self::cast_from(i),
UInt(u) => u,
}
}
}
impl TryFrom<Number> for bool {
type Error = error::TCError;
fn try_from(n: Number) -> TCResult<bool> {
match n {
Number::Bool(b) => Ok(b.into()),
other => Err(error::bad_request("Expected Boolean but found", other)),
}
}
}
impl TryFrom<Number> for Boolean {
type Error = error::TCError;
fn try_from(n: Number) -> TCResult<Boolean> {
match n {
Number::Bool(b) => Ok(b),
other => Err(error::bad_request("Expected Boolean but found", other)),
}
}
}
impl TryFrom<Number> for Complex {
type Error = error::TCError;
fn try_from(n: Number) -> TCResult<Complex> {
match n {
Number::Complex(c) => Ok(c),
other => Err(error::bad_request("Expected Complex but found", other)),
}
}
}
impl TryFrom<Number> for Float {
type Error = error::TCError;
fn try_from(n: Number) -> TCResult<Float> {
match n {
Number::Float(f) => Ok(f),
other => Err(error::bad_request("Expected Float but found", other)),
}
}
}
impl TryFrom<Number> for Int {
type Error = error::TCError;
fn try_from(n: Number) -> TCResult<Int> {
match n {
Number::Int(i) => Ok(i),
other => Err(error::bad_request("Expected Int but found", other)),
}
}
}
impl TryFrom<Number> for UInt {
type Error = error::TCError;
fn try_from(n: Number) -> TCResult<UInt> {
match n {
Number::UInt(u) => Ok(u),
other => Err(error::bad_request("Expected UInt but found", other)),
}
}
}
impl TryFrom<Number> for u64 {
type Error = error::TCError;
fn try_from(n: Number) -> TCResult<u64> {
let u: UInt = n.try_into()?;
Ok(u.into())
}
}
impl Serialize for Number {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
match self {
Number::Bool(b) => b.serialize(s),
Number::Complex(c) => c.serialize(s),
Number::Float(f) => f.serialize(s),
Number::Int(i) => i.serialize(s),
Number::UInt(u) => u.serialize(s),
}
}
}
impl fmt::Debug for Number {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(self, f)
}
}
impl fmt::Display for Number {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Number::Bool(b) => write!(f, "Bool({})", b),
Number::Complex(c) => write!(f, "Complex({})", c),
Number::Float(n) => write!(f, "Float({})", n),
Number::Int(i) => write!(f, "Int({})", i),
Number::UInt(u) => write!(f, "UInt({})", u),
}
}
}
| true |
fc3e37751dc530bea81185d8f700f54c7b62fd07
|
Rust
|
isgasho/const-combinations
|
/src/lib.rs
|
UTF-8
| 3,673 | 3.84375 | 4 |
[
"Apache-2.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
//! const fn combinations iter adapter
//!
//! # Examples
//!
//! ```
//! use const_combinations::IterExt;
//!
//! let mut combinations = (1..5).combinations();
//! assert_eq!(combinations.next(), Some([1, 2, 3]));
//! assert_eq!(combinations.next(), Some([1, 2, 4]));
//! assert_eq!(combinations.next(), Some([1, 3, 4]));
//! assert_eq!(combinations.next(), Some([2, 3, 4]));
//! assert_eq!(combinations.next(), None);
//! ```
#![feature(maybe_uninit_uninit_array)]
use std::iter::Iterator;
use std::mem::MaybeUninit;
pub trait IterExt: Iterator + Clone + Sized
where
<Self as Iterator>::Item: Clone,
{
fn combinations<const N: usize>(self) -> Combinations<Self, N> {
Combinations::new(self)
}
}
impl<I> IterExt for I
where
I: Clone + Iterator,
<I as Iterator>::Item: Clone,
{
}
pub struct Combinations<I, const N: usize>
where
I: Clone + Iterator,
I::Item: Clone,
{
iter: I,
done: bool,
buffer: Vec<I::Item>,
indices: [usize; N],
first: bool,
}
impl<I, const N: usize> Combinations<I, N>
where
I: Clone + Iterator,
I::Item: Clone,
{
fn new(mut iter: I) -> Self {
// Prepare the indices.
let mut indices = [0; N];
for i in 0..N {
indices[i] = i;
}
// Prefill the buffer.
let buffer: Vec<I::Item> = iter.by_ref().take(N).collect();
let done = buffer.len() < N;
Self {
indices,
first: true,
iter,
done,
buffer,
}
}
}
impl<I, const N: usize> Iterator for Combinations<I, N>
where
I: Clone + Iterator,
I::Item: Clone,
{
type Item = [I::Item; N];
fn next(&mut self) -> Option<[<I as Iterator>::Item; N]> {
if self.first {
// Validate N never exceeds the total no. of items in the iterator
if N > self.buffer.len() {
return None;
}
self.first = false;
} else if N == 0 {
return None;
} else {
// Scan from the end, looking for an index to increment
let mut i: usize = N - 1;
// Check if we need to consume more from the iterator
if !self.done && self.indices[i] == self.buffer.len() - 1 {
match self.iter.next() {
Some(x) => self.buffer.push(x),
None => self.done = true,
}
}
while self.indices[i] == i + self.buffer.len() - N {
if i > 0 {
i -= 1;
} else {
// Reached the last combination
return None;
}
}
// Increment index, and reset the ones to its right
self.indices[i] += 1;
for j in i + 1..N {
self.indices[j] = self.indices[j - 1] + 1;
}
}
// Create result vector based on the indexes
let mut out: [MaybeUninit<I::Item>; N] = MaybeUninit::uninit_array();
self.indices.iter().enumerate().for_each(|(oi, i)| {
out[oi] = MaybeUninit::new(self.buffer[*i].clone());
});
Some(unsafe { out.as_ptr().cast::<[I::Item; N]>().read() })
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn none_on_size_too_big() {
let mut combinations = (1..2).combinations::<2>();
assert_eq!(combinations.next(), None);
}
#[test]
fn empty_arr_on_n_zero() {
let mut combinations = (1..5).combinations();
assert_eq!(combinations.next(), Some([]));
assert_eq!(combinations.next(), None);
}
}
| true |
18d39ed0c7f54969f01cfef89552ac26d6300780
|
Rust
|
nand-nor/dedelf
|
/src/header.rs
|
UTF-8
| 80,061 | 2.84375 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
use std::fs::File;
use byteorder::*;
use std::io::{Read, Seek, SeekFrom};
/* Enum needed for various functions that support runtime parsing of ELF data*/
#[derive(Clone, Debug)]
pub enum ExecHeader {
ThirtyTwo(ExecHeader32),
SixtyFour(ExecHeader64)
}
#[derive(Clone, Debug)]
pub struct ExecHeader32 {
pub e_ident: [u8; EXEC::EI_IDENT as usize],
pub e_type: u16,
pub e_machine: u16,
pub e_version: u32,
pub e_entry: u32,
pub e_phoff: u32,
pub e_shoff: u32,
pub e_flags: u32,
pub e_ehsize: u16,
pub e_phentsize: u16,
pub e_phnum: u16,
pub e_shentsize: u16,
pub e_shnum: u16,
pub e_shstrndx: u16,
}
#[derive(Clone, Debug)]
pub struct ExecHeader64 {
pub e_ident: [u8; EXEC::EI_IDENT as usize],
pub e_type: u16,
pub e_machine: u16,
pub e_version: u32,
pub e_entry: u64,
pub e_phoff: u64,
pub e_shoff: u64,
pub e_flags: u32,
pub e_ehsize: u16,
pub e_phentsize: u16,
pub e_phnum: u16,
pub e_shentsize: u16,
pub e_shnum: u16,
pub e_shstrndx: u16,
}
impl ExecHeader32{
pub fn new(ident_array: [u8; 16], etype: u16,
emach: u16, evers: u32, eentry: u32,
phoff: u32, shoff: u32, flags: u32, ehsize: u16,
pehsize: u16, phnum: u16, shent: u16,
shnum: u16, shstrndx: u16,) -> ExecHeader32{
ExecHeader32{
e_ident: ident_array,
e_type: etype,
e_machine : emach,
e_version : evers,
e_entry : eentry,
e_phoff : phoff,
e_shoff : shoff,
e_flags : flags,
e_ehsize : ehsize,
e_phentsize : pehsize,
e_phnum : phnum,
e_shentsize : shent,
e_shnum : shnum,
e_shstrndx : shstrndx,
}
}
pub fn parse_exec_header<R, B: ByteOrder>(file_ptr: &mut R)
-> Result<ExecHeader32, std::io::Error> where R: Read,{
let mut ident_array = [0; EXEC::EI_IDENT];
file_ptr.read_exact(&mut ident_array)?;
let etype = file_ptr.read_u16::<B>()?;
let emach = file_ptr.read_u16::<B>()?;
let evers = file_ptr.read_u32::<B>()?;
let eentry = file_ptr.read_u32::<B>()?;
let phoff = file_ptr.read_u32::<B>()?;
let shoff = file_ptr.read_u32::<B>()?;
let flags = file_ptr.read_u32::<B>()?;
let ehsize = file_ptr.read_u16::<B>()?;
let pehsize = file_ptr.read_u16::<B>()?;
let phnum = file_ptr.read_u16::<B>()?;
let shent = file_ptr.read_u16::<B>()?;
let shnum = file_ptr.read_u16::<B>()?;
let shstrndx = file_ptr.read_u16::<B>()?;
Ok(ExecHeader32{
e_ident: ident_array,
e_type: etype,
e_machine : emach,
e_version : evers,
e_entry : eentry,
e_phoff : phoff,
e_shoff : shoff,
e_flags : flags,
e_ehsize : ehsize,
e_phentsize : pehsize,
e_phnum : phnum,
e_shentsize : shent,
e_shnum : shnum,
e_shstrndx : shstrndx,
})
}
/*TODO -- this can be improved; just write directly to file pointer rather than intermediate vec */
pub fn write_header<B: ByteOrder>(&self, file_ptr: &mut File)-> Result<(),std::io::Error>{
for &val in &self.e_ident{
file_ptr.write_u8(val)?;
}
file_ptr.write_u16::<B>(self.e_type)?;
file_ptr.write_u16::<B>(self.e_machine)?;
file_ptr.write_u32::<B>(self.e_version)?;
file_ptr.write_u32::<B>(self.e_entry)?;
file_ptr.write_u32::<B>(self.e_phoff)?;
file_ptr.write_u32::<B>(self.e_shoff)?;
file_ptr.write_u32::<B>(self.e_flags)?;
file_ptr.write_u16::<B>(self.e_ehsize)?;
file_ptr.write_u16::<B>(self.e_phentsize)?;
file_ptr.write_u16::<B>(self.e_phnum)?;
file_ptr.write_u16::<B>(self.e_shentsize)?;
file_ptr.write_u16::<B>(self.e_shnum)?;
file_ptr.write_u16::<B>(self.e_shstrndx)?;
Ok(())
}
/*
* Note: The calling function is responsible for parsing a safe-to-downcast
* value from u64 to either u8, u16, or u32
*/
pub fn update_exec_header(&mut self, field: String,
val: u32, offset: Option<usize>)-> Result<(),std::io::Error>{
match field.as_ref() {
"e_ident" => {
if let Some(offset) = offset {
self.e_ident[offset]=val as u8
} else {
return Err(std::io::Error::new(std::io::ErrorKind::Other,
"Invalid exec header change option"))
}
},
"e_type" => self.e_type = val as u16,
"e_machine" => self.e_machine = val as u16,
"e_version" => self.e_version =val,
"e_entry" => self.e_entry = val,
"e_phoff" => self.e_phoff = val,
"e_shoff" => self.e_shoff =val,
"e_flags" => self.e_flags=val,
"e_ehsize" => self.e_ehsize=val as u16,
"e_phentsize" => self.e_phentsize=val as u16,
"e_phnum" => self.e_phnum=val as u16,
"e_shentsize" => self.e_shentsize=val as u16,
"e_shnum" => self.e_shnum=val as u16,
"e_shstrndx" => self.e_shstrndx=val as u16,
_ => return Err(std::io::Error::new(std::io::ErrorKind::Other,
"Invalid exec header change option"))
};
Ok(())
}
}
impl ExecHeader64{
pub fn new(ident_array: [u8; EXEC::EI_IDENT], etype: u16,
emach: u16, evers: u32, eentry: u64,
phoff: u64, shoff: u64, flags: u32, ehsize: u16,
pehsize: u16, phnum: u16, shent: u16,
shnum: u16, shstrndx: u16,) -> ExecHeader64 {
ExecHeader64{
e_ident: ident_array,
e_type: etype,
e_machine : emach,
e_version : evers,
e_entry : eentry,
e_phoff : phoff,
e_shoff : shoff,
e_flags : flags,
e_ehsize : ehsize,
e_phentsize : pehsize,
e_phnum : phnum,
e_shentsize : shent,
e_shnum : shnum,
e_shstrndx : shstrndx,
}
}
pub fn parse_exec_header<R,B: ByteOrder>(file_ptr: &mut R,)
-> Result<ExecHeader64, std::io::Error> where R: Read,{
let mut ident_array = [0; EXEC::EI_IDENT];
file_ptr.read_exact(&mut ident_array)?;
let etype = file_ptr.read_u16::<B>()?;
let emach = file_ptr.read_u16::<B>()?;
let evers = file_ptr.read_u32::<B>()?;
let eentry = file_ptr.read_u64::<B>()?;
let phoff = file_ptr.read_u64::<B>()?;
let shoff = file_ptr.read_u64::<B>()?;
let flags = file_ptr.read_u32::<B>()?;
let ehsize = file_ptr.read_u16::<B>()?;
let pehsize = file_ptr.read_u16::<B>()?;
let phnum = file_ptr.read_u16::<B>()?;
let shent = file_ptr.read_u16::<B>()?;
let shnum = file_ptr.read_u16::<B>()?;
let shstrndx = file_ptr.read_u16::<B>()?;
Ok(ExecHeader64{
e_ident: ident_array,
e_type: etype,
e_machine : emach,
e_version : evers,
e_entry : eentry,
e_phoff : phoff,
e_shoff : shoff,
e_flags : flags,
e_ehsize : ehsize,
e_phentsize : pehsize,
e_phnum : phnum,
e_shentsize : shent,
e_shnum : shnum,
e_shstrndx : shstrndx,
})
}
/* TODO: IMPROVE THIS, dont need the intermediate writer vec, just write directly to file pointer*/
pub fn write_header<B: ByteOrder>(&self,
file_ptr: &mut File)->Result<(),std::io::Error>{
file_ptr.seek( SeekFrom::Start(0))?;
for &val in &self.e_ident{
file_ptr.write_u8(val)?;
}
file_ptr.write_u16::<B>(self.e_type)?;
file_ptr.write_u16::<B>(self.e_machine)?;
file_ptr.write_u32::<B>(self.e_version)?;
file_ptr.write_u64::<B>(self.e_entry)?;
file_ptr.write_u64::<B>(self.e_phoff)?;
file_ptr.write_u64::<B>(self.e_shoff)?;
file_ptr.write_u32::<B>(self.e_flags)?;
file_ptr.write_u16::<B>(self.e_ehsize)?;
file_ptr.write_u16::<B>(self.e_phentsize)?;
file_ptr.write_u16::<B>(self.e_phnum)?;
file_ptr.write_u16::<B>(self.e_shentsize)?;
file_ptr.write_u16::<B>(self.e_shnum)?;
file_ptr.write_u16::<B>(self.e_shstrndx)?;
Ok(())
}
/*
* Note: The calling function is responsible for parsing a safe-to-downcast
* value from u64 to either u8, u16, or u32
*/
pub fn update_exec_header(&mut self, field: String,
val: u64, offset: Option<usize>)->Result<(),std::io::Error> {
match field.as_ref() {
"e_ident" => {
if let Some(offset) = offset {
self.e_ident[offset]=val as u8
} else{
return Err(std::io::Error::new(std::io::ErrorKind::Other,
"Invalid exec header change option"))
}
},
"e_type" => self.e_type = val as u16,
"e_machine" => self.e_machine = val as u16,
"e_version" => self.e_version =val as u32,
"e_entry" => self.e_entry = val,
"e_phoff" => self.e_phoff = val,
"e_shoff" => self.e_shoff =val,
"e_flags" => self.e_flags=val as u32,
"e_ehsize" => self.e_ehsize=val as u16,
"e_phentsize" => self.e_phentsize=val as u16,
"e_phnum" => self.e_phnum=val as u16,
"e_shentsize" => self.e_shentsize=val as u16,
"e_shnum" => self.e_shnum=val as u16,
"e_shstrndx" => self.e_shstrndx=val as u16,
_ => return Err(std::io::Error::new(std::io::ErrorKind::Other,
"Invalid exec header change option"))
};
Ok(())
}
}
#[allow(non_snake_case)]
#[derive(Clone, Debug)]
pub struct ExecutiveHeader {
pub data: EXEC::EI_DATA,
pub class: EXEC::EI_CLASS,
pub EH: ExecHeader,
}
impl ExecutiveHeader {
pub fn new<R>(file_ptr: &mut R) -> Result<ExecutiveHeader,std::io::Error>
where R: Read + Seek, {
file_ptr.seek(SeekFrom::Start(0))?;
let mut ident_array = [0; EXEC::EI_IDENT];
file_ptr.read_exact(&mut ident_array)?;
file_ptr.seek(SeekFrom::Start(0))?;
let class: EXEC::EI_CLASS = match_class( ident_array[EXEC::_EI_CLASS]);
let data: EXEC::EI_DATA = match_data(ident_array[EXEC::_EI_DATA]);
let eh_t = match class {
EXEC::EI_CLASS::ELFCLASSNONE => {
return Err(std::io::Error::new(std::io::ErrorKind::Other,
"Elf class not supported"))
},
EXEC::EI_CLASS::ELFCLASS32=> {
match data {
EXEC::EI_DATA::ELFDATANONE => {
return Err(std::io::Error::new(std::io::ErrorKind::Other,
"Elf data not supported"))
},
EXEC::EI_DATA::ELFDATA2LSB => {
let exec: ExecHeader32=
ExecHeader32::parse_exec_header::<R, LittleEndian>(file_ptr)?;
ExecHeader::ThirtyTwo(exec)
},
EXEC::EI_DATA::ELFDATA2MSB => {
let exec: ExecHeader32 =
ExecHeader32::parse_exec_header::<R, BigEndian>(file_ptr)?;
ExecHeader::ThirtyTwo(exec)
},
EXEC::EI_DATA::ELFDATAOTHER(_)=> {
return Err(std::io::Error::new(std::io::ErrorKind::Other,
"Elf data not supported"))
}
}
},
EXEC::EI_CLASS::ELFCLASS64=>{
match data {
EXEC::EI_DATA::ELFDATANONE => {
return Err(std::io::Error::new(std::io::ErrorKind::Other,
"Elf data not supported"))
},
EXEC::EI_DATA::ELFDATA2LSB => {
let exec: ExecHeader64=
ExecHeader64::parse_exec_header::<R, LittleEndian>(file_ptr)?;
ExecHeader::SixtyFour(exec)
},
EXEC::EI_DATA::ELFDATA2MSB => {
let exec: ExecHeader64 =
ExecHeader64::parse_exec_header::<R, BigEndian>(file_ptr)?;
ExecHeader::SixtyFour(exec)
},
EXEC::EI_DATA::ELFDATAOTHER(_)=> {
return Err(std::io::Error::new(std::io::ErrorKind::Other,
"Elf data not supported"))
}
}
},
EXEC::EI_CLASS::ELFCLASSOTHER(_) =>{
return Err(std::io::Error::new(std::io::ErrorKind::Other,
"Elf class not supported"))
},
};
Ok(ExecutiveHeader {
class: class,
data: data,
EH: eh_t,
})
}
/*
pub fn write_header(&self, file_ptr: &mut File ) -> Result<(),std::io::Error>{
file_ptr.seek(SeekFrom::Start(0))?;
self.write_exec_header(file_ptr)?;
Ok(())
}*/
pub fn write_exec_header(&self, file_ptr: &mut File) -> Result<(),std::io::Error>{
match &self.EH {
ExecHeader::ThirtyTwo(exec32) => {
match self.data {
EXEC::EI_DATA::ELFDATA2LSB => {
exec32.write_header::<LittleEndian>(file_ptr)
},
EXEC::EI_DATA::ELFDATA2MSB => {
exec32.write_header::<BigEndian>(file_ptr)
}
_ => {
return Err(std::io::Error::new(std::io::ErrorKind::Other,
"Elf class not supported"))
}
}
},
ExecHeader::SixtyFour(exec64)=>{
match self.data {
EXEC::EI_DATA::ELFDATA2LSB => {
exec64.write_header::<LittleEndian>(file_ptr)
},
EXEC::EI_DATA::ELFDATA2MSB => {
exec64.write_header::<BigEndian>(file_ptr)
}
_ => {
return Err(std::io::Error::new(std::io::ErrorKind::Other,
"Elf class not supported"))
}
}
},
}
}
pub fn update_sht_offset(&mut self, by_size: u64){
match &mut self.EH {
ExecHeader::ThirtyTwo(exec32) => {
exec32.e_shoff += by_size as u32
},
ExecHeader::SixtyFour(exec64)=>{
exec64.e_shoff += by_size
},
}
}
pub fn sht_offset(&self)-> SHTOffset {
match &self.EH {
ExecHeader::ThirtyTwo(exec32) => {
SHTOffset::ThirtyTwo(exec32.e_shoff)
},
ExecHeader::SixtyFour(exec64)=>{
SHTOffset::SixtyFour(exec64.e_shoff)
},
}
}
pub fn pht_offset(&self)-> PHTOffset {
match &self.EH {
ExecHeader::ThirtyTwo(exec32) => {
PHTOffset::ThirtyTwo(exec32.e_phoff)
},
ExecHeader::SixtyFour(exec64)=>{
PHTOffset::SixtyFour(exec64.e_phoff)
},
}
}
pub fn entry(&self)-> Entry {
match &self.EH {
ExecHeader::ThirtyTwo(exec32) => {
Entry::ThirtyTwo(exec32.e_entry)
},
ExecHeader::SixtyFour(exec64)=>{
Entry::SixtyFour(exec64.e_entry)
},
}
}
pub fn ph_entry_num(&self)-> u16 {
match &self.EH {
ExecHeader::ThirtyTwo(exec32) => {
exec32.e_phnum
},
ExecHeader::SixtyFour(exec64)=>{
exec64.e_phnum
},
}
}
pub fn sh_entry_num(&self)-> u16 {
match &self.EH {
ExecHeader::ThirtyTwo(exec32) => {
exec32.e_shnum
},
ExecHeader::SixtyFour(exec64)=>{
exec64.e_shnum
},
}
}
pub fn sh_entry_size(&self)-> u16 {
match &self.EH {
ExecHeader::ThirtyTwo(exec32) => {
exec32.e_shentsize
},
ExecHeader::SixtyFour(exec64)=>{
exec64.e_shentsize
},
}
}
pub fn ph_entry_size(&self)-> u16 {
match &self.EH {
ExecHeader::ThirtyTwo(exec32) => {
exec32.e_phentsize
},
ExecHeader::SixtyFour(exec64)=>{
exec64.e_phentsize
},
}
}
pub fn shstrndx(&self)-> u16 {
match &self.EH {
ExecHeader::ThirtyTwo(exec32) => {
exec32.e_shstrndx
},
ExecHeader::SixtyFour(exec64)=>{
exec64.e_shstrndx
},
}
}
//This function should only ever be called after obtaining 'safe' values for val i.e.
//should be parsed to return a u8 or u16 appropriately so that we already know
//up or downcasting is safe
pub fn update_exec_header(&mut self, field: String, val: u64, offset: Option<usize> )
-> Result<(),std::io::Error>{
match &mut self.EH {
ExecHeader::ThirtyTwo(exec32) => {
exec32.update_exec_header(field, val as u32, offset)?;
},
ExecHeader::SixtyFour(exec64) => {
exec64.update_exec_header(field, val, offset)?;
},
};
Ok(())
}
}
#[derive(Clone, Debug)]
pub enum Entry{
ThirtyTwo(u32),
SixtyFour(u64),
}
#[derive(Clone, Debug)]
pub enum SHTOffset{
ThirtyTwo(u32),
SixtyFour(u64),
}
#[derive(Clone, Debug)]
pub enum PHTOffset{
ThirtyTwo(u32),
SixtyFour(u64),
}
pub fn match_data(data: u8) -> EXEC::EI_DATA {
match data {
0 => EXEC::EI_DATA::ELFDATANONE,
1 => EXEC::EI_DATA::ELFDATA2LSB,
2 => EXEC::EI_DATA::ELFDATA2MSB,
d => EXEC::EI_DATA::ELFDATAOTHER(d),
}
}
pub fn match_class(class: u8) -> EXEC::EI_CLASS {
match class {
0 => EXEC::EI_CLASS::ELFCLASSNONE,
1 => EXEC::EI_CLASS::ELFCLASS32,
2 => EXEC::EI_CLASS::ELFCLASS64,
c => EXEC::EI_CLASS::ELFCLASSOTHER(c),
}
}
pub fn match_osabi(osabi: u8) -> EXEC::EI_OSABI {
match osabi {
0 => EXEC::EI_OSABI::ELFOSABI_NONE,
1 => EXEC::EI_OSABI::ELFOSABI_HPUX,
2 => EXEC::EI_OSABI::ELFOSABI_NETBSD,
3 => EXEC::EI_OSABI::ELFOSABI_GNU,
6 => EXEC::EI_OSABI::ELFOSABI_SOLARIS,
7 => EXEC::EI_OSABI::ELFOSABI_AIX,
8 => EXEC::EI_OSABI::ELFOSABI_IRIX,
9 => EXEC::EI_OSABI::ELFOSABI_FREEBSD,
10 => EXEC::EI_OSABI::ELFOSABI_TRU64,
11 => EXEC::EI_OSABI::ELFOSABI_MODESTO,
12 => EXEC::EI_OSABI::ELFOSABI_OPENBSD,
64 => EXEC::EI_OSABI::ELFOSABI_ARM_AEABI,
97 => EXEC::EI_OSABI::ELFOSABI_ARM,
255 => EXEC::EI_OSABI::ELFOSABI_STANDALONE,
osabi => EXEC::EI_OSABI::ELFOSABI_OTHER(osabi),
}
}
pub fn match_data_as_str(data: String)-> Result<u8, std::io::Error>{
match data.as_str(){
"ELFDATANONE" =>Ok(0), //should this be supported?
"ELFDATA2LSB" =>Ok(1),
"ELFDATA2MSB" =>Ok(2),
//ELFCLASSOTHER, //not supported
_ => return Err(std::io::Error::new(std::io::ErrorKind::Other, "Elf data not supported"))
}
}
pub fn match_class_as_str(class: String)-> Result<u8, std::io::Error>{
match class.as_str(){
"ELFCLASSNONE" =>Ok(0), //should this be supported?
"ELFCLASS32" =>Ok(1),
"ELFCLASS64" =>Ok(2),
//ELFCLASSOTHER, //not supported
_ => return Err(std::io::Error::new(std::io::ErrorKind::Other, "Elf class not supported"))
}
}
/* comments from elf.h*/
pub fn match_osabi_as_str(osabi: String)-> Result<u8, std::io::Error>{
match osabi.as_str(){
"ELFOSABI_NONE" =>Ok(0), /* UNIX System V ABI */
"ELFOSABI_SYSV" => Ok(0), /* Alias for ELFOSABI_NONE */
"ELFOSABI_HPUX" =>Ok(1), /* HP-UX */
"ELFOSABI_NETBSD" =>Ok(2), /* NetBSD. */
"ELFOSABI_GNU" =>Ok(3), /* Object uses GNU ELF extensions. */
"ELFOSABI_LINUX" => Ok(3), /* Compatibility alias for ELFOSABI_GNU */
"ELFOSABI_SOLARIS" =>Ok(6), /* Sun Solaris. */
"ELFOSABI_AIX" =>Ok(7), /* IBM AIX. */
"ELFOSABI_IRIX" =>Ok(8), /* SGI Irix. */
"ELFOSABI_FREEBSD" =>Ok(9), /* FreeBSD. */
"ELFOSABI_TRU64" =>Ok(10), /* Compaq TRU64 UNIX. */
"ELFOSABI_MODESTO" =>Ok(11), /* Novell Modesto. */
"ELFOSABI_OPENBSD" =>Ok( 12), /* OpenBSD. */
"ELFOSABI_ARM_AEABI" =>Ok(64), /* ARM EABI */
"ELFOSABI_ARM" =>Ok(97), /* ARM */
//ELFOSABI_OTHER(u8), //TODO should support 'other'?
"ELFOSABI_STANDALONE" =>Ok(255), /* Standalone (embedded) application */
_ => return Err(std::io::Error::new(std::io::ErrorKind::Other, "Elf osabi not supported"))
}
}
pub fn match_version(e_vers: u32)-> Result<EXEC::EI_VERS, std::io::Error> {
match e_vers{
0 => Ok(EXEC::EI_VERS::EV_NONE),
1 => Ok(EXEC::EI_VERS::EV_CURRENT),
_ => return Err(std::io::Error::new(std::io::ErrorKind::Other,
"Elf version not supported"))
}
}
pub fn match_version_as_str(e_vers: String)-> Result<u32, std::io::Error> {
match e_vers.as_str(){
"EV_NONE"=> Ok(0),
"EV_CURRENT"=>Ok(1),
_ => return Err(std::io::Error::new(std::io::ErrorKind::Other,
"Elf version not supported"))
}
}
pub fn match_type(etype: u16)-> Result<EXEC::EI_TYPE, std::io::Error> {
match etype {
0 => Ok(EXEC::EI_TYPE::ET_NONE),
1 => Ok(EXEC::EI_TYPE::ET_REL),
2=> Ok(EXEC::EI_TYPE::ET_EXEC),
3=> Ok(EXEC::EI_TYPE::ET_DYN),
4=> Ok(EXEC::EI_TYPE::ET_CORE),
0xfe00 => Ok(EXEC::EI_TYPE::ET_LOOS),
0xfeff=> Ok(EXEC::EI_TYPE::ET_HIOS),
0xff00=> Ok(EXEC::EI_TYPE::ET_LOPROC),
0xffff=> Ok(EXEC::EI_TYPE::ET_HIPROC),
_ => return Err(std::io::Error::new(std::io::ErrorKind::Other,
"Elf type not supported"))
}
}
pub fn match_type_as_str(etype: String)->Result<u16, std::io::Error>{
match etype.as_str() {
"ET_NONE"=> Ok(0),
"ET_REL"=> Ok(1),
"ET_EXEC"=> Ok(2),
"ET_DYN"=> Ok(3),
"ET_CORE"=> Ok(4),
"ET_LOOS"=> Ok(0xfe00),
"ET_HIOS"=> Ok(0xfeff),
"ET_LOPROC"=> Ok(0xff00),
"ET_HIPROC"=> Ok(0xffff),
_ => return Err(std::io::Error::new(std::io::ErrorKind::Other,
"Elf type not supported"))
}
}
pub fn match_mach_as_str(mach: String) -> Result<u16, std::io::Error> {
match mach.as_str(){
"EM_NONE" => Ok(0),
"EM_M32" => Ok(1), /* AT&T WE 32100 */
"EM_SPARC" => Ok(2), /*SPARC*/
"EM_386" => Ok(3), /*Intel 80386*/
"EM_68K" => Ok(4), /*Motorola 68000*/
"EM_88K" => Ok(5), /* Motorola 88000*/
// RESERVED = 6, /* Reserved for future use*/
"EM_860" => Ok(7), /*Intel 80860*/
"EM_MIPS" => Ok(8), /* MIPS I Architecture */
"EM_S370" => Ok(9), /* IBM System/370 Processor */
"EM_MIPS_RS3_LE" => Ok(10), /* MIPS RS3000 Little-endian */
//RESERVED 11-14 // /*Reserved for future use */
"EM_PARISC" => Ok(15), /*Hewlett-Packard PA-RISC */
//RESERVED 16 // /*Reserved for future use */
"EM_VPP500" => Ok(17), /*Fujitsu VPP500 */
"EM_SPARC32PLUS" => Ok(18), /*Enhanced instruction set SPARC */
"EM_960" => Ok(19), /* Intel 80960 */
"EM_PPC" => Ok(20), /* PowerPC */
"EM_PPC64" => Ok(21), /* 64-bit PowerPC */
//RESERVED 22-35 // /*Reserved for future use */
"EM_V800" => Ok(36), /* NEC V800 */
"EM_FR20" => Ok(37), /* Fujitsu FR20 */
"EM_RH32" => Ok(38), /*TRW RH-32 */
"EM_RCE" => Ok(39), /*Motorola RCE */
"EM_ARM" => Ok(40), /*Advanced RISC Machines ARM */
"EM_ALPHA" => Ok(41), /* Digital Alpha */
"EM_SH" => Ok(42), /*Hitachi SH */
"EM_SPARCV9" => Ok(43), /* SPARC Version 9 */
"EM_TRICORE" => Ok(44), /* Siemens Tricore embedded processor */
"EM_ARC" => Ok(45), /*Argonaut RISC Core, Argonaut Technologies Inc. */
"EM_H8_300" => Ok(46), /* Hitachi H8/300 */
"EM_H8_300H" => Ok(47), /* Hitachi H8/300H */
"EM_H8S" => Ok(48), /*Hitachi H8S */
"EM_H8_500" => Ok(49), /*Hitachi H8/500 */
"EM_IA_64" => Ok(50), /*Intel IA-64 processor architecture */
"EM_MIPS_X" => Ok(51), /*Stanford MIPS-X */
"EM_COLDFIRE" => Ok(52), /* Motorola ColdFire */
"EM_68HC12" => Ok(53), /*Motorola M68HC12 */
"EM_MMA" => Ok(54), /*Fujitsu MMA Multimedia Accelerator */
"EM_PCP" => Ok(55), /*Siemens PCP */
"EM_NCPU" => Ok(56), /*Sony nCPU embedded RISC processor */
"EM_NDR1" => Ok(57), /*Denso NDR1 microprocessor */
"EM_STARCORE" => Ok(58), /* Motorola Star*Core processor */
"EM_ME16" => Ok(59), /*Toyota ME16 processor */
"EM_ST100" => Ok(60), /*STMicroelectronics ST100 processor */
"EM_TINYJ" => Ok(61), /*Advanced Logic Corp. TinyJ embedded processor family */
//Reserved 62-65 /*Reserved for future use */
"EM_FX66" => Ok(66), /*Siemens FX66 microcontroller */
"EM_ST9PLUS" => Ok(67), /* STMicroelectronics ST9+ 8/16 bit microcontroller */
"EM_ST7" => Ok(68), /*STMicroelectronics ST7 8-bit microcontroller */
"EM_68HC16" => Ok(69), /* Motorola MC68HC16 Microcontroller */
"EM_68HC11" => Ok(70), /* Motorola MC68HC11 Microcontroller */
"EM_68HC08" => Ok(71), /* Motorola MC68HC08 Microcontroller */
"EM_68HC05" => Ok(72), /* Motorola MC68HC05 Microcontroller */
"EM_SVX" => Ok(73), /*Silicon Graphics SVx */
"EM_ST19" => Ok(74), /* STMicroelectronics ST19 8-bit microcontroller */
"EM_VAX" => Ok(75), /* Digital VAX */
"EM_CRIS" => Ok(76), /* Axis Communications 32-bit embedded processor */
"EM_JAVELIN" => Ok(77), /*Infineon Technologies 32-bit embedded processor */
"EM_FIREPATH" => Ok(78), /* Element 14 64-bit DSP Processor */
"EM_ZSP" => Ok(79), /*LSI Logic 16-bit DSP Processor */
"EM_MMIX" => Ok(80), /* Donald Knuth's educational 64-bit processor */
"EM_HUANY" => Ok(81), /* Harvard University machine-independent object files */
"EM_PRISM" => Ok(82), /* SiTera Prism */
"EM_AVR" => Ok(83), /* Atmel AVR 8-bit microcontroller */
"EM_FR30" => Ok(84), /* Fujitsu FR30 */
"EM_D10V" => Ok(85), /* Mitsubishi D10V */
"EM_D30V" => Ok(86), /* Mitsubishi D30V */
"EM_V850" => Ok(87), /* NEC v850 */
"EM_M32R" => Ok(88), /* Mitsubishi M32R */
"EM_MN10300" => Ok(89), /* Matsushita MN10300 */
"EM_MN10200" => Ok(90), /* Matsushita MN10200 */
"EM_PJ" => Ok(91), /* picoJava */
"EM_OPENRISC" => Ok(92), /* OpenRISC 32-bit embedded processor */
"EM_ARC_COMPACT" => Ok(93), /* ARC International ARCompact */
"EM_XTENSA" => Ok(94), /* Tensilica Xtensa Architecture */
"EM_VIDEOCORE" => Ok(95), /* Alphamosaic VideoCore */
"EM_TMM_GPP" => Ok(96), /* Thompson Multimedia General Purpose Proc */
"EM_NS32K" => Ok(97), /* National Semi. 32000 */
"EM_TPC" => Ok(98), /* Tenor Network TPC */
"EM_SNP1K" => Ok(99), /* Trebia SNP 1000 */
"EM_ST200" => Ok(100), /* STMicroelectronics ST200 */
"EM_IP2K" => Ok(101), /* Ubicom IP2xxx */
"EM_MAX" => Ok(102), /* MAX processor */
"EM_CR" => Ok(103), /* National Semi. CompactRISC */
"EM_F2MC16" => Ok(104), /* Fujitsu F2MC16 */
"EM_MSP430" => Ok(105), /* Texas Instruments msp430 */
"EM_BLACKFIN" => Ok(106), /* Analog Devices Blackfin DSP */
"EM_SE_C33" => Ok(107), /* Seiko Epson S1C33 family */
"EM_SEP" => Ok(108), /* Sharp embedded microprocessor */
"EM_ARCA" => Ok(109), /* Arca RISC */
"EM_UNICORE" => Ok(110), /* PKU-Unity & MPRC Peking Uni. mc series */
"EM_EXCESS" => Ok(111), /* eXcess configurable cpu */
"EM_DXP" => Ok(112), /* Icera Semi. Deep Execution Processor */
"EM_ALTERA_NIOS2" => Ok(113), /* Altera Nios II */
"EM_CRX" => Ok(114), /* National Semi. CompactRISC CRX */
"EM_XGATE" => Ok(115), /* Motorola XGATE */
"EM_C166" => Ok(116), /* Infineon C16x/XC16x */
"EM_M16C" => Ok(117), /* Renesas M16C */
"EM_DSPIC30F" => Ok(118), /* Microchip Technology dsPIC30F */
"EM_CE" => Ok(119), /* Freescale Communication Engine RISC */
"EM_M32C" => Ok(120), /* Renesas M32C */
/* reserved 121-130 */
"EM_TSK3000" => Ok(131), /* Altium TSK3000 */
"EM_RS08" => Ok(132), /* Freescale RS08 */
"EM_SHARC" => Ok(133), /* Analog Devices SHARC family */
"EM_ECOG2" => Ok(134), /* Cyan Technology eCOG2 */
"EM_SCORE7" => Ok(135), /* Sunplus S+core7 RISC */
"EM_DSP24" => Ok(136), /* New Japan Radio (NJR) 24-bit DSP */
"EM_VIDEOCORE3" => Ok(137), /* Broadcom VideoCore III */
"EM_LATTICEMICO32" => Ok(138), /* RISC for Lattice FPGA */
"EM_SE_C17" => Ok(139), /* Seiko Epson C17 */
"EM_TI_C6000" => Ok(140), /* Texas Instruments TMS320C6000 DSP */
"EM_TI_C2000" => Ok(141), /* Texas Instruments TMS320C2000 DSP */
"EM_TI_C5500" => Ok(142), /* Texas Instruments TMS320C55x DSP */
"EM_TI_ARP32" => Ok(143), /* Texas Instruments App. Specific RISC */
"EM_TI_PRU" => Ok(144), /* Texas Instruments Prog. Realtime Unit */
/* reserved 145-159 */
"EM_MMDSP_PLUS" => Ok(160), /* STMicroelectronics 64bit VLIW DSP */
"EM_CYPRESS_M8C" => Ok(161), /* Cypress M8C */
"EM_R32C" => Ok(162), /* Renesas R32C */
"EM_TRIMEDIA" => Ok(163), /* NXP Semi. TriMedia */
"EM_QDSP6" => Ok(164), /* QUALCOMM DSP6 */
"EM_8051" => Ok(165), /* Intel 8051 and variants */
"EM_STXP7X" => Ok(166), /* STMicroelectronics STxP7x */
"EM_NDS32" => Ok(167), /* Andes Tech. compact code emb. RISC */
"EM_ECOG1X" => Ok(168), /* Cyan Technology eCOG1X */
"EM_MAXQ30" => Ok(169), /* Dallas Semi. MAXQ30 mc */
"EM_XIMO16" => Ok(170), /* New Japan Radio (NJR) 16-bit DSP */
"EM_MANIK" => Ok(171), /* M2000 Reconfigurable RISC */
"EM_CRAYNV2" => Ok(172), /* Cray NV2 vector architecture */
"EM_RX" => Ok(173), /* Renesas RX */
"EM_METAG" => Ok(174), /* Imagination Tech. META */
"EM_MCST_ELBRUS" => Ok(175), /* MCST Elbrus */
"EM_ECOG16" => Ok(176), /* Cyan Technology eCOG16 */
"EM_CR16" => Ok(177), /* National Semi. CompactRISC CR16 */
"EM_ETPU" => Ok(178), /* Freescale Extended Time Processing Unit */
"EM_SLE9X" => Ok(179), /* Infineon Tech. SLE9X */
"EM_L10M" => Ok(180), /* Intel L10M */
"EM_K10M" => Ok(181), /* Intel K10M */
/* reserved 182 */
"EM_AARCH64" => Ok(183), /* ARM AARCH64 */
/* reserved 184 */
"EM_AVR32" => Ok(185), /* Amtel 32-bit microprocessor */
"EM_STM8" => Ok(186), /* STMicroelectronics STM8 */
"EM_TILE64" => Ok(187), /* Tileta TILE64 */
"EM_TILEPRO" => Ok(188), /* Tilera TILEPro */
"EM_MICROBLAZE" => Ok(189), /* Xilinx MicroBlaze */
"EM_CUDA" => Ok(190), /* NVIDIA CUDA */
"EM_TILEGX" => Ok(191), /* Tilera TILE-Gx */
"EM_CLOUDSHIELD" => Ok(192), /* CloudShield */
"EM_COREA_1ST" => Ok(193), /* KIPO-KAIST Core-A 1st gen. */
"EM_COREA_2ND" => Ok(194), /* KIPO-KAIST Core-A 2nd gen. */
"EM_ARC_COMPACT2" => Ok(195), /* Synopsys ARCompact V2 */
"EM_OPEN8" => Ok(196), /* Open8 RISC */
"EM_RL78" => Ok(197), /* Renesas RL78 */
"EM_VIDEOCORE5" => Ok(198), /* Broadcom VideoCore V */
"EM_78KOR" => Ok(199), /* Renesas 78KOR */
"EM_56800EX" => Ok(200), /* Freescale 56800EX DSC */
"EM_BA1" => Ok(201), /* Beyond BA1 */
"EM_BA2" => Ok(202), /* Beyond BA2 */
"EM_XCORE" => Ok(203), /* XMOS xCORE */
"EM_MCHP_PIC" => Ok(204), /* Microchip 8-bit PIC(r) */
/* reserved 205-209 */
"EM_KM32" => Ok(210), /* KM211 KM32 */
"EM_KMX32" => Ok(211), /* KM211 KMX32 */
"EM_EMX16" => Ok(212), /* KM211 KMX16 */
"EM_EMX8" => Ok(213), /* KM211 KMX8 */
"EM_KVARC" => Ok(214), /* KM211 KVARC */
"EM_CDP" => Ok(215), /* Paneve CDP */
"EM_COGE" => Ok(216), /* Cognitive Smart Memory Processor */
"EM_COOL" => Ok(217), /* Bluechip CoolEngine */
"EM_NORC" => Ok(218), /* Nanoradio Optimized RISC */
"EM_CSR_KALIMBA" => Ok(219), /* CSR Kalimba */
"EM_Z80" => Ok(220), /* Zilog Z80 */
"EM_VISIUM" => Ok(221), /* Controls and Data Services VISIUMcore */
"EM_FT32" => Ok(222), /* FTDI Chip FT32 */
"EM_MOXIE" => Ok(223), /* Moxie processor */
"EM_AMDGPU" => Ok(224), /* AMD GPU */
/* reserved 225-242 */
"EM_RISCV" => Ok(243), /* RISC-V */
"EM_BPF" => Ok(247), /* Linux BPF -- in-kernel virtual machine */
"EM_CSKY" => Ok(252), /* C-SKY */
"EM_NUM" => Ok(253),
/* Old spellings/synonyms. */
"EM_ARC_A5" => Ok(93),
/* If it is necessary to assign new unofficial EM_* values, please
pick large random numbers (0x8523, 0xa7f2, etc.) to minimize the
chances of collision with official or non-GNU unofficial values. */
//EM_ALPHA = 0x9026,
_ => return Err(std::io::Error::new(std::io::ErrorKind::Other, "Elf mach not supported"))
}
}
//TODO check that all machine options are represented
/*comments from elf.h*/
pub fn match_mach(mach: u16) -> Result<EXEC::EI_MACH, std::io::Error> {
match mach {
0=> Ok(EXEC::EI_MACH::EM_NONE ),
1=> Ok(EXEC::EI_MACH::EM_M32 ), // AT&T WE 32100
2=> Ok(EXEC::EI_MACH::EM_SPARC ), //SPARC
3=> Ok(EXEC::EI_MACH::EM_386 ), //Intel 80386
4=> Ok(EXEC::EI_MACH::EM_68K ), //Motorola 68000
5=> Ok(EXEC::EI_MACH::EM_88K ), // Motorola 88000
// RESERVED 6 // Reserved for future use
7=> Ok(EXEC::EI_MACH::EM_860 ), //Intel 80860
8=> Ok(EXEC::EI_MACH::EM_MIPS ), // MIPS I Architecture
9=> Ok(EXEC::EI_MACH::EM_S370 ), // IBM System/370 Processor
10=> Ok(EXEC::EI_MACH::EM_MIPS_RS3_LE ), // MIPS RS3000 Little-endian
//RESERVED 11-14 // Reserved for future use
15=> Ok(EXEC::EI_MACH::EM_PARISC ), //Hewlett-Packard PA-RISC
//RESERVED 16 // Reserved for future use
17=> Ok(EXEC::EI_MACH::EM_VPP500 ), //Fujitsu VPP500
18=> Ok(EXEC::EI_MACH::EM_SPARC32PLUS ), //Enhanced instruction set SPARC
19=> Ok(EXEC::EI_MACH::EM_960 ), // Intel 80960
20=> Ok(EXEC::EI_MACH::EM_PPC ), // PowerPC
21=> Ok(EXEC::EI_MACH::EM_PPC64 ), // 64-bit PowerPC
//RESERVED 22-35 // Reserved for future use
36=> Ok(EXEC::EI_MACH::EM_V800 ), // NEC V800
37=> Ok(EXEC::EI_MACH::EM_FR20 ), // Fujitsu FR20
38=> Ok(EXEC::EI_MACH::EM_RH32 ), //TRW RH-32
39=> Ok(EXEC::EI_MACH::EM_RCE ), //Motorola RCE
40=> Ok(EXEC::EI_MACH::EM_ARM ), //Advanced RISC Machines ARM
41=> Ok(EXEC::EI_MACH::EM_ALPHA ), // Digital Alpha
42=> Ok(EXEC::EI_MACH::EM_SH ), //Hitachi SH
43=> Ok(EXEC::EI_MACH::EM_SPARCV9 ), // SPARC Version 9
44=> Ok(EXEC::EI_MACH::EM_TRICORE ), // Siemens Tricore embedded processor
45=> Ok(EXEC::EI_MACH::EM_ARC), //Argonaut RISC Core, Argonaut Technologies Inc.
46=> Ok(EXEC::EI_MACH::EM_H8_300 ), // Hitachi H8/300
47=> Ok(EXEC::EI_MACH::EM_H8_300H ), // Hitachi H8/300H
48=> Ok(EXEC::EI_MACH::EM_H8S ), //Hitachi H8S
49=> Ok(EXEC::EI_MACH::EM_H8_500 ), //Hitachi H8/500
50=> Ok(EXEC::EI_MACH::EM_IA_64 ), //Intel IA-64 processor architecture
51=> Ok(EXEC::EI_MACH::EM_MIPS_X ), //Stanford MIPS-X
52=> Ok(EXEC::EI_MACH::EM_COLDFIRE ), // Motorola ColdFire
53=> Ok(EXEC::EI_MACH::EM_68HC12 ), //Motorola M68HC12
54=> Ok(EXEC::EI_MACH::EM_MMA), //Fujitsu MMA Multimedia Accelerator
55=> Ok(EXEC::EI_MACH::EM_PCP ), //Siemens PCP
56=> Ok(EXEC::EI_MACH::EM_NCPU ), //Sony nCPU embedded RISC processor
57=> Ok(EXEC::EI_MACH::EM_NDR1 ), //Denso NDR1 microprocessor
58=> Ok(EXEC::EI_MACH::EM_STARCORE ), // Motorola Star*Core processor
59=> Ok(EXEC::EI_MACH::EM_ME16 ), //Toyota ME16 processor
60=> Ok(EXEC::EI_MACH::EM_ST100 ), //STMicroelectronics ST100 processor
61=> Ok(EXEC::EI_MACH::EM_TINYJ ), //Advanced Logic Corp. TinyJ embedded processor family
//Reserved 62-65 //Reserved for future use
66=> Ok(EXEC::EI_MACH::EM_FX66 ), //Siemens FX66 microcontroller
67=> Ok(EXEC::EI_MACH::EM_ST9PLUS ), // STMicroelectronics ST9+ 8/16 bit microcontroller
68=> Ok(EXEC::EI_MACH::EM_ST7 ), //STMicroelectronics ST7 8-bit microcontroller
69=> Ok(EXEC::EI_MACH::EM_68HC16 ), // Motorola MC68HC16 Microcontroller
70=> Ok(EXEC::EI_MACH::EM_68HC11 ), // Motorola MC68HC11 Microcontroller
71=> Ok(EXEC::EI_MACH::EM_68HC08 ), // Motorola MC68HC08 Microcontroller
72=> Ok(EXEC::EI_MACH::EM_68HC05 ), // Motorola MC68HC05 Microcontroller
73=> Ok(EXEC::EI_MACH::EM_SVX ), //Silicon Graphics SVx
74=> Ok(EXEC::EI_MACH::EM_ST19 ), // STMicroelectronics ST19 8-bit microcontroller
75=> Ok(EXEC::EI_MACH::EM_VAX ), // Digital VAX
76=> Ok(EXEC::EI_MACH::EM_CRIS ), // Axis Communications 32-bit embedded processor
77=> Ok(EXEC::EI_MACH::EM_JAVELIN ), //Infineon Technologies 32-bit embedded processor
78=> Ok(EXEC::EI_MACH::EM_FIREPATH ), // Element 14 64-bit DSP Processor
79=> Ok(EXEC::EI_MACH::EM_ZSP ), //LSI Logic 16-bit DSP Processor
80=> Ok(EXEC::EI_MACH::EM_MMIX ), // Donald Knuth's educational 64-bit processor
81=> Ok(EXEC::EI_MACH::EM_HUANY ), // Harvard University machine-independent object files
82=> Ok(EXEC::EI_MACH::EM_PRISM ), // SiTera Prism
83=> Ok(EXEC::EI_MACH::EM_AVR ), /* Atmel AVR 8-bit microcontroller */
84=> Ok(EXEC::EI_MACH::EM_FR30 ), /* Fujitsu FR30 */
85=> Ok(EXEC::EI_MACH::EM_D10V ), /* Mitsubishi D10V */
86=> Ok(EXEC::EI_MACH::EM_D30V ), /* Mitsubishi D30V */
87=> Ok(EXEC::EI_MACH::EM_V850 ), /* NEC v850 */
88=> Ok(EXEC::EI_MACH::EM_M32R), /* Mitsubishi M32R */
89=> Ok(EXEC::EI_MACH::EM_MN10300 ), /* Matsushita MN10300 */
90=> Ok(EXEC::EI_MACH::EM_MN10200 ), /* Matsushita MN10200 */
91=> Ok(EXEC::EI_MACH::EM_PJ ), /* picoJava */
92=> Ok(EXEC::EI_MACH::EM_OPENRISC ), /* OpenRISC 32-bit embedded processor */
93=> Ok(EXEC::EI_MACH::EM_ARC_COMPACT ), /* ARC International ARCompact */
94=> Ok(EXEC::EI_MACH::EM_XTENSA ), /* Tensilica Xtensa Architecture */
95=> Ok(EXEC::EI_MACH::EM_VIDEOCORE ), /* Alphamosaic VideoCore */
96=> Ok(EXEC::EI_MACH::EM_TMM_GPP ), /* Thompson Multimedia General Purpose Proc */
97=> Ok(EXEC::EI_MACH::EM_NS32K), /* National Semi. 32000 */
98=> Ok(EXEC::EI_MACH::EM_TPC ), /* Tenor Network TPC */
99=> Ok(EXEC::EI_MACH::EM_SNP1K ), /* Trebia SNP 1000 */
100=> Ok(EXEC::EI_MACH::EM_ST200 ), /* STMicroelectronics ST200 */
101=> Ok(EXEC::EI_MACH::EM_IP2K ), /* Ubicom IP2xxx */
102=> Ok(EXEC::EI_MACH::EM_MAX ), /* MAX processor */
103=> Ok(EXEC::EI_MACH::EM_CR ), /* National Semi. CompactRISC */
104=> Ok(EXEC::EI_MACH::EM_F2MC16 ), /* Fujitsu F2MC16 */
105=> Ok(EXEC::EI_MACH::EM_MSP430 ), /* Texas Instruments msp430 */
106=> Ok(EXEC::EI_MACH::EM_BLACKFIN ), /* Analog Devices Blackfin DSP */
107=> Ok(EXEC::EI_MACH::EM_SE_C33 ), /* Seiko Epson S1C33 family */
108=> Ok(EXEC::EI_MACH::EM_SEP ), /* Sharp embedded microprocessor */
109=> Ok(EXEC::EI_MACH::EM_ARCA ), /* Arca RISC */
110=> Ok(EXEC::EI_MACH::EM_UNICORE ), /* PKU-Unity & MPRC Peking Uni. mc series */
111=> Ok(EXEC::EI_MACH::EM_EXCESS ), /* eXcess configurable cpu */
112=> Ok(EXEC::EI_MACH::EM_DXP ), /* Icera Semi. Deep Execution Processor */
113 => Ok(EXEC::EI_MACH::EM_ALTERA_NIOS2 ),/* Altera Nios II */
114=> Ok(EXEC::EI_MACH::EM_CRX ), /* National Semi. CompactRISC CRX */
115=> Ok(EXEC::EI_MACH::EM_XGATE ), /* Motorola XGATE */
116=> Ok(EXEC::EI_MACH::EM_C166 ), /* Infineon C16x/XC16x */
117=> Ok(EXEC::EI_MACH::EM_M16C ), /* Renesas M16C */
118=> Ok(EXEC::EI_MACH::EM_DSPIC30F ), /* Microchip Technology dsPIC30F */
119=> Ok(EXEC::EI_MACH::EM_CE ), /* Freescale Communication Engine RISC */
120=> Ok(EXEC::EI_MACH::EM_M32C ), /* Renesas M32C */
/* reserved 121-130 */
131=> Ok(EXEC::EI_MACH::EM_TSK3000 ), /* Altium TSK3000 */
132=> Ok(EXEC::EI_MACH::EM_RS08 ), /* Freescale RS08 */
133=> Ok(EXEC::EI_MACH::EM_SHARC ), /* Analog Devices SHARC family */
134=> Ok(EXEC::EI_MACH::EM_ECOG2 ), /* Cyan Technology eCOG2 */
135=> Ok(EXEC::EI_MACH::EM_SCORE7 ), /* Sunplus S+core7 RISC */
136=> Ok(EXEC::EI_MACH::EM_DSP24 ), /* New Japan Radio (NJR) 24-bit DSP */
137=> Ok(EXEC::EI_MACH::EM_VIDEOCORE3 ), /* Broadcom VideoCore III */
138=> Ok(EXEC:: EI_MACH::EM_LATTICEMICO32 ), /* RISC for Lattice FPGA */
139=> Ok(EXEC::EI_MACH::EM_SE_C17), /* Seiko Epson C17 */
140=> Ok(EXEC::EI_MACH::EM_TI_C6000 ), /* Texas Instruments TMS320C6000 DSP */
141=> Ok(EXEC::EI_MACH::EM_TI_C2000 ), /* Texas Instruments TMS320C2000 DSP */
142=> Ok(EXEC::EI_MACH::EM_TI_C5500 ), /* Texas Instruments TMS320C55x DSP */
143=> Ok(EXEC::EI_MACH::EM_TI_ARP32 ), /* Texas Instruments App. Specific RISC */
144=> Ok(EXEC::EI_MACH::EM_TI_PRU ), /* Texas Instruments Prog. Realtime Unit */
/* reserved 145-159 */
160=> Ok(EXEC::EI_MACH::EM_MMDSP_PLUS ), /* STMicroelectronics 64bit VLIW DSP */
161=> Ok(EXEC::EI_MACH::EM_CYPRESS_M8C ), /* Cypress M8C */
162=> Ok(EXEC::EI_MACH::EM_R32C ), /* Renesas R32C */
163=> Ok(EXEC::EI_MACH::EM_TRIMEDIA ), /* NXP Semi. TriMedia */
164=> Ok(EXEC::EI_MACH::EM_QDSP6 ), /* QUALCOMM DSP6 */
165=> Ok(EXEC::EI_MACH::EM_8051 ), /* Intel 8051 and variants */
166=> Ok(EXEC::EI_MACH::EM_STXP7X ), /* STMicroelectronics STxP7x */
167=> Ok(EXEC::EI_MACH::EM_NDS32 ), /* Andes Tech. compact code emb. RISC */
168=> Ok(EXEC::EI_MACH::EM_ECOG1X ), /* Cyan Technology eCOG1X */
169=> Ok(EXEC::EI_MACH::EM_MAXQ30 ), /* Dallas Semi. MAXQ30 mc */
170=> Ok(EXEC::EI_MACH::EM_XIMO16 ), /* New Japan Radio (NJR) 16-bit DSP */
171=> Ok(EXEC::EI_MACH::EM_MANIK ), /* M2000 Reconfigurable RISC */
172=> Ok(EXEC::EI_MACH::EM_CRAYNV2 ), /* Cray NV2 vector architecture */
173=> Ok(EXEC::EI_MACH::EM_RX ), /* Renesas RX */
174=> Ok(EXEC::EI_MACH::EM_METAG ), /* Imagination Tech. META */
175=> Ok(EXEC::EI_MACH::EM_MCST_ELBRUS ), /* MCST Elbrus */
176=> Ok(EXEC::EI_MACH::EM_ECOG16 ), /* Cyan Technology eCOG16 */
177=> Ok(EXEC::EI_MACH::EM_CR16 ), /* National Semi. CompactRISC CR16 */
178=> Ok(EXEC::EI_MACH::EM_ETPU ), /* Freescale Extended Time Processing Unit */
179=> Ok(EXEC::EI_MACH::EM_SLE9X ), /* Infineon Tech. SLE9X */
180=> Ok(EXEC::EI_MACH::EM_L10M ), /* Intel L10M */
181=> Ok(EXEC::EI_MACH::EM_K10M ), /* Intel K10M */
/* reserved 182 */
183=> Ok(EXEC::EI_MACH::EM_AARCH64 ), /* ARM AARCH64 */
/* reserved 184 */
185=> Ok(EXEC::EI_MACH::EM_AVR32 ), /* Amtel 32-bit microprocessor */
186=> Ok(EXEC::EI_MACH::EM_STM8 ), /* STMicroelectronics STM8 */
187=> Ok(EXEC::EI_MACH::EM_TILE64), /* Tileta TILE64 */
188=> Ok(EXEC::EI_MACH::EM_TILEPRO ), /* Tilera TILEPro */
189=> Ok(EXEC::EI_MACH::EM_MICROBLAZE ), /* Xilinx MicroBlaze */
190=> Ok(EXEC::EI_MACH::EM_CUDA ), /* NVIDIA CUDA */
191=> Ok(EXEC::EI_MACH::EM_TILEGX ), /* Tilera TILE-Gx */
192=> Ok(EXEC::EI_MACH::EM_CLOUDSHIELD ), /* CloudShield */
193=> Ok(EXEC::EI_MACH::EM_COREA_1ST ), /* KIPO-KAIST Core-A 1st gen. */
194=> Ok(EXEC::EI_MACH::EM_COREA_2ND ), /* KIPO-KAIST Core-A 2nd gen. */
195=> Ok(EXEC::EI_MACH::EM_ARC_COMPACT2 ), /* Synopsys ARCompact V2 */
196=> Ok(EXEC::EI_MACH::EM_OPEN8 ), /* Open8 RISC */
197=> Ok(EXEC::EI_MACH::EM_RL78 ), /* Renesas RL78 */
198=> Ok(EXEC::EI_MACH::EM_VIDEOCORE5 ), /* Broadcom VideoCore V */
199=> Ok(EXEC::EI_MACH::EM_78KOR ), /* Renesas 78KOR */
200=> Ok(EXEC::EI_MACH::EM_56800EX ), /* Freescale 56800EX DSC */
201=> Ok(EXEC::EI_MACH::EM_BA1), /* Beyond BA1 */
202=> Ok(EXEC::EI_MACH::EM_BA2), /* Beyond BA2 */
203=> Ok(EXEC::EI_MACH::EM_XCORE), /* XMOS xCORE */
204=> Ok(EXEC::EI_MACH::EM_MCHP_PIC), /* Microchip 8-bit PIC(r) */
/* reserved 205-209 */
210=> Ok(EXEC::EI_MACH::EM_KM32), /* KM211 KM32 */
211=> Ok(EXEC::EI_MACH::EM_KMX32), /* KM211 KMX32 */
212=> Ok(EXEC::EI_MACH::EM_EMX16), /* KM211 KMX16 */
213=> Ok(EXEC::EI_MACH::EM_EMX8), /* KM211 KMX8 */
214=> Ok(EXEC::EI_MACH::EM_KVARC), /* KM211 KVARC */
215=> Ok(EXEC::EI_MACH::EM_CDP), /* Paneve CDP */
216=> Ok(EXEC::EI_MACH::EM_COGE), /* Cognitive Smart Memory Processor */
217=> Ok(EXEC::EI_MACH::EM_COOL), /* Bluechip CoolEngine */
218=> Ok(EXEC::EI_MACH::EM_NORC), /* Nanoradio Optimized RISC */
219=> Ok(EXEC::EI_MACH::EM_CSR_KALIMBA), /* CSR Kalimba */
220=> Ok(EXEC::EI_MACH::EM_Z80), /* Zilog Z80 */
221=> Ok(EXEC::EI_MACH::EM_VISIUM), /* Controls and Data Services VISIUMcore */
222=> Ok(EXEC::EI_MACH::EM_FT32), /* FTDI Chip FT32 */
223=> Ok(EXEC::EI_MACH::EM_MOXIE), /* Moxie processor */
224=> Ok(EXEC::EI_MACH::EM_AMDGPU), /* AMD GPU */
/* reserved 225-242 */
243=> Ok(EXEC::EI_MACH::EM_RISCV), /* RISC-V */
/*244-246*/
247=> Ok(EXEC::EI_MACH::EM_BPF), /* Linux BPF -- in-kernel virtual machine */
/*248-251*/
252=> Ok(EXEC::EI_MACH::EM_CSKY), /* C-SKY */
253 => Ok(EXEC::EI_MACH::EM_NUM),
/* Old spellings/synonyms. */
// EM_ARC_A5 = EM_ARC_COMPACT,
/* If it is necessary to assign new unofficial EM_* values, please
pick large random numbers (0x8523, 0xa7f2, etc.) to minimize the
chances of collision with official or non-GNU unofficial values. */
// EM_ALPHA => 0x9026,
_ => return Err(std::io::Error::new(std::io::ErrorKind::Other, "Elf mach not supported"))
}
}
#[allow(non_camel_case_types, non_snake_case)]
pub(super) mod EXEC {
pub const _EI_MAG0: usize = 0;
pub const _EI_MAG1: usize = 1;
pub const _EI_MAG2: usize = 2;
pub const _EI_MAG3: usize = 3;
pub const _EI_CLASS: usize = 4;
pub const _EI_DATA: usize = 5;
pub const _EI_VERSION: usize = 6;
pub const _EI_OSABI: usize = 7;
pub const _EI_ABIVERSION: usize = 8;
pub const _EI_PAD: usize = 9;
pub const _EI_NIDENT: usize = 16;
pub const EI_IDENT:usize = 16;
#[repr(u16)]
#[allow(non_camel_case_types)]
pub enum EI_TYPE {
ET_NONE = 0,
ET_REL = 1,
ET_EXEC = 2,
ET_DYN = 3,
ET_CORE = 4,
ET_LOOS = 0xfe00,
ET_HIOS = 0xfeff,
ET_LOPROC = 0xff00,
ET_HIPROC = 0xffff,
}
impl EI_TYPE {
pub fn as_u16(&self) -> u16 {
match self {
EI_TYPE::ET_NONE => 0,
EI_TYPE::ET_REL => 1,
EI_TYPE::ET_EXEC => 2,
EI_TYPE::ET_DYN => 3,
EI_TYPE::ET_CORE => 4,
EI_TYPE::ET_LOOS => 0xfe00,
EI_TYPE::ET_HIOS => 0xfeff,
EI_TYPE::ET_LOPROC => 0xff00,
EI_TYPE::ET_HIPROC => 0xffff,
}
}
}
#[repr(u16)]
#[allow(non_camel_case_types)]
pub enum EI_MACH {
EM_NONE = 0,
EM_M32 = 1, // AT&T WE 32100
EM_SPARC = 2, //SPARC
EM_386 = 3, //Intel 80386
EM_68K = 4, //Motorola 68000
EM_88K = 5, // Motorola 88000
// RESERVED = 6, // Reserved for future use
EM_860 = 7, //Intel 80860
EM_MIPS = 8, // MIPS I Architecture
EM_S370 = 9, // IBM System/370 Processor
EM_MIPS_RS3_LE = 10, // MIPS RS3000 Little-endian
//RESERVED 11-14 // Reserved for future use
EM_PARISC = 15, //Hewlett-Packard PA-RISC
//RESERVED 16 // Reserved for future use
EM_VPP500 = 17, //Fujitsu VPP500
EM_SPARC32PLUS = 18, //Enhanced instruction set SPARC
EM_960 = 19, // Intel 80960
EM_PPC = 20, // PowerPC
EM_PPC64 = 21, // 64-bit PowerPC
//RESERVED 22-35 // Reserved for future use
EM_V800 = 36, // NEC V800
EM_FR20 = 37, // Fujitsu FR20
EM_RH32 = 38, //TRW RH-32
EM_RCE = 39, //Motorola RCE
EM_ARM = 40, //Advanced RISC Machines ARM
EM_ALPHA = 41, // Digital Alpha
EM_SH = 42, //Hitachi SH
EM_SPARCV9 = 43, // SPARC Version 9
EM_TRICORE = 44, // Siemens Tricore embedded processor
EM_ARC = 45, //Argonaut RISC Core, Argonaut Technologies Inc.
EM_H8_300 = 46, // Hitachi H8/300
EM_H8_300H = 47, // Hitachi H8/300H
EM_H8S = 48, //Hitachi H8S
EM_H8_500 = 49, //Hitachi H8/500
EM_IA_64 = 50, //Intel IA-64 processor architecture
EM_MIPS_X = 51, //Stanford MIPS-X
EM_COLDFIRE = 52, // Motorola ColdFire
EM_68HC12 = 53, //Motorola M68HC12
EM_MMA = 54, //Fujitsu MMA Multimedia Accelerator
EM_PCP = 55, //Siemens PCP
EM_NCPU = 56, //Sony nCPU embedded RISC processor
EM_NDR1 = 57, //Denso NDR1 microprocessor
EM_STARCORE = 58, // Motorola Star*Core processor
EM_ME16 = 59, //Toyota ME16 processor
EM_ST100 = 60, //STMicroelectronics ST100 processor
EM_TINYJ = 61, //Advanced Logic Corp. TinyJ embedded processor family
//Reserved 62-65 //Reserved for future use
EM_FX66 = 66, //Siemens FX66 microcontroller
EM_ST9PLUS = 67, // STMicroelectronics ST9+ 8/16 bit microcontroller
EM_ST7 = 68, //STMicroelectronics ST7 8-bit microcontroller
EM_68HC16 = 69, // Motorola MC68HC16 Microcontroller
EM_68HC11 = 70, // Motorola MC68HC11 Microcontroller
EM_68HC08 = 71, // Motorola MC68HC08 Microcontroller
EM_68HC05 = 72, // Motorola MC68HC05 Microcontroller
EM_SVX = 73, //Silicon Graphics SVx
EM_ST19 = 74, // STMicroelectronics ST19 8-bit microcontroller
EM_VAX = 75, // Digital VAX
EM_CRIS = 76, // Axis Communications 32-bit embedded processor
EM_JAVELIN = 77, //Infineon Technologies 32-bit embedded processor
EM_FIREPATH = 78, // Element 14 64-bit DSP Processor
EM_ZSP = 79, //LSI Logic 16-bit DSP Processor
EM_MMIX = 80, // Donald Knuth's educational 64-bit processor
EM_HUANY = 81, // Harvard University machine-independent object files
EM_PRISM = 82, // SiTera Prism
EM_AVR = 83, /* Atmel AVR 8-bit microcontroller */
EM_FR30 = 84, /* Fujitsu FR30 */
EM_D10V = 85, /* Mitsubishi D10V */
EM_D30V = 86, /* Mitsubishi D30V */
EM_V850 = 87, /* NEC v850 */
EM_M32R = 88, /* Mitsubishi M32R */
EM_MN10300 = 89, /* Matsushita MN10300 */
EM_MN10200 = 90, /* Matsushita MN10200 */
EM_PJ = 91, /* picoJava */
EM_OPENRISC = 92, /* OpenRISC 32-bit embedded processor */
EM_ARC_COMPACT = 93, /* ARC International ARCompact */
EM_XTENSA = 94, /* Tensilica Xtensa Architecture */
EM_VIDEOCORE = 95, /* Alphamosaic VideoCore */
EM_TMM_GPP = 96, /* Thompson Multimedia General Purpose Proc */
EM_NS32K = 97, /* National Semi. 32000 */
EM_TPC = 98, /* Tenor Network TPC */
EM_SNP1K = 99, /* Trebia SNP 1000 */
EM_ST200 = 100, /* STMicroelectronics ST200 */
EM_IP2K = 101, /* Ubicom IP2xxx */
EM_MAX = 102, /* MAX processor */
EM_CR = 103, /* National Semi. CompactRISC */
EM_F2MC16 = 104, /* Fujitsu F2MC16 */
EM_MSP430 = 105, /* Texas Instruments msp430 */
EM_BLACKFIN = 106, /* Analog Devices Blackfin DSP */
EM_SE_C33 = 107, /* Seiko Epson S1C33 family */
EM_SEP = 108, /* Sharp embedded microprocessor */
EM_ARCA = 109, /* Arca RISC */
EM_UNICORE = 110, /* PKU-Unity & MPRC Peking Uni. mc series */
EM_EXCESS = 111, /* eXcess configurable cpu */
EM_DXP = 112, /* Icera Semi. Deep Execution Processor */
EM_ALTERA_NIOS2 = 113, /* Altera Nios II */
EM_CRX = 114, /* National Semi. CompactRISC CRX */
EM_XGATE = 115, /* Motorola XGATE */
EM_C166 = 116, /* Infineon C16x/XC16x */
EM_M16C = 117, /* Renesas M16C */
EM_DSPIC30F = 118, /* Microchip Technology dsPIC30F */
EM_CE = 119, /* Freescale Communication Engine RISC */
EM_M32C = 120, /* Renesas M32C */
/* reserved 121-130 */
EM_TSK3000 = 131, /* Altium TSK3000 */
EM_RS08 = 132, /* Freescale RS08 */
EM_SHARC = 133, /* Analog Devices SHARC family */
EM_ECOG2 = 134, /* Cyan Technology eCOG2 */
EM_SCORE7 = 135, /* Sunplus S+core7 RISC */
EM_DSP24 = 136, /* New Japan Radio (NJR) 24-bit DSP */
EM_VIDEOCORE3 = 137, /* Broadcom VideoCore III */
EM_LATTICEMICO32 = 138, /* RISC for Lattice FPGA */
EM_SE_C17 = 139, /* Seiko Epson C17 */
EM_TI_C6000 = 140, /* Texas Instruments TMS320C6000 DSP */
EM_TI_C2000 = 141, /* Texas Instruments TMS320C2000 DSP */
EM_TI_C5500 = 142, /* Texas Instruments TMS320C55x DSP */
EM_TI_ARP32 = 143, /* Texas Instruments App. Specific RISC */
EM_TI_PRU = 144, /* Texas Instruments Prog. Realtime Unit */
/* reserved 145-159 */
EM_MMDSP_PLUS = 160, /* STMicroelectronics 64bit VLIW DSP */
EM_CYPRESS_M8C = 161, /* Cypress M8C */
EM_R32C = 162, /* Renesas R32C */
EM_TRIMEDIA = 163, /* NXP Semi. TriMedia */
EM_QDSP6 = 164, /* QUALCOMM DSP6 */
EM_8051 = 165, /* Intel 8051 and variants */
EM_STXP7X = 166, /* STMicroelectronics STxP7x */
EM_NDS32 = 167, /* Andes Tech. compact code emb. RISC */
EM_ECOG1X = 168, /* Cyan Technology eCOG1X */
EM_MAXQ30 = 169, /* Dallas Semi. MAXQ30 mc */
EM_XIMO16 = 170, /* New Japan Radio (NJR) 16-bit DSP */
EM_MANIK = 171, /* M2000 Reconfigurable RISC */
EM_CRAYNV2 = 172, /* Cray NV2 vector architecture */
EM_RX = 173, /* Renesas RX */
EM_METAG = 174, /* Imagination Tech. META */
EM_MCST_ELBRUS = 175, /* MCST Elbrus */
EM_ECOG16 = 176, /* Cyan Technology eCOG16 */
EM_CR16 = 177, /* National Semi. CompactRISC CR16 */
EM_ETPU = 178, /* Freescale Extended Time Processing Unit */
EM_SLE9X = 179, /* Infineon Tech. SLE9X */
EM_L10M = 180, /* Intel L10M */
EM_K10M = 181, /* Intel K10M */
/* reserved 182 */
EM_AARCH64 = 183, /* ARM AARCH64 */
/* reserved 184 */
EM_AVR32 = 185, /* Amtel 32-bit microprocessor */
EM_STM8 = 186, /* STMicroelectronics STM8 */
EM_TILE64 = 187, /* Tileta TILE64 */
EM_TILEPRO = 188, /* Tilera TILEPro */
EM_MICROBLAZE = 189, /* Xilinx MicroBlaze */
EM_CUDA = 190, /* NVIDIA CUDA */
EM_TILEGX = 191, /* Tilera TILE-Gx */
EM_CLOUDSHIELD = 192, /* CloudShield */
EM_COREA_1ST = 193, /* KIPO-KAIST Core-A 1st gen. */
EM_COREA_2ND = 194, /* KIPO-KAIST Core-A 2nd gen. */
EM_ARC_COMPACT2 = 195, /* Synopsys ARCompact V2 */
EM_OPEN8 = 196, /* Open8 RISC */
EM_RL78 = 197, /* Renesas RL78 */
EM_VIDEOCORE5 = 198, /* Broadcom VideoCore V */
EM_78KOR = 199, /* Renesas 78KOR */
EM_56800EX = 200, /* Freescale 56800EX DSC */
EM_BA1 = 201, /* Beyond BA1 */
EM_BA2 = 202, /* Beyond BA2 */
EM_XCORE = 203, /* XMOS xCORE */
EM_MCHP_PIC = 204, /* Microchip 8-bit PIC(r) */
/* reserved 205-209 */
EM_KM32 = 210, /* KM211 KM32 */
EM_KMX32 = 211, /* KM211 KMX32 */
EM_EMX16 = 212, /* KM211 KMX16 */
EM_EMX8 = 213, /* KM211 KMX8 */
EM_KVARC = 214, /* KM211 KVARC */
EM_CDP = 215, /* Paneve CDP */
EM_COGE = 216, /* Cognitive Smart Memory Processor */
EM_COOL = 217, /* Bluechip CoolEngine */
EM_NORC = 218, /* Nanoradio Optimized RISC */
EM_CSR_KALIMBA = 219, /* CSR Kalimba */
EM_Z80 = 220, /* Zilog Z80 */
EM_VISIUM = 221, /* Controls and Data Services VISIUMcore */
EM_FT32 = 222, /* FTDI Chip FT32 */
EM_MOXIE = 223, /* Moxie processor */
EM_AMDGPU = 224, /* AMD GPU */
/* reserved 225-242 */
EM_RISCV = 243, /* RISC-V */
EM_BPF = 247, /* Linux BPF -- in-kernel virtual machine */
EM_CSKY = 252, /* C-SKY */
EM_NUM = 253,
/* Old spellings/synonyms. */
// EM_ARC_A5 = EM_ARC_COMPACT,
/* If it is necessary to assign new unofficial EM_* values, please
pick large random numbers (0x8523, 0xa7f2, etc.) to minimize the
chances of collision with official or non-GNU unofficial values. */
//EM_ALPHA = 0x9026,
}
impl EI_MACH {
pub fn as_u16(&self) -> u16 {
match self {
EI_MACH::EM_NONE => 0,
EI_MACH::EM_M32 => 1, // AT&T WE 32100
EI_MACH::EM_SPARC => 2, //SPARC
EI_MACH::EM_386 => 3, //Intel 80386
EI_MACH::EM_68K => 4, //Motorola 68000
EI_MACH::EM_88K => 5, // Motorola 88000
// RESERVED 6 // Reserved for future use
EI_MACH::EM_860 => 7, //Intel 80860
EI_MACH::EM_MIPS => 8, // MIPS I Architecture
EI_MACH::EM_S370 => 9, // IBM System/370 Processor
EI_MACH::EM_MIPS_RS3_LE => 10, // MIPS RS3000 Little-endian
//RESERVED 11-14 // Reserved for future use
EI_MACH::EM_PARISC => 15, //Hewlett-Packard PA-RISC
//RESERVED 16 // Reserved for future use
EI_MACH::EM_VPP500 => 17, //Fujitsu VPP500
EI_MACH::EM_SPARC32PLUS => 18, //Enhanced instruction set SPARC
EI_MACH::EM_960 => 19, // Intel 80960
EI_MACH::EM_PPC => 20, // PowerPC
EI_MACH::EM_PPC64 => 21, // 64-bit PowerPC
//RESERVED 22-35 // Reserved for future use
EI_MACH::EM_V800 => 36, // NEC V800
EI_MACH::EM_FR20 => 37, // Fujitsu FR20
EI_MACH::EM_RH32 => 38, //TRW RH-32
EI_MACH::EM_RCE => 39, //Motorola RCE
EI_MACH::EM_ARM => 40, //Advanced RISC Machines ARM
EI_MACH::EM_ALPHA => 41, // Digital Alpha
EI_MACH::EM_SH => 42, //Hitachi SH
EI_MACH::EM_SPARCV9 => 43, // SPARC Version 9
EI_MACH::EM_TRICORE => 44, // Siemens Tricore embedded processor
EI_MACH::EM_ARC => 45, //Argonaut RISC Core, Argonaut Technologies Inc.
EI_MACH::EM_H8_300 => 46, // Hitachi H8/300
EI_MACH::EM_H8_300H => 47, // Hitachi H8/300H
EI_MACH::EM_H8S => 48, //Hitachi H8S
EI_MACH::EM_H8_500 => 49, //Hitachi H8/500
EI_MACH::EM_IA_64 => 50, //Intel IA-64 processor architecture
EI_MACH::EM_MIPS_X => 51, //Stanford MIPS-X
EI_MACH::EM_COLDFIRE => 52, // Motorola ColdFire
EI_MACH::EM_68HC12 => 53, //Motorola M68HC12
EI_MACH::EM_MMA => 54, //Fujitsu MMA Multimedia Accelerator
EI_MACH::EM_PCP => 55, //Siemens PCP
EI_MACH:: EM_NCPU => 56, //Sony nCPU embedded RISC processor
EI_MACH::EM_NDR1 => 57, //Denso NDR1 microprocessor
EI_MACH::EM_STARCORE => 58, // Motorola Star*Core processor
EI_MACH::EM_ME16 => 59, //Toyota ME16 processor
EI_MACH::EM_ST100 => 60, //STMicroelectronics ST100 processor
EI_MACH::EM_TINYJ => 61, //Advanced Logic Corp. TinyJ embedded processor family
//Reserved 62-65 //Reserved for future use
EI_MACH::EM_FX66 => 66, //Siemens FX66 microcontroller
EI_MACH::EM_ST9PLUS => 67, // STMicroelectronics ST9+ 8/16 bit microcontroller
EI_MACH::EM_ST7 => 68, //STMicroelectronics ST7 8-bit microcontroller
EI_MACH::EM_68HC16 => 69, // Motorola MC68HC16 Microcontroller
EI_MACH::EM_68HC11 => 70, // Motorola MC68HC11 Microcontroller
EI_MACH::EM_68HC08 => 71, // Motorola MC68HC08 Microcontroller
EI_MACH::EM_68HC05 => 72, // Motorola MC68HC05 Microcontroller
EI_MACH::EM_SVX => 73, //Silicon Graphics SVx
EI_MACH::EM_ST19 => 74, // STMicroelectronics ST19 8-bit microcontroller
EI_MACH::EM_VAX => 75, // Digital VAX
EI_MACH::EM_CRIS => 76, // Axis Communications 32-bit embedded processor
EI_MACH::EM_JAVELIN => 77, //Infineon Technologies 32-bit embedded processor
EI_MACH::EM_FIREPATH => 78, // Element 14 64-bit DSP Processor
EI_MACH::EM_ZSP => 79, //LSI Logic 16-bit DSP Processor
EI_MACH::EM_MMIX => 80, // Donald Knuth's educational 64-bit processor
EI_MACH::EM_HUANY => 81, // Harvard University machine-independent object files
EI_MACH::EM_PRISM => 82, // SiTera Prism
EI_MACH::EM_AVR => 83, /* Atmel AVR 8-bit microcontroller */
EI_MACH::EM_FR30 => 84, /* Fujitsu FR30 */
EI_MACH::EM_D10V => 85, /* Mitsubishi D10V */
EI_MACH::EM_D30V => 86, /* Mitsubishi D30V */
EI_MACH::EM_V850 => 87, /* NEC v850 */
EI_MACH::EM_M32R => 88, /* Mitsubishi M32R */
EI_MACH::EM_MN10300 => 89, /* Matsushita MN10300 */
EI_MACH::EM_MN10200 => 90, /* Matsushita MN10200 */
EI_MACH::EM_PJ => 91, /* picoJava */
EI_MACH::EM_OPENRISC => 92, /* OpenRISC 32-bit embedded processor */
EI_MACH::EM_ARC_COMPACT => 93, /* ARC International ARCompact */
EI_MACH::EM_XTENSA => 94, /* Tensilica Xtensa Architecture */
EI_MACH::EM_VIDEOCORE => 95, /* Alphamosaic VideoCore */
EI_MACH::EM_TMM_GPP => 96, /* Thompson Multimedia General Purpose Proc */
EI_MACH::EM_NS32K => 97, /* National Semi. 32000 */
EI_MACH::EM_TPC => 98, /* Tenor Network TPC */
EI_MACH::EM_SNP1K => 99, /* Trebia SNP 1000 */
EI_MACH::EM_ST200 => 100, /* STMicroelectronics ST200 */
EI_MACH::EM_IP2K => 101, /* Ubicom IP2xxx */
EI_MACH::EM_MAX => 102, /* MAX processor */
EI_MACH::EM_CR => 103, /* National Semi. CompactRISC */
EI_MACH::EM_F2MC16 => 104, /* Fujitsu F2MC16 */
EI_MACH::EM_MSP430 => 105, /* Texas Instruments msp430 */
EI_MACH::EM_BLACKFIN => 106, /* Analog Devices Blackfin DSP */
EI_MACH::EM_SE_C33 => 107, /* Seiko Epson S1C33 family */
EI_MACH::EM_SEP => 108, /* Sharp embedded microprocessor */
EI_MACH::EM_ARCA => 109, /* Arca RISC */
EI_MACH::EM_UNICORE => 110, /* PKU-Unity & MPRC Peking Uni. mc series */
EI_MACH::EM_EXCESS => 111, /* eXcess configurable cpu */
EI_MACH::EM_DXP => 112, /* Icera Semi. Deep Execution Processor */
EI_MACH::EM_ALTERA_NIOS2 => 113, /* Altera Nios II */
EI_MACH::EM_CRX => 114, /* National Semi. CompactRISC CRX */
EI_MACH::EM_XGATE => 115, /* Motorola XGATE */
EI_MACH::EM_C166 => 116, /* Infineon C16x/XC16x */
EI_MACH::EM_M16C => 117, /* Renesas M16C */
EI_MACH::EM_DSPIC30F => 118, /* Microchip Technology dsPIC30F */
EI_MACH::EM_CE => 119, /* Freescale Communication Engine RISC */
EI_MACH::EM_M32C => 120, /* Renesas M32C */
/* reserved 121-130 */
EI_MACH::EM_TSK3000 => 131, /* Altium TSK3000 */
EI_MACH::EM_RS08 => 132, /* Freescale RS08 */
EI_MACH::EM_SHARC => 133, /* Analog Devices SHARC family */
EI_MACH::EM_ECOG2 => 134, /* Cyan Technology eCOG2 */
EI_MACH::EM_SCORE7 => 135, /* Sunplus S+core7 RISC */
EI_MACH::EM_DSP24 => 136, /* New Japan Radio (NJR) 24-bit DSP */
EI_MACH::EM_VIDEOCORE3 => 137, /* Broadcom VideoCore III */
EI_MACH::EM_LATTICEMICO32 => 138, /* RISC for Lattice FPGA */
EI_MACH::EM_SE_C17 => 139, /* Seiko Epson C17 */
EI_MACH::EM_TI_C6000 => 140, /* Texas Instruments TMS320C6000 DSP */
EI_MACH::EM_TI_C2000 => 141, /* Texas Instruments TMS320C2000 DSP */
EI_MACH::EM_TI_C5500 => 142, /* Texas Instruments TMS320C55x DSP */
EI_MACH::EM_TI_ARP32 => 143, /* Texas Instruments App. Specific RISC */
EI_MACH::EM_TI_PRU => 144, /* Texas Instruments Prog. Realtime Unit */
/* reserved 145-159 */
EI_MACH::EM_MMDSP_PLUS => 160, /* STMicroelectronics 64bit VLIW DSP */
EI_MACH::EM_CYPRESS_M8C => 161, /* Cypress M8C */
EI_MACH::EM_R32C => 162, /* Renesas R32C */
EI_MACH::EM_TRIMEDIA => 163, /* NXP Semi. TriMedia */
EI_MACH::EM_QDSP6 => 164, /* QUALCOMM DSP6 */
EI_MACH::EM_8051 => 165, /* Intel 8051 and variants */
EI_MACH::EM_STXP7X => 166, /* STMicroelectronics STxP7x */
EI_MACH::EM_NDS32 => 167, /* Andes Tech. compact code emb. RISC */
EI_MACH::EM_ECOG1X => 168, /* Cyan Technology eCOG1X */
EI_MACH::EM_MAXQ30 => 169, /* Dallas Semi. MAXQ30 mc */
EI_MACH::EM_XIMO16 => 170, /* New Japan Radio (NJR) 16-bit DSP */
EI_MACH::EM_MANIK => 171, /* M2000 Reconfigurable RISC */
EI_MACH::EM_CRAYNV2 => 172, /* Cray NV2 vector architecture */
EI_MACH::EM_RX => 173, /* Renesas RX */
EI_MACH::EM_METAG => 174, /* Imagination Tech. META */
EI_MACH::EM_MCST_ELBRUS => 175, /* MCST Elbrus */
EI_MACH::EM_ECOG16 => 176, /* Cyan Technology eCOG16 */
EI_MACH::EM_CR16 => 177, /* National Semi. CompactRISC CR16 */
EI_MACH::EM_ETPU => 178, /* Freescale Extended Time Processing Unit */
EI_MACH::EM_SLE9X => 179, /* Infineon Tech. SLE9X */
EI_MACH::EM_L10M => 180, /* Intel L10M */
EI_MACH::EM_K10M => 181, /* Intel K10M */
/* reserved 182 */
EI_MACH::EM_AARCH64 => 183, /* ARM AARCH64 */
/* reserved 184 */
EI_MACH::EM_AVR32 => 185, /* Amtel 32-bit microprocessor */
EI_MACH::EM_STM8 => 186, /* STMicroelectronics STM8 */
EI_MACH::EM_TILE64 => 187, /* Tileta TILE64 */
EI_MACH::EM_TILEPRO => 188, /* Tilera TILEPro */
EI_MACH::EM_MICROBLAZE => 189, /* Xilinx MicroBlaze */
EI_MACH::EM_CUDA => 190, /* NVIDIA CUDA */
EI_MACH::EM_TILEGX => 191, /* Tilera TILE-Gx */
EI_MACH::EM_CLOUDSHIELD => 192, /* CloudShield */
EI_MACH::EM_COREA_1ST => 193, /* KIPO-KAIST Core-A 1st gen. */
EI_MACH::EM_COREA_2ND => 194, /* KIPO-KAIST Core-A 2nd gen. */
EI_MACH::EM_ARC_COMPACT2 => 195, /* Synopsys ARCompact V2 */
EI_MACH::EM_OPEN8 => 196, /* Open8 RISC */
EI_MACH::EM_RL78 => 197, /* Renesas RL78 */
EI_MACH::EM_VIDEOCORE5 => 198, /* Broadcom VideoCore V */
EI_MACH::EM_78KOR => 199, /* Renesas 78KOR */
EI_MACH::EM_56800EX => 200, /* Freescale 56800EX DSC */
EI_MACH::EM_BA1 => 201, /* Beyond BA1 */
EI_MACH::EM_BA2 => 202, /* Beyond BA2 */
EI_MACH::EM_XCORE => 203, /* XMOS xCORE */
EI_MACH::EM_MCHP_PIC => 204, /* Microchip 8-bit PIC(r) */
/* reserved 205-209 */
EI_MACH::EM_KM32 => 210, /* KM211 KM32 */
EI_MACH::EM_KMX32 => 211, /* KM211 KMX32 */
EI_MACH::EM_EMX16 => 212, /* KM211 KMX16 */
EI_MACH::EM_EMX8 => 213, /* KM211 KMX8 */
EI_MACH::EM_KVARC => 214, /* KM211 KVARC */
EI_MACH::EM_CDP => 215, /* Paneve CDP */
EI_MACH::EM_COGE => 216, /* Cognitive Smart Memory Processor */
EI_MACH::EM_COOL => 217, /* Bluechip CoolEngine */
EI_MACH::EM_NORC => 218, /* Nanoradio Optimized RISC */
EI_MACH::EM_CSR_KALIMBA => 219, /* CSR Kalimba */
EI_MACH::EM_Z80 => 220, /* Zilog Z80 */
EI_MACH::EM_VISIUM => 221, /* Controls and Data Services VISIUMcore */
EI_MACH::EM_FT32 => 222, /* FTDI Chip FT32 */
EI_MACH::EM_MOXIE => 223, /* Moxie processor */
EI_MACH::EM_AMDGPU => 224, /* AMD GPU */
/* reserved 225-242 */
EI_MACH::EM_RISCV => 243, /* RISC-V */
EI_MACH::EM_BPF => 247, /* Linux BPF -- in-kernel virtual machine */
EI_MACH::EM_CSKY => 252, /* C-SKY */
EI_MACH::EM_NUM => 253,
/* Old spellings/synonyms. */
// EM_ARC_A5 = EM_ARC_COMPACT,
/* If it is necessary to assign new unofficial EM_* values, please
pick large random numbers (0x8523, 0xa7f2, etc.) to minimize the
chances of collision with official or non-GNU unofficial values. */
// EM_ALPHA => 0x9026,
}
}
}
#[derive(Clone, Copy, Debug)]
pub enum EI_CLASS {
ELFCLASSNONE,
ELFCLASS32,
ELFCLASS64,
ELFCLASSOTHER(u8),
}
impl EI_CLASS {
pub fn as_u8(&self) -> u8 {
match self {
EI_CLASS::ELFCLASSNONE => 0,
EI_CLASS::ELFCLASS32 => 1,
EI_CLASS::ELFCLASS64 => 2,
EI_CLASS::ELFCLASSOTHER(d) => *d,
}
}
}
#[repr(u8)]
#[derive(Clone, Copy, Debug)]
pub enum EI_DATA {
ELFDATANONE = 0,
ELFDATA2LSB,
ELFDATA2MSB,
ELFDATAOTHER(u8), //TODO are other values than 3 valid here? Need to check ELF Specs for arm and x86
}
impl EI_DATA {
pub fn as_u8(&self) -> u8 {
match self {
EI_DATA::ELFDATANONE => 0,
EI_DATA::ELFDATA2LSB => 1,
EI_DATA::ELFDATA2MSB => 2,
EI_DATA::ELFDATAOTHER(d) => *d,
}
}
}
//TODO figure out different system so that aliasing is allowed?
#[repr(u8)]
#[allow(non_camel_case_types)]
pub enum EI_OSABI {
ELFOSABI_NONE = 0, /* UNIX System V ABI */
//ELFOSABI_SYSV = /* Alias ELFOSABI_NONE, */
ELFOSABI_HPUX = 1, /* HP-UX */
ELFOSABI_NETBSD = 2, /* NetBSD. */
ELFOSABI_GNU = 3, /* Object uses GNU ELF extensions. */
//ELFOSABI_LINUX = , /* Compatibility alias ELFOSABI_GNU */
ELFOSABI_SOLARIS = 6, /* Sun Solaris. */
ELFOSABI_AIX = 7, /* IBM AIX. */
ELFOSABI_IRIX = 8, /* SGI Irix. */
ELFOSABI_FREEBSD = 9, /* FreeBSD. */
ELFOSABI_TRU64 = 10, /* Compaq TRU64 UNIX. */
ELFOSABI_MODESTO = 11, /* Novell Modesto. */
ELFOSABI_OPENBSD = 12, /* OpenBSD. */
ELFOSABI_ARM_AEABI = 64, /* ARM EABI */
ELFOSABI_ARM = 97, /* ARM */
ELFOSABI_OTHER(u8),
ELFOSABI_STANDALONE = 255, /* Standalone (embedded) application */
}
#[allow(non_camel_case_types)]
impl EI_OSABI {
pub fn as_u8(&self) -> u8 {
match self {
EI_OSABI::ELFOSABI_NONE => 0, /* UNIX System V ABI */
//EI_OSABI::ELFOSABI_SYSV => 0, //EI_OSABI::ELFOSABI_NONE, /* Alias. */
EI_OSABI::ELFOSABI_HPUX => 1, /* HP-UX */
EI_OSABI::ELFOSABI_NETBSD => 2, /* NetBSD. */
EI_OSABI::ELFOSABI_GNU => 3, /* Object uses GNU ELF extensions. */
// EI_OSABI::ELFOSABI_LINUX => 3, //EI_OSABI::ELFOSABI_GNU, /* Compatibility alias. */
EI_OSABI::ELFOSABI_SOLARIS => 6, /* Sun Solaris. */
EI_OSABI::ELFOSABI_AIX => 7, /* IBM AIX. */
EI_OSABI::ELFOSABI_IRIX => 8, /* SGI Irix. */
EI_OSABI::ELFOSABI_FREEBSD => 9, /* FreeBSD. */
EI_OSABI::ELFOSABI_TRU64 => 10, /* Compaq TRU64 UNIX. */
EI_OSABI::ELFOSABI_MODESTO => 11, /* Novell Modesto. */
EI_OSABI::ELFOSABI_OPENBSD => 12, /* OpenBSD. */
EI_OSABI::ELFOSABI_ARM_AEABI => 64, /* ARM EABI */
EI_OSABI::ELFOSABI_ARM => 97, /* ARM */
EI_OSABI::ELFOSABI_OTHER(d) => *d,
EI_OSABI::ELFOSABI_STANDALONE => 255, /* Standalone (embedded) application */
}
}
}
pub enum EI_VERS{
EV_NONE = 0,
EV_CURRENT = 1,
}
}
| true |
4643bf2accbcf86bd1bfa93541e50ae7959a98ba
|
Rust
|
illef/pantin
|
/src/view/stack_panel.rs
|
UTF-8
| 2,251 | 2.953125 | 3 |
[] |
no_license
|
use super::*;
pub struct StackPanel<E: AsUIEvent> {
children: Vec<Box<dyn View<Event = E>>>,
bg: Option<color::Color>,
}
pub fn make_stack_panel<E: AsUIEvent>() -> StackPanel<E> {
StackPanel {
children: vec![],
bg: None,
}
}
impl<E: AsUIEvent> StackPanel<E> {
pub fn set_bg(mut self, bg: color::Color) -> Self {
self.bg = Some(bg);
self
}
pub fn clear_children(&mut self) {
self.children.clear();
}
pub fn get_children(&mut self) -> &mut Vec<Box<dyn View<Event = E>>> {
&mut self.children
}
pub fn add_child(&mut self, view: Box<dyn View<Event = E>>) -> &mut Self {
self.children.push(view);
self
}
pub fn swap_child(&mut self, index: usize, mut view: Box<dyn View<Event = E>>) {
assert!(self.children.len() > index);
std::mem::swap(&mut self.children[index], &mut view);
}
fn render_child(buffer: &mut BufferMut, children: &mut Vec<Box<dyn View<Event = E>>>) {
let mut offset = Point(0, 0);
let mut size = buffer.size();
for child_view in children.iter_mut() {
let mut buffer_mut_view = buffer.as_mut_view(offset, size);
let available_size = available_size(buffer_mut_view.size(), child_view.desire_size());
if available_size.is_zero() {
break;
}
let mut buffer_mut = buffer_mut_view.as_mut_view(Point(0, 0), available_size);
child_view.render(&mut buffer_mut);
offset = offset.add(Point(0, available_size.height));
size = Size {
width: buffer_mut_view.size().width,
height: buffer_mut_view.size().height - available_size.height,
};
}
}
}
impl<E: AsUIEvent> View for StackPanel<E> {
type Event = E;
fn desire_size(&self) -> Size {
let height: u64 = self
.children
.iter()
.map(|view| view.desire_size().height as u64)
.sum();
Size {
width: std::u16::MAX,
height: height as u16,
}
}
fn render(&mut self, buf: &mut BufferMut) {
StackPanel::render_child(buf, &mut self.children);
}
}
| true |
f5abf42437c368422794d372a8aba1996ade8786
|
Rust
|
cannontwo/rust_learning
|
/fn_pointer_testing/src/main.rs
|
UTF-8
| 857 | 3.296875 | 3 |
[] |
no_license
|
type PotentialFunc = fn(&[String]) -> i32;
struct Holder<'a> {
names: &'a [String],
func: PotentialFunc
}
#[derive(Debug)]
struct Larger<'a> {
holders: Vec<Holder<'a>>,
}
impl<'a> std::fmt::Debug for Holder<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "Holder {{ {:?}, <func: {}> }}", self.names, (self.func)(self.names))
}
}
impl<'a> Larger<'a> {
fn new() -> Larger<'a> {
Larger { holders: vec!() }
}
fn add_holder(&mut self, holder: Holder<'a>) {
self.holders.push(holder);
}
}
fn dummy_func(args: &[String]) -> i32 {
args.len() as i32
}
fn main() {
let h = Holder { names: &vec!(String::from("Hello"), String::from("world!")), func: dummy_func };
let mut larger = Larger::new();
larger.add_holder(h);
println!("{:?}", larger);
}
| true |
c6596306052228d1683ff0f2b681fe83146b4403
|
Rust
|
regendo/advent-of-code-2019
|
/day04/src/lib.rs
|
UTF-8
| 2,588 | 3.359375 | 3 |
[] |
no_license
|
mod input;
fn criteria_six_digits(num: u32) -> bool {
num >= 100_000 && num <= 999_999
}
fn criteria_in_range(num: u32) -> bool {
num >= input::LOWER && num <= input::UPPER
}
fn criteria_two_same(num: u32) -> bool {
let mut num = num;
while num > 0 {
if num % 10 == num / 10 % 10 {
return true;
}
num /= 10;
}
false
}
fn criteria_two_same_strictly(num: u32) -> bool {
let mut digits = [0; 10];
let mut num = num;
while num > 0 {
digits[(num % 10) as usize] += 1;
num /= 10;
}
digits.iter().any(|n| *n == 2)
}
fn criteria_non_descending(num: u32) -> bool {
let mut num = num;
while num > 0 {
if num % 10 < num / 10 % 10 {
return false;
}
num /= 10;
}
true
}
pub fn count_valid_options() -> u32 {
(input::LOWER..=input::UPPER)
.filter(|n| {
// We don't _really_ need the first two since we're already iterating over 6-digit in-range numbers.
criteria_six_digits(*n)
&& criteria_in_range(*n)
&& criteria_two_same(*n)
&& criteria_non_descending(*n)
})
.count() as u32
}
pub fn count_valid_options_strictly() -> u32 {
(input::LOWER..=input::UPPER)
.filter(|n| {
// We don't _really_ need the first two since we're already iterating over 6-digit in-range numbers.
criteria_six_digits(*n)
&& criteria_in_range(*n)
&& criteria_two_same_strictly(*n)
&& criteria_non_descending(*n)
})
.count() as u32
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn spec_double_11() {
let num = 111_111;
let valid =
criteria_non_descending(num) && criteria_six_digits(num) && criteria_two_same(num);
assert_eq!(valid, true);
}
#[test]
fn spec_decreasing() {
let num = 223_450;
let valid =
criteria_non_descending(num) && criteria_six_digits(num) && criteria_two_same(num);
assert_eq!(valid, false);
}
#[test]
fn spec_no_double() {
let num = 123_789;
let valid =
criteria_non_descending(num) && criteria_six_digits(num) && criteria_two_same(num);
assert_eq!(valid, false);
}
#[test]
fn spec_all_double() {
let num = 11_22_33;
let valid = criteria_non_descending(num)
&& criteria_six_digits(num)
&& criteria_two_same_strictly(num);
assert_eq!(valid, true);
}
#[test]
fn spec_just_triplet() {
let num = 123_444;
let valid = criteria_non_descending(num)
&& criteria_six_digits(num)
&& criteria_two_same_strictly(num);
assert_eq!(valid, false);
}
#[test]
fn spec_with_multiplet() {
let num = 111_122;
let valid = criteria_non_descending(num)
&& criteria_six_digits(num)
&& criteria_two_same_strictly(num);
assert_eq!(valid, true);
}
}
| true |
1dfd98eb808c5fc602372acf0d88414d49e1d3f7
|
Rust
|
canpok1/atcoder-rust
|
/contests/abc187/src/bin/b.rs
|
UTF-8
| 1,673 | 3.546875 | 4 |
[] |
no_license
|
struct Point {
x: f64,
y: f64,
}
fn main() {
let n: usize = {
let mut line = String::new();
std::io::stdin().read_line(&mut line).unwrap();
line.trim_end().parse().unwrap()
};
let mut points: Vec<Point> = Vec::new();
(0..n).for_each(|_| {
let (x, y) = {
let mut line = String::new();
std::io::stdin().read_line(&mut line).unwrap();
let mut ws = line.trim_end().split_whitespace();
let n1: isize = ws.next().unwrap().parse().unwrap();
let n2: isize = ws.next().unwrap().parse().unwrap();
(n1, n2)
};
points.push(Point {
x: x as f64,
y: y as f64,
});
});
let stdout = solve(points);
stdout.iter().for_each(|s| {
println!("{}", s);
})
}
fn solve(points: Vec<Point>) -> Vec<String> {
let mut count = 0;
for (i, p1) in points.iter().enumerate() {
for (j, p2) in points.iter().enumerate() {
if i >= j {
continue;
}
let a = (p2.y - p1.y) / (p2.x - p1.x);
if a >= -1.0 && a <= 1.0 {
count += 1;
}
}
}
let mut buf = Vec::new();
buf.push(format!("{}", count));
buf
}
#[test]
fn test_solve_1() {
let points: Vec<Point> = vec![
Point { x: 0.0, y: 0.0 },
Point { x: 1.0, y: 2.0 },
Point { x: 2.0, y: 1.0 },
];
assert_eq!(solve(points), vec!("2"));
}
#[test]
fn test_solve_2() {
let points: Vec<Point> = vec![Point {
x: -691.0,
y: 273.0,
}];
assert_eq!(solve(points), vec!("0"));
}
| true |
fb4c436c885f385dda13cdd31d533b32143352e2
|
Rust
|
subspace/decoupled-execution-experiment
|
/pallets/simple-event/src/lib.rs
|
UTF-8
| 1,036 | 2.921875 | 3 |
[
"Unlicense"
] |
permissive
|
//! Demonstration of Event variants that use only primative types
//! These events do not use types from the pallet's configuration trait
#![cfg_attr(not(feature = "std"), no_std)]
use frame_support::{decl_event, decl_module, dispatch::DispatchResult};
use frame_system::ensure_signed;
// #[cfg(test)]
// mod tests;
pub trait Config: frame_system::Config {
type Event: From<Event> + Into<<Self as frame_system::Config>::Event>;
}
decl_module! {
pub struct Module<T: Config> for enum Call where origin: T::Origin {
fn deposit_event() = default;
/// A simple call that does little more than emit an event
#[weight = 10_000]
fn do_something(origin, input: u32) -> DispatchResult {
let _ = ensure_signed(origin)?;
// In practice, you could do some processing with the input here.
let new_number = input;
// emit event
Self::deposit_event(Event::EmitInput(new_number));
Ok(())
}
}
}
// uses u32 and not types from Trait so does not require `<T>`
decl_event!(
pub enum Event {
EmitInput(u32),
}
);
| true |
5d2664e0d15c121fba9acedf8ab7b4fef29fc2b8
|
Rust
|
archification/guess
|
/src/main.rs
|
UTF-8
| 2,833 | 3.0625 | 3 |
[] |
no_license
|
extern crate rand;
extern crate crossterm;
mod solarized;
mod common;
use std::io::stdin;
use std::cmp::Ordering::{
Less,
Greater,
Equal
};
use rand::Rng;
use crossterm::style::{
Attribute,
ResetColor,
SetBackgroundColor,
SetForegroundColor
};
use solarized::{
BACK,
YELLOW,
ORANGE,
RED,
MAGENTA,
VIOLET,
BLUE,
CYAN,
GREEN
};
use common::clear;
fn main() {
clear().unwrap();
println!(
"{}{}Please {}enter {}your {}name {}to {}save {}your {}score: {}",
SetBackgroundColor(BACK),
SetForegroundColor(YELLOW),
SetForegroundColor(ORANGE),
SetForegroundColor(RED),
SetForegroundColor(MAGENTA),
SetForegroundColor(VIOLET),
SetForegroundColor(BLUE),
SetForegroundColor(CYAN),
SetForegroundColor(GREEN),
ResetColor
);
let mut name = String::new();
stdin().read_line(&mut name)
.expect("Failed to read line.");
clear().unwrap();
println!(
"{}{}Guess {}a {}five {}digit {}number {}now {}or {}else: {}",
SetBackgroundColor(BACK),
SetForegroundColor(YELLOW),
SetForegroundColor(ORANGE),
SetForegroundColor(RED),
SetForegroundColor(MAGENTA),
SetForegroundColor(VIOLET),
SetForegroundColor(BLUE),
SetForegroundColor(CYAN),
SetForegroundColor(GREEN),
ResetColor
);
let secret_number = rand::thread_rng().gen_range(10000..99999);
let mut tries = 0;
loop {
let mut guess = String::new();
stdin().read_line(&mut guess)
.expect("Failed to read line");
let guess: u32 = match guess.trim().parse() {
Ok(num) => num,
Err(_) => continue,
};
tries += 1;
match guess.cmp(&secret_number) {
Less => println!("{}{}higher{}",
SetBackgroundColor(BACK),
SetForegroundColor(GREEN),
ResetColor
),
Greater => println!("{}{}lower{}",
SetBackgroundColor(BACK),
SetForegroundColor(BLUE),
ResetColor
),
Equal => {
println!("{}{}{}{}Well done {}{}{}, you matched in {}{}{} tries!{}",
SetBackgroundColor(BACK),
SetForegroundColor(CYAN),
Attribute::Bold,
Attribute::SlowBlink,
SetForegroundColor(VIOLET),
name.trim(),
SetForegroundColor(CYAN),
SetForegroundColor(VIOLET),
tries,
SetForegroundColor(CYAN),
ResetColor
);
break;
}
}
}
}
| true |
7814fd2b1186b5b1560b9025b0368d6dde906568
|
Rust
|
denoland/deno
|
/runtime/fs_util.rs
|
UTF-8
| 1,812 | 2.90625 | 3 |
[
"MIT"
] |
permissive
|
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
use deno_core::anyhow::Context;
use deno_core::error::AnyError;
pub use deno_core::normalize_path;
use std::path::Path;
use std::path::PathBuf;
#[inline]
pub fn resolve_from_cwd(path: &Path) -> Result<PathBuf, AnyError> {
if path.is_absolute() {
Ok(normalize_path(path))
} else {
#[allow(clippy::disallowed_methods)]
let cwd = std::env::current_dir()
.context("Failed to get current working directory")?;
Ok(normalize_path(cwd.join(path)))
}
}
#[cfg(test)]
mod tests {
use super::*;
fn current_dir() -> PathBuf {
#[allow(clippy::disallowed_methods)]
std::env::current_dir().unwrap()
}
#[test]
fn resolve_from_cwd_child() {
let cwd = current_dir();
assert_eq!(resolve_from_cwd(Path::new("a")).unwrap(), cwd.join("a"));
}
#[test]
fn resolve_from_cwd_dot() {
let cwd = current_dir();
assert_eq!(resolve_from_cwd(Path::new(".")).unwrap(), cwd);
}
#[test]
fn resolve_from_cwd_parent() {
let cwd = current_dir();
assert_eq!(resolve_from_cwd(Path::new("a/..")).unwrap(), cwd);
}
#[test]
fn test_normalize_path() {
assert_eq!(normalize_path(Path::new("a/../b")), PathBuf::from("b"));
assert_eq!(normalize_path(Path::new("a/./b/")), PathBuf::from("a/b/"));
assert_eq!(
normalize_path(Path::new("a/./b/../c")),
PathBuf::from("a/c")
);
if cfg!(windows) {
assert_eq!(
normalize_path(Path::new("C:\\a\\.\\b\\..\\c")),
PathBuf::from("C:\\a\\c")
);
}
}
#[test]
fn resolve_from_cwd_absolute() {
let expected = Path::new("a");
let cwd = current_dir();
let absolute_expected = cwd.join(expected);
assert_eq!(resolve_from_cwd(expected).unwrap(), absolute_expected);
}
}
| true |
65b0e1b34a94891ddcd3b170b2d9eaa878f05d83
|
Rust
|
arlyon/holding
|
/holding_kronos/src/calendar/day.rs
|
UTF-8
| 908 | 2.96875 | 3 |
[
"Apache-2.0",
"MIT"
] |
permissive
|
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
use super::traits::DayCycle;
/// Represents a day.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Day {
seconds_in_minute: u32,
minutes_in_hour: u32,
hours_in_day: u32,
}
impl Day {
/// Creates a new `Day`.
pub fn new(seconds_in_minute: u32, minutes_in_hour: u32, hours_in_day: u32) -> Self {
Self {
seconds_in_minute,
minutes_in_hour,
hours_in_day,
}
}
}
impl DayCycle for Day {
fn hours_in_day(&self) -> u32 {
self.hours_in_day
}
fn minutes_in_hour(&self) -> u32 {
self.minutes_in_hour
}
fn seconds_in_minute(&self) -> u32 {
self.seconds_in_minute
}
}
impl Default for Day {
fn default() -> Self {
Self::new(60, 60, 24)
}
}
| true |
7f30cbad8a175cb88203de761496c074146db5f5
|
Rust
|
bokutotu/curs
|
/src/operator.rs
|
UTF-8
| 5,030 | 3.078125 | 3 |
[] |
no_license
|
//! Implementing an operator for an Array
use std::ops;
use super::array::Array;
use super::cublas::level1::{daxpy, saxpy};
use super::kernel::array_scalar_add::{double_array_add_scalar, float_array_add_scalar};
use super::kernel::element_wise_operator::{element_wise_devide, element_wise_product};
//////////////////////////// Add and Sub ///////////////////////////////
//////////// Array and Array
macro_rules! add_sub_impl {
($impl_name: ident, $func_name: ident, $type: ty, $alpha: literal, $cublas_func: ident) => {
impl<'a> ops::$impl_name<Array<'a, $type>> for Array<'a, $type> {
type Output = Array<'a, $type>;
fn $func_name(self, other: Array<'a, $type>) -> Self::Output {
if self.dim != other.dim {
panic!("dimension mismatch");
}
if self.order != other.order {
todo!();
}
$cublas_func($alpha, &other, &self).unwrap();
self
}
}
};
}
add_sub_impl!(Add, add, f32, 1f32, saxpy);
add_sub_impl!(Add, add, f64, 1f64, daxpy);
add_sub_impl!(Sub, sub, f32, -1f32, saxpy);
add_sub_impl!(Sub, sub, f64, -1f64, daxpy);
// TODO
// impl Add and Sub Array<'a, f64> Array<'a, f64>
// impl Add and Sub Array<'a, f64, f32> f64, f32
macro_rules! array_scalar_add_sub_impl {
($type: ty, $func: ident) => {
impl<'a> ops::Add<$type> for Array<'a, $type> {
type Output = Array<'a, $type>;
fn add(self, other: $type) -> Self::Output {
$func(self, other)
}
}
impl<'a> ops::Add<Array<'a, $type>> for $type {
type Output = Array<'a, $type>;
fn add(self, other: Array<'a, $type>) -> Self::Output {
$func(other, self)
}
}
impl<'a> ops::Sub<$type> for Array<'a, $type> {
type Output = Array<'a, $type>;
fn sub(self, other: $type) -> Self::Output {
let scalar = -1. * other;
$func(self, scalar)
}
}
impl<'a> ops::Sub<Array<'a, $type>> for $type {
type Output = Array<'a, $type>;
fn sub(self, other: Array<'a, $type>) -> Self::Output {
let scalar = -1. * self;
$func(other, scalar)
}
}
};
}
array_scalar_add_sub_impl!(f32, float_array_add_scalar);
array_scalar_add_sub_impl!(f64, double_array_add_scalar);
////////////////// Mul and Div /////////////////////////
//////////// Array and f32 or f64
macro_rules! mul_axpy {
($type: ty, $cublas_func: ident) => {
impl<'a> ops::Mul<$type> for Array<'a, $type> {
type Output = Array<'a, $type>;
#[inline]
fn mul(self, other: $type) -> Self::Output {
let res = Array::zeros(&self.dim, self.state).unwrap();
$cublas_func(other, &self, &res).unwrap();
res
}
}
impl<'a> ops::Mul<Array<'a, $type>> for $type {
type Output = Array<'a, $type>;
#[inline]
fn mul(self, other: Array<'a, $type>) -> Self::Output {
other * self
}
}
};
}
mul_axpy!(f32, saxpy);
mul_axpy!(f64, daxpy);
macro_rules! div_axpy {
($type: ty, $cublas_func: ident) => {
impl<'a> ops::Div<$type> for Array<'a, $type> {
type Output = Array<'a, $type>;
#[inline]
fn div(self, other: $type) -> Self::Output {
let other = (1 as $type) / other;
self * other
}
}
impl<'a> ops::Div<Array<'a, $type>> for $type {
type Output = Array<'a, $type>;
#[inline]
fn div(self, other: Array<'a, $type>) -> Self::Output {
let div = (1 as $type) / self;
div * other
}
}
};
}
div_axpy!(f32, saxpy);
div_axpy!(f64, saxpy);
//////////// Array and Array
impl<'a> ops::Mul<Array<'a, f32>> for Array<'a, f32> {
type Output = Array<'a, f32>;
fn mul(self, other: Array<'a, f32>) -> Self::Output {
if self.dim != other.dim {
panic!("add operation dimension mismatch");
}
if self.order != other.order {
todo!();
}
if self.dtype != other.dtype {
panic!("data type is not same ");
}
element_wise_product(self, other)
}
}
impl<'a> ops::Div<Array<'a, f32>> for Array<'a, f32> {
type Output = Array<'a, f32>;
fn div(self, other: Array<'a, f32>) -> Self::Output {
if self.dim != other.dim {
panic!("add operation dimension mismatch");
}
if self.order != other.order {
todo!();
}
if self.dtype != other.dtype {
panic!("data type is not same ");
}
element_wise_devide(self, other)
}
}
// TODO
// impl Mul and Div Array<'a, f64> Array<'a, f64>
| true |
8fe9de3e4e4c02068909910dfc9e2b05d80f1e41
|
Rust
|
horou-dsk/nes-online-server
|
/examples/thread-buffer/main.rs
|
UTF-8
| 4,446 | 3.0625 | 3 |
[] |
no_license
|
use std::time::Duration;
use std::thread;
use chrono::Local;
use std::thread::JoinHandle;
use actix::{Actor, Context, Addr, AsyncContext, Message, Handler, Running, ActorContext};
use actix_rt::System;
const MS_PER_UPDATE: f64 = 100000000.0 / 6.0;
pub struct Room {
frame_buffer: Vec<Vec<u8>>,
addr: Option<Addr<Room>>,
stopped: bool,
}
impl Actor for Room {
type Context = Context<Self>;
fn started(&mut self, ctx: &mut Self::Context) {
self.addr = Some(ctx.address());
}
//
// fn stopping(&mut self, ctx: &mut Self::Context) -> Running {
// let addr = ctx.address();
// println!("正在关闭");
// addr.do_send(Msg { id: -3 });
// Running::Stop
// }
fn stopped(&mut self, ctx: &mut Self::Context) {
println!("已关闭");
}
}
#[derive(Message)]
#[rtype(isize)]
struct Msg {
id: i64,
}
impl Handler<Msg> for Room {
type Result = isize;
fn handle(&mut self, msg: Msg, ctx: &mut Context<Self>) -> Self::Result {
if msg.id == -3 {
ctx.stop();
// self.stopped = true;
}
if msg.id < 0 {
self.startup(msg.id);
} else {
let mut frame_buffer = &mut self.frame_buffer;
// println!("{}", msg.id);
while let Some(v) = frame_buffer.pop() {
// println!("{:?}", v);
// addr.do_send();
}
}
if self.stopped {
-1
} else {
0
}
}
}
impl Room {
pub fn new() -> Self {
Self {
frame_buffer: vec![vec![1, 8, 24]; 5],
addr: None,
stopped: false,
}
}
pub fn startup(&mut self, id: i64) {
if let Some(addr) = self.addr.clone() {
actix::spawn(async move {
let mut previous = Local::now().timestamp_millis();
let mut next_game_tick = Local::now().timestamp_nanos() as f64;
let mut fps = 0;
loop {
let current = Local::now().timestamp_millis();
if current - previous >= 1000 {
if id == -2 {
println!("fps-- = {}", fps);
} else {
println!("fps = {}", fps);
}
fps = 0;
previous = current;
}
fps += 1;
next_game_tick += MS_PER_UPDATE;
let sleep_time = next_game_tick - Local::now().timestamp_nanos() as f64;
let result = addr.send(Msg { id: fps }).await;
match result {
Ok(i) => {
if i < 0 {
println!("结束");
break;
}
}
Err(err) => {
println!("{:?}", err);
break;
}
}
if sleep_time > 0.0 {
actix::clock::delay_for(Duration::from_nanos(sleep_time as u64)).await;
// tokio::time::sleep(Duration::from_nanos(sleep_time as u64)).await;
// thread::sleep(if id == -2 {Duration::from_nanos(sleep_time as u64)} else {Duration::from_secs(3)});
}
}
});
}
}
}
fn main() {
let system = System::new("room");
let mut room = Room::new().start();
room.do_send(Msg { id: -1 });
println!("我他吗服了");
thread::spawn(move || {
thread::sleep(Duration::from_secs(5));
room.do_send(Msg { id: -3 });
});
// thread::sleep(Duration::from_millis(500));
// let mut room = Room::new().start();
// room.do_send(Msg { id: -2 });
// let mut room = Room::new().start();
// room.do_send(Msg { id: 0 });
// let mut room = Room::new().start();
// room.do_send(Msg { id: 0 });
// let mut room = Room::new().start();
// room.do_send(Msg { id: 0 });
// let mut room = Room::new().start();
// room.do_send(Msg { id: 0 });
// room.send().aw
// join_handle.join();
// System::current().stop();
system.run();
// thread::sleep(Duration::from_secs(8));
}
| true |
fb26054c93520ee5694b67f253639fd3936fa7e5
|
Rust
|
DaTa-/advent-of-code-2020
|
/src/bin/day15_part2.rs
|
UTF-8
| 774 | 3.34375 | 3 |
[
"MIT"
] |
permissive
|
use std::collections::HashMap;
fn main() {
const MAX_NUMBERS: u32 = 30000000;
let input = "6,13,1,15,2,0"; // "0,3,6";
let mut input = input.split(',').rev().map(|n| n.parse().unwrap());
let mut last_num = input.next().unwrap();
let input = input.rev();
let mut spoken_count = 0;
let mut spoken_numbers = HashMap::new();
for n in input {
spoken_numbers.insert(n, spoken_count);
spoken_count += 1;
}
spoken_count += 1; // last number isn't mapped
for i in spoken_count..MAX_NUMBERS {
let last_num_idx = i - 1;
last_num = spoken_numbers
.insert(last_num, last_num_idx)
.map_or(0, |prev| last_num_idx - prev);
}
let answer = last_num;
println!("{}", answer);
}
| true |
8f6ea80a2e908780e626e13991cb48fbde3d020e
|
Rust
|
maximeborges/svd2rust_efm32gg990
|
/src/prs/swpulse.rs
|
UTF-8
| 9,772 | 2.734375 | 3 |
[
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
#[doc = r" Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::SWPULSE {
#[doc = r" Writes to the register"]
#[inline]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
let mut w = W::reset_value();
f(&mut w);
self.register.set(w.bits);
}
}
#[doc = r" Proxy"]
pub struct _CH0PULSEW<'a> {
w: &'a mut W,
}
impl<'a> _CH0PULSEW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 0;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _CH1PULSEW<'a> {
w: &'a mut W,
}
impl<'a> _CH1PULSEW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 1;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _CH2PULSEW<'a> {
w: &'a mut W,
}
impl<'a> _CH2PULSEW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 2;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _CH3PULSEW<'a> {
w: &'a mut W,
}
impl<'a> _CH3PULSEW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 3;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _CH4PULSEW<'a> {
w: &'a mut W,
}
impl<'a> _CH4PULSEW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 4;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _CH5PULSEW<'a> {
w: &'a mut W,
}
impl<'a> _CH5PULSEW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 5;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _CH6PULSEW<'a> {
w: &'a mut W,
}
impl<'a> _CH6PULSEW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 6;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _CH7PULSEW<'a> {
w: &'a mut W,
}
impl<'a> _CH7PULSEW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 7;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _CH8PULSEW<'a> {
w: &'a mut W,
}
impl<'a> _CH8PULSEW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 8;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _CH9PULSEW<'a> {
w: &'a mut W,
}
impl<'a> _CH9PULSEW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 9;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _CH10PULSEW<'a> {
w: &'a mut W,
}
impl<'a> _CH10PULSEW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 10;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _CH11PULSEW<'a> {
w: &'a mut W,
}
impl<'a> _CH11PULSEW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 11;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
impl W {
#[doc = r" Reset value of the register"]
#[inline]
pub fn reset_value() -> W {
W { bits: 0 }
}
#[doc = r" Writes raw bits to the register"]
#[inline]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bit 0 - Channel 0 Pulse Generation"]
#[inline]
pub fn ch0pulse(&mut self) -> _CH0PULSEW {
_CH0PULSEW { w: self }
}
#[doc = "Bit 1 - Channel 1 Pulse Generation"]
#[inline]
pub fn ch1pulse(&mut self) -> _CH1PULSEW {
_CH1PULSEW { w: self }
}
#[doc = "Bit 2 - Channel 2 Pulse Generation"]
#[inline]
pub fn ch2pulse(&mut self) -> _CH2PULSEW {
_CH2PULSEW { w: self }
}
#[doc = "Bit 3 - Channel 3 Pulse Generation"]
#[inline]
pub fn ch3pulse(&mut self) -> _CH3PULSEW {
_CH3PULSEW { w: self }
}
#[doc = "Bit 4 - Channel 4 Pulse Generation"]
#[inline]
pub fn ch4pulse(&mut self) -> _CH4PULSEW {
_CH4PULSEW { w: self }
}
#[doc = "Bit 5 - Channel 5 Pulse Generation"]
#[inline]
pub fn ch5pulse(&mut self) -> _CH5PULSEW {
_CH5PULSEW { w: self }
}
#[doc = "Bit 6 - Channel 6 Pulse Generation"]
#[inline]
pub fn ch6pulse(&mut self) -> _CH6PULSEW {
_CH6PULSEW { w: self }
}
#[doc = "Bit 7 - Channel 7 Pulse Generation"]
#[inline]
pub fn ch7pulse(&mut self) -> _CH7PULSEW {
_CH7PULSEW { w: self }
}
#[doc = "Bit 8 - Channel 8 Pulse Generation"]
#[inline]
pub fn ch8pulse(&mut self) -> _CH8PULSEW {
_CH8PULSEW { w: self }
}
#[doc = "Bit 9 - Channel 9 Pulse Generation"]
#[inline]
pub fn ch9pulse(&mut self) -> _CH9PULSEW {
_CH9PULSEW { w: self }
}
#[doc = "Bit 10 - Channel 10 Pulse Generation"]
#[inline]
pub fn ch10pulse(&mut self) -> _CH10PULSEW {
_CH10PULSEW { w: self }
}
#[doc = "Bit 11 - Channel 11 Pulse Generation"]
#[inline]
pub fn ch11pulse(&mut self) -> _CH11PULSEW {
_CH11PULSEW { w: self }
}
}
| true |
fcd7d292f04634a34c84f8f937434b452cfbe7c7
|
Rust
|
ohazi/cryptopals
|
/src/set1.rs
|
UTF-8
| 17,184 | 3.3125 | 3 |
[] |
no_license
|
pub fn base64_encode(bytes: &[u8]) -> Result<String, &'static str> {
let mut result = String::new();
for group in bytes.chunks(3) {
let extended = match group.len() {
1 => [group[0], 0, 0],
2 => [group[0], group[1], 0],
3 => [group[0], group[1], group[2]],
_ => return Err("chunk too large!"),
};
for i in 0..=3 {
let sextet = match i {
0 => ((extended[0] & 0xFC) >> 2),
1 => ((extended[0] & 0x03) << 4) | ((extended[1] & 0xF0) >> 4),
2 => ((extended[1] & 0x0F) << 2) | ((extended[2] & 0xC0) >> 6),
3 => ((extended[2] & 0x3F) << 0),
_ => return Err("too many groups!"),
};
let symbol: char = match sextet {
c @ 0...25 => char::from(0x41 + c),
c @ 26...51 => char::from(0x61 + c - 26),
c @ 52...61 => char::from(0x30 + c - 52),
62 => '+',
63 => '/',
_ => return Err("too many bits!"),
};
if (group.len() as i8) - (i as i8) >= 0 {
result.push(symbol);
} else {
result.push('=');
}
}
}
return Ok(result);
}
pub fn base64_decode(encoded: &str) -> Result<Vec<u8>, &'static str> {
let mut result: Vec<u8> = Vec::with_capacity(encoded.len() * 3 / 4);
let encoded_stripped = encoded
.as_bytes()
.iter()
.cloned()
.filter(|letter| match *letter {
b'\n' => false,
_ => true,
})
.collect::<Vec<u8>>();
for group in encoded_stripped.chunks(4) {
if group.len() != 4 {
return Err("chunk too small!");
}
let mut padding: i8 = 0;
let sextets = group
.iter()
.map(|letter| match *letter {
c @ b'A'...b'Z' => Ok(c as u8 - 0x41),
c @ b'a'...b'z' => Ok(c as u8 - 0x61 + 26),
c @ b'0'...b'9' => Ok(c as u8 - 0x30 + 52),
b'+' => Ok(62),
b'/' => Ok(63),
b'=' => {
padding += 1;
Ok(0)
}
_ => Err("illegal character!"),
})
.collect::<Result<Vec<u8>, &'static str>>()?;
for i in 0..=2 {
let octet = match i {
0 => ((sextets[0] & 0x3F) << 2) | ((sextets[1] & 0x30) >> 4),
1 => ((sextets[1] & 0x0F) << 4) | ((sextets[2] & 0x3C) >> 2),
2 => ((sextets[2] & 0x03) << 6) | ((sextets[3] & 0x3F) >> 0),
_ => return Err("too many octets!"),
};
if (i as i8) < (3 - padding) {
result.push(octet);
}
}
}
return Ok(result);
}
pub fn xor(a: &[u8], b: &[u8]) -> Result<Vec<u8>, &'static str> {
if a.len() != b.len() {
return Err("buffer size mismatch");
}
let result = a.iter()
.zip(b)
.map(|pair| match pair {
(&aa, &bb) => aa ^ bb,
})
.collect::<Vec<u8>>();
return Ok(result);
}
pub fn xor_in_place(data: &mut [u8], other: &[u8]) -> Result<usize, &'static str> {
if data.len() != other.len() {
return Err("buffer size mismatch");
}
let xor_count = data.iter_mut()
.zip(other)
.map(|(data_elem, other_elem)| {
*data_elem ^= other_elem;
})
.count();
return Ok(xor_count);
}
pub fn xor_repeat(plaintext: &[u8], key: &[u8]) -> Vec<u8> {
let result = plaintext
.iter()
.zip(key.iter().cycle())
.map(|pair| match pair {
(&aa, &bb) => aa ^ bb,
})
.collect::<Vec<u8>>();
return result;
}
use std::collections::BTreeMap;
pub fn char_freq_score(text: &[u8]) -> f64 {
let mut non_printable_count = 0;
let letter_freq: BTreeMap<u8, f64> = btreemap! {
b'a' => 0.08167,
b'b' => 0.01492,
b'c' => 0.02782,
b'd' => 0.04253,
b'e' => 0.12702,
b'f' => 0.02228,
b'g' => 0.02015,
b'h' => 0.06094,
b'i' => 0.06966,
b'j' => 0.00153,
b'k' => 0.00772,
b'l' => 0.04025,
b'm' => 0.02406,
b'n' => 0.06749,
b'o' => 0.07507,
b'p' => 0.01929,
b'q' => 0.00095,
b'r' => 0.05987,
b's' => 0.06327,
b't' => 0.09056,
b'u' => 0.02758,
b'v' => 0.00978,
b'w' => 0.02360,
b'x' => 0.00150,
b'y' => 0.01974,
b'z' => 0.00074,
};
let mut letter_counts: BTreeMap<u8, u32> = BTreeMap::new();
for letter in b'a'..=b'z' {
letter_counts.insert(letter, 0);
}
let mut num_letters = 0;
for letter in text {
match *letter {
// null
0 => {}
// non-printable characters
1...9 => non_printable_count += 1,
// newline
10 => {}
// more non-printable characters
11...31 => non_printable_count += 1,
// space
32 => {}
// printable symbols, including digits (ascii '!' - '@')
33...64 => {}
// upper-case letters
c @ 65...90 => {
*letter_counts.get_mut(&(c - 65 + 97)).unwrap() += 1;
num_letters += 1;
}
// more printable symbols (ascii '[' - '`')
91...96 => {}
// lower-case letters
c @ 97...122 => {
*letter_counts.get_mut(&c).unwrap() += 1;
num_letters += 1;
}
// more printable symbols (ascii '{' - '~')
123...126 => {}
// non-printable characters
_ => non_printable_count += 1,
}
}
if num_letters == 0 {
return 10000.0 + (non_printable_count as f64 * 500.0);
}
let mut chisquared = 0.0;
for (key, prob) in letter_freq {
chisquared += (num_letters as f64)
* ((*letter_counts.get(&key).unwrap() as f64 / num_letters as f64) - prob).powf(2.0)
/ prob;
}
return chisquared + (non_printable_count as f64 * 500.0);
}
extern crate bit_vec;
use self::bit_vec::BitVec;
pub fn hamming_distance(a: &[u8], b: &[u8]) -> Result<u32, &'static str> {
if a.len() != b.len() {
return Err("sequences must have same length");
}
let result = a.iter()
.zip(b.iter())
.map(|(aa, bb)| -> u32 {
BitVec::from_bytes(&[aa ^ bb])
.iter()
.map(|val| val as u32)
.sum()
})
.sum();
return Ok(result);
}
pub fn find_best_single_byte_xor(ciphertext: &[u8]) -> u8 {
let mut decoded: Vec<(f64, u8, Vec<u8>)> = Vec::with_capacity(256);
for i in 0..=256 {
let key: Vec<u8> = vec![i as u8; ciphertext.len()];
if let Ok(decoded_bytes) = xor(ciphertext, &key) {
let score = char_freq_score(&decoded_bytes);
decoded.push((score, i as u8, decoded_bytes));
}
}
decoded.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap());
let (_, key, _) = decoded[0];
return key;
}
pub fn to_hex(data: &[u8]) -> String {
data.iter()
.map(|b| format!("{:02x}", b))
.collect::<Vec<String>>()
.join("")
}
#[cfg(test)]
mod tests {
use set1;
extern crate hex;
use self::hex::FromHex;
#[test]
fn base64_encode() {
let example_hex = "49276d206b696c6c696e6720796f757220627261696e206c\
696b65206120706f69736f6e6f7573206d757368726f6f6d";
let example_bytes = Vec::from_hex(example_hex).unwrap();
if let Ok(b64) = set1::base64_encode(&example_bytes) {
assert_eq!(
b64,
"SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t"
);
} else {
panic!();
}
let test = "foobar".as_bytes();
if let Ok(b64) = set1::base64_encode(&test) {
assert_eq!(b64, "Zm9vYmFy");
} else {
panic!();
}
}
#[test]
fn base64_decode() {
let example_b64 = "SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t";
if let Ok(example) = set1::base64_decode(example_b64) {
assert_eq!(
example,
Vec::from_hex(
"49276d206b696c6c696e6720796f757220627261696e206c\
696b65206120706f69736f6e6f7573206d757368726f6f6d"
).unwrap()
);
} else {
panic!();
}
let b64 = "Zm9vYmFy";
if let Ok(test) = set1::base64_decode(&b64) {
assert_eq!(test, "foobar".as_bytes());
} else {
panic!();
}
}
#[test]
fn xor() {
let a = "1c0111001f010100061a024b53535009181c";
let b = "686974207468652062756c6c277320657965";
let res = "746865206b696420646f6e277420706c6179";
let a_bytes = Vec::from_hex(a).unwrap();
let b_bytes = Vec::from_hex(b).unwrap();
let res_bytes = Vec::from_hex(res).unwrap();
match set1::xor(&a_bytes, &b_bytes) {
Ok(r) => assert_eq!(r, res_bytes),
Err(str) => panic!(str),
};
}
use std::collections::BTreeMap;
use std::str;
#[test]
fn single_byte_xor_cipher() {
let encoded = "1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736";
let encoded_bytes = Vec::from_hex(encoded).unwrap();
//don't want to use a map here, because we'll lose any values with the same score
//let mut decoded: BTreeMap<u64, (u8, Vec<u8>)> = BTreeMap::new();
let mut decoded: Vec<(f64, u8, Vec<u8>)> = Vec::with_capacity(256);
for i in 0..=256 {
let key: Vec<u8> = vec![i as u8; encoded_bytes.len()];
if let Ok(decoded_bytes) = set1::xor(&encoded_bytes, &key) {
let score = set1::char_freq_score(&decoded_bytes);
//decoded.insert((score * 1000.0) as u64, (i as u8, decoded_bytes));
decoded.push((score, i as u8, decoded_bytes));
}
}
decoded.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap());
//let &(key, ref value) = decoded.values().next().unwrap();
let (_, key, ref value) = decoded[0];
assert_eq!(key, 88);
assert_eq!(
str::from_utf8(value.as_slice()).unwrap(),
"Cooking MC's like a pound of bacon"
);
}
use std::fs::File;
use std::io::BufReader;
use std::io::BufRead;
#[test]
fn detect_single_char_xor() {
let file = File::open("challenge-data/4.txt").unwrap();
let reader = BufReader::new(file);
let mut decoded = BTreeMap::new();
let mut line_num = 0;
for line in reader.lines() {
if let Ok(line) = line {
let line_bytes = Vec::from_hex(line).unwrap();
for i in 0..=256 {
let key: Vec<u8> = vec![i as u8; line_bytes.len()];
if let Ok(decoded_bytes) = set1::xor(&line_bytes, &key) {
let score = set1::char_freq_score(&decoded_bytes);
decoded.insert((score * 1000.0) as u64, (line_num, i as u8, decoded_bytes));
}
}
}
line_num += 1;
}
let mut found = false;
for (score, &(line, key, ref value)) in decoded.iter() {
let score: f64 = *score as f64 / 1000.0;
if score < 100.0 {
if line == 170 && key == 53 {
let value = str::from_utf8(value).unwrap();
assert_eq!(value, "Now that the party is jumping\n");
found = true;
}
}
}
assert!(found, "decrypted string not found!");
}
#[test]
fn repeating_key_xor() {
let plaintext = "Burning 'em, if you ain't quick and nimble\n\
I go crazy when I hear a cymbal";
let key = "ICE";
let plaintext = plaintext.as_bytes();
let key = key.as_bytes();
let ciphertext = set1::xor_repeat(&plaintext, &key);
let ciphertext_ref = "0b3637272a2b2e63622c2e69692a23693a2a3c6324202d623d63343c2a26226\
324272765272a282b2f20430a652e2c652a3124333a653e2b2027630c692b20\
283165286326302e27282f";
let ciphertext_ref = Vec::from_hex(ciphertext_ref).unwrap();
assert_eq!(ciphertext, ciphertext_ref);
}
#[test]
fn hamming_distance() {
assert_eq!(
set1::hamming_distance("this is a test".as_bytes(), "wokka wokka!!!".as_bytes())
.unwrap(),
37
);
}
#[test]
fn break_repeating_key_xor() {
let mut f = File::open("challenge-data/6.txt").unwrap();
let mut encoded = String::new();
f.read_to_string(&mut encoded).unwrap();
let decoded = set1::base64_decode(&encoded).unwrap();
let mut results: Vec<(f32, usize)> = Vec::with_capacity(40);
for keysize in 2..=40 {
let sequences = decoded.chunks(keysize).collect::<Vec<&[u8]>>();
let norm_distances = sequences
.chunks(2)
.filter(|maybe_pair| maybe_pair.len() == 2)
.filter(|maybe_same_len| maybe_same_len[0].len() == maybe_same_len[1].len())
.map(|pair| {
set1::hamming_distance(pair[0], pair[1]).unwrap() as f32 / keysize as f32
})
.collect::<Vec<f32>>();
let norm_dist_avg: f32 = &norm_distances.iter().sum() / norm_distances.len() as f32;
results.push((norm_dist_avg, keysize));
}
results.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap());
let keysize = results[0].1;
assert_eq!(keysize, 29);
let sequences = decoded.chunks(keysize).collect::<Vec<&[u8]>>();
let mut transposed: Vec<Vec<u8>> = Vec::with_capacity(keysize);
for i in 0..keysize {
let mut line = Vec::with_capacity(sequences.len());
for j in 0..sequences.len() {
if i < sequences[j].len() {
line.push(sequences[j][i]);
}
}
transposed.push(line);
}
let mut key: Vec<u8> = Vec::with_capacity(keysize);
for block in transposed {
let key_byte = set1::find_best_single_byte_xor(&block);
key.push(key_byte);
}
assert_eq!(
str::from_utf8(&key).unwrap(),
"Terminator X: Bring the noise"
);
let plaintext = set1::xor_repeat(&decoded, &key);
let plaintext = str::from_utf8(&plaintext).unwrap();
let mut f = File::open("challenge-data/6_plaintext.txt").unwrap();
let mut plaintext_ref = String::new();
f.read_to_string(&mut plaintext_ref).unwrap();
assert_eq!(plaintext, plaintext_ref);
}
extern crate openssl;
use self::openssl::symm;
use self::openssl::symm::Cipher;
use std::io::prelude::*;
#[test]
fn aes_ecb_mode() {
let mut f = File::open("challenge-data/7.txt").unwrap();
let mut encoded = String::new();
f.read_to_string(&mut encoded).unwrap();
let decoded = set1::base64_decode(&encoded).unwrap();
let plaintext = symm::decrypt(
Cipher::aes_128_ecb(),
"YELLOW SUBMARINE".as_bytes(),
None,
&decoded,
).unwrap();
let plaintext = str::from_utf8(&plaintext).unwrap();
let mut f = File::open("challenge-data/7_plaintext.txt").unwrap();
let mut plaintext_ref = String::new();
f.read_to_string(&mut plaintext_ref).unwrap();
assert_eq!(plaintext, plaintext_ref);
}
#[test]
fn detect_aes_ecb_mode() {
let f = File::open("challenge-data/8.txt").unwrap();
let reader = BufReader::new(f);
let mut results: Vec<(u32, usize, Vec<u8>)> = Vec::new();
let mut linenum = 0;
for line in reader.lines() {
if let Ok(line) = line {
let line_bytes = Vec::from_hex(line).unwrap();
let sequences = line_bytes.chunks(16).collect::<Vec<&[u8]>>();
let mut scores: Vec<u32> = Vec::new();
for i in 0..sequences.len() {
for j in (i + 1)..sequences.len() {
let score = set1::hamming_distance(sequences[i], sequences[j]).unwrap();
scores.push(score);
}
}
scores.sort();
results.push((scores[0], linenum, line_bytes.clone()));
linenum += 1;
}
}
results.sort_by_key(|elem| elem.0);
assert_eq!(results[0].1, 132);
}
}
| true |
29f35c3cc75708649c82ba0b54a1d4736a48b151
|
Rust
|
flip1995/rust-clippy
|
/tests/ui/incorrect_partial_ord_impl_on_ord_type_fully_qual.rs
|
UTF-8
| 1,083 | 3 | 3 |
[
"MIT",
"Apache-2.0"
] |
permissive
|
// This test's filename is... a bit verbose. But it ensures we suggest the correct code when `Ord`
// is not in scope.
#![no_main]
#![no_implicit_prelude]
//@no-rustfix
extern crate std;
use std::cmp::{self, Eq, Ordering, PartialEq, PartialOrd};
use std::option::Option::{self, Some};
use std::todo;
// lint
#[derive(Eq, PartialEq)]
struct A(u32);
impl cmp::Ord for A {
fn cmp(&self, other: &Self) -> Ordering {
todo!();
}
}
impl PartialOrd for A {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
// NOTE: This suggestion is wrong, as `Ord` is not in scope. But this should be fine as it isn't
// automatically applied
todo!();
}
}
#[derive(Eq, PartialEq)]
struct B(u32);
impl B {
fn cmp(&self, other: &Self) -> Ordering {
todo!();
}
}
impl cmp::Ord for B {
fn cmp(&self, other: &Self) -> Ordering {
todo!();
}
}
impl PartialOrd for B {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
// This calls `B.cmp`, not `Ord::cmp`!
Some(self.cmp(other))
}
}
| true |
928b3d6772317b8ad4af53024c337163900bcfbd
|
Rust
|
snuk182/anl-rs
|
/src/implicit_modifier.rs
|
UTF-8
| 2,700 | 2.96875 | 3 |
[
"MIT",
"Apache-2.0"
] |
permissive
|
use super::implicit_base::ImplicitModuleBase;
use super::ImplicitModule;
use super::curve::Curve;
use super::utility::clamp;
use std::rc::Rc;
use std::cell::RefCell;
pub struct ImplicitModifier {
base: ImplicitModuleBase,
source: Option<Rc<RefCell<ImplicitModule>>>,
curve: Curve<f64>,
}
impl ImplicitModifier {
pub fn new() -> ImplicitModifier {
ImplicitModifier {
base: Default::default(),
source: None,
curve: Curve::new(),
}
}
pub fn with_capacity(capacity: usize) -> ImplicitModifier {
ImplicitModifier {
base: Default::default(),
source: None,
curve: Curve::with_capacity(capacity),
}
}
pub fn set_source(&mut self, source: Option<Rc<RefCell<ImplicitModule>>>) {
self.source = source;
}
pub fn add_control_point(&mut self, v: f64, p: f64) {
self.curve.push_point(v, p);
}
pub fn clear_control_points(&mut self) {
self.curve.clear();
}
}
impl ImplicitModule for ImplicitModifier {
fn get_2d(&mut self, x: f64, y: f64) -> f64 {
if let Some(ref s) = self.source {
let mut v = s.borrow_mut().get_2d(x, y);
// Should clamp; make sure inputs are in range
// v=(v+1.0 ) * 0.5;
v = clamp(v, 0.0, 1.0);
self.curve.linear_interp(v)
} else {
0.0
}
}
fn get_3d(&mut self, x: f64, y: f64, z: f64) -> f64 {
if let Some(ref s) = self.source {
let mut v = s.borrow_mut().get_3d(x, y, z);
// v=(v+1)*0.5;
v = clamp(v, 0.0, 1.0);
self.curve.linear_interp(v)
} else {
0.0
}
}
fn get_4d(&mut self, x: f64, y: f64, z: f64, w: f64) -> f64 {
if let Some(ref s) = self.source {
let mut v = s.borrow_mut().get_4d(x, y, z, w);
// Should clamp; make sure inputs are in range
// v=(v+1.0 ) * 0.5;
v = clamp(v, 0.0, 1.0);
self.curve.linear_interp(v)
} else {
0.0
}
}
fn get_6d(&mut self, x: f64, y: f64, z: f64, w: f64, u: f64, v: f64) -> f64 {
if let Some(ref s) = self.source {
let mut val = s.borrow_mut().get_6d(x, y, z, w, u, v);
// Should clamp; make sure inputs are in range
// val=(val+1.0 ) * 0.5;
val = clamp(val, 0.0, 1.0);
self.curve.linear_interp(val)
} else {
0.0
}
}
fn spacing(&self) -> f64 {
self.base.spacing
}
fn set_deriv_spacing(&mut self, s: f64) {
self.base.spacing = s;
}
}
| true |
aa3390b1038ebecc22a59b8f6044187df6f5ff2b
|
Rust
|
dduan/mmm
|
/src/mmm/commands/git_command.rs
|
UTF-8
| 2,577 | 3.109375 | 3 |
[] |
no_license
|
use std::process;
use std::io::Write;
use super::Command;
use super::utils;
use termcolor::{
Buffer,
BufferWriter,
Color,
ColorChoice,
};
pub struct GitCommand {
in_git: bool
}
fn run_git(arg1: String, arg2: String) -> bool {
let mut git = process::Command::new("git");
git.arg(arg1);
git.arg(arg2);
let git_proc = git.spawn();
if !git_proc.is_ok() {
return false
}
git_proc.unwrap()
.wait()
.map(|s| s.success())
.unwrap_or(false)
}
fn is_in_git() -> bool {
process::Command::new("git")
.arg("rev-parse")
.arg("--is-inside-work-tree")
.output()
.map(|o| o.status.success())
.ok()
.unwrap_or(false)
}
impl Command for GitCommand {
fn new() -> GitCommand {
GitCommand {
in_git: is_in_git()
}
}
fn name(&self) -> String { String::from("Git") }
fn hotkey_pos(&self) -> usize { 0 }
#[allow(unused_variables)]
fn exe_msg(&self, path: &String) -> Option<String> {
Some(String::from("Now, pick a git subcommand\n"))
}
fn should_show_if_path_exists(&self) -> bool { self.in_git }
fn should_show_if_path_exists_not(&self) -> bool { false }
fn need_followup(&self) -> bool { true }
fn followup_prompt(&self, path: &String) -> Buffer {
let mut buffer = BufferWriter::stdout(ColorChoice::Auto).buffer();
write!(&mut buffer, "`git ").expect("Buffer write error");
utils::write(&mut buffer, ".", Color::Yellow);
write!(&mut buffer, " {}`\n ", path).expect("Buffer write error");
utils::write(&mut buffer, "└", Color::Yellow);
write!(&mut buffer, " ").expect("Buffer write error");
buffer
}
fn execute(&self, path: &String, followup_input: Option<String>) -> bool {
let subcommand = String::from(followup_input.unwrap_or_default().trim_end());
if subcommand.is_empty() {
utils::elog("Please provide a valid git subcommand.\n");
return false
}
let whole_command = format!("git {} {}", subcommand, path);
let stdout = BufferWriter::stdout(ColorChoice::Auto);
let mut buffer = stdout.buffer();
write!(&mut buffer, "[mmm] Running `").expect("Buffer write failure");
utils::write(&mut buffer, whole_command, Color::Yellow);
write!(&mut buffer, "`\n").expect("Buffer write failure");
stdout.print(&buffer).expect("Stdout print failure");
run_git(subcommand, path.to_string())
}
}
| true |
e61398240a9ef88ed22e461bc2267be758c20494
|
Rust
|
rust-lang/rust
|
/tests/ui/suggestions/assoc-ct-for-assoc-method.rs
|
UTF-8
| 618 | 3.296875 | 3 |
[
"Apache-2.0",
"LLVM-exception",
"NCSA",
"BSD-2-Clause",
"LicenseRef-scancode-unicode",
"MIT",
"LicenseRef-scancode-other-permissive"
] |
permissive
|
struct MyS;
impl MyS {
const FOO: i32 = 1;
fn foo() -> MyS {
MyS
}
}
fn main() {
let x: i32 = MyS::foo;
//~^ ERROR mismatched types
//~| HELP try referring to the
let z: i32 = i32::max;
//~^ ERROR mismatched types
//~| HELP try referring to the
// This example is still broken though... This is a hard suggestion to make,
// because we don't have access to the associated const probing code to make
// this suggestion where it's emitted, i.e. in trait selection.
let y: i32 = i32::max - 42;
//~^ ERROR cannot subtract
//~| HELP use parentheses
}
| true |
09ffc35f115afaffcc555e65691eefa7ae643f20
|
Rust
|
mcqueen256/gol-wasm
|
/src/universe.rs
|
UTF-8
| 13,211 | 2.75 | 3 |
[] |
no_license
|
use crate::utils;
use crate::config;
use crate::rle_loader;
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use web_sys;
use getrandom;
#[wasm_bindgen]
#[repr(u8)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Cell {
Dead = 0,
Alive = 1
}
#[wasm_bindgen]
pub struct Universe {
width: u32,
height: u32,
cells: Vec<Cell>,
canvas: Option<web_sys::HtmlCanvasElement>,
canvas_cell:Option<web_sys::HtmlCanvasElement>,
config: config::UniverseConfig,
visible_rows: u32,
visible_columns: u32,
visible_row_start_position: u32,
visible_column_start_position: u32,
}
/// Keep track of count of rows and columns
struct RowColCount {
rows: u32,
cols: u32,
}
impl Universe {
fn canvas_width(&self) -> u32 {
if let Some(canvas) = &self.canvas {
canvas.width()
} else {
0
}
}
fn canvas_height(&self) -> u32 {
if let Some(canvas) = &self.canvas {
canvas.height()
} else {
0
}
}
fn calculate_visible_grid_size(&self) -> RowColCount {
let canvas_width = self.canvas.as_ref().unwrap().width();
let canvas_height = self.canvas.as_ref().unwrap().height();
let line_width = self.config.border_width;
let cell_width = self.config.get_cell_size();
let cell_height = self.config.get_cell_size();
let visible_columns = if self.config.allow_overflow {
(canvas_width + line_width) / (cell_width + line_width)
} else {
let columns = (canvas_width + line_width) as f64 / (cell_width + line_width) as f64;
columns.ceil() as u32
};
log!("visible_columns: {}", visible_columns);
let visible_rows = if self.config.allow_overflow {
(canvas_height + line_width) / (cell_height + line_width)
} else {
let rows = (canvas_height + line_width) as f64 / (cell_height + line_width) as f64;
rows.ceil() as u32
};
log!("visible_rows: {}", visible_rows);
RowColCount {
rows: visible_rows,
cols: visible_columns,
}
}
// fn visible_grid_width(&self) -> u32 {
// }
/// Called when a canvas is available
fn build(&mut self) {
// calculate the visibility of
let row_col_count = self.calculate_visible_grid_size();
self.visible_rows = row_col_count.rows;
self.visible_columns = row_col_count.cols;
let padding = self.config.get_padding();
if let Some((w, h)) = self.config.get_override_size() {
self.width = w + 2 * padding;
self.height = h + 2 * padding;
if self.width < self.visible_columns {
self.visible_columns = self.width;
}
if self.height < self.visible_rows {
self.visible_rows = self.height;
}
log!("Overriding visible_columns ({}) visible_rows({})", self.visible_columns, self.visible_rows);
} else {
}
self.visible_row_start_position = (self.height - self.visible_rows) / 2;
self.visible_column_start_position = (self.width - self.visible_columns) / 2;
// Generate random cells
let mut rand_cells = vec![0u8; (self.width * self.height) as usize];
getrandom::getrandom(&mut rand_cells[..]).expect("random cell generation failed");
self.cells = rand_cells.into_iter().map(|cell| if cell%2==0 {Cell::Dead} else {Cell::Alive}).collect();
// self.cells = vec![Cell::Dead; (self.width * self.height) as usize];
// let cells = rle_loader::load_spaceships(self.width, self.height);
}
/// Check if the cell is within the visibility bounding box.
fn is_visible(&self, row: u32, col: u32) -> bool {
let row_lower = self.visible_row_start_position;
let row_upper = row_lower + self.visible_rows; // up to but not including
let col_lower = self.visible_column_start_position;
let col_upper = col_lower + self.visible_columns; // up to but not including
// log!("row_lower = {}", row_lower);
// log!("row_upper = {}", row_upper);
// log!("col_lower = {}", col_lower);
// log!("col_upper = {}", col_upper);
// log!("row = {}", row);
// log!("col = {}", col);
(row_lower <= row && row < row_upper) && (col_lower <= col && col < col_upper)
}
fn translate_to_visible_row_col(&self, row: u32, col:u32) -> (u32, u32) {
(row - self.visible_row_start_position, col - self.visible_column_start_position)
}
fn get_index(&self, row: u32, column: u32) -> usize {
(row * self.width + column) as usize
}
fn living_neighbor_count(&self, row: u32, col: u32) -> u8 {
let mut count = 0;
for delta_row in [self.height - 1, 0, 1].iter().cloned() {
for delta_col in [self.width - 1, 0, 1].iter().cloned() {
if delta_col == 0 && delta_row == 0 {
continue;
}
let neighbor_row = (row + delta_row) % self.height;
let neighbor_col = (col + delta_col) % self.width;
let idx = self.get_index(neighbor_row, neighbor_col);
count += self.cells[idx] as u8;
}
}
count
}
}
#[wasm_bindgen]
impl Universe {
/// Create a new Universe with default parameters.
///
/// ```
/// let universe = Universe::new();
/// ```
pub fn new() -> Self {
utils::set_panic_hook();
Universe {
canvas: None,
config: config::UniverseConfig::new(),
width: 0,
height: 0,
cells: vec![],
visible_rows: 0,
visible_columns: 0,
visible_row_start_position: 0,
visible_column_start_position: 0,
}
}
pub fn from(conf: config::UniverseConfig) -> Self {
utils::set_panic_hook();
Universe {
canvas: None,
config: conf,
width: 0,
height: 0,
cells: vec![],
visible_columns: 0,
visible_rows: 0,
visible_row_start_position: 0,
visible_column_start_position: 0,
}
}
/// Connects a Canvas DOM reference to the Universe and constructs the
/// internal data structures.
pub fn connect_canvas(&mut self, canvas: web_sys::HtmlCanvasElement) {
log!("{:?}", canvas);
self.canvas = Some(canvas);
self.build();
log!("width: {}, height: {}", self.canvas_width(), self.canvas_height());
}
pub fn draw(&self) {
if let Some(canvas) = &self.canvas {
let context: web_sys::CanvasRenderingContext2d = canvas
.get_context("2d")
.unwrap()
.unwrap()
.dyn_into::<web_sys::CanvasRenderingContext2d>()
.unwrap();
use std::f64;
// Draw the outer circle.
// let cell_col_count = if self.config.allow_overlap {
// 0
// } else {
// }
let vis_col_count = self.visible_columns as f64;
let vis_row_count = self.visible_rows as f64;
let line_width = self.config.line_width as f64;
let border_width = self.config.border_width as f64;
let cell_size = self.config.get_cell_size() as f64;
let visible_grid_width = vis_col_count * (cell_size + line_width) - line_width;
let visible_grid_height = vis_row_count * (cell_size + line_width) - line_width;
// log!("vis_gid_wid {:.2}", visible_grid_width);
// log!("vis_gid_hei {:.2}", visible_grid_height);
// calculate offsets
let x_offset: f64 = ((canvas.width() as f64 - visible_grid_width) / 2.0).floor();
let y_offset: f64 = ((canvas.height() as f64 - visible_grid_height) / 2.0).floor();
// log!("offsets x={:.2}, y={:.2}", x_offset, y_offset);
// draw border
context.begin_path();
context.set_stroke_style(&JsValue::from(self.config.get_line_color()));
context.set_line_width(border_width);
context.rect(
x_offset - border_width / 2.0,
y_offset - border_width / 2.0,
visible_grid_width + border_width,
visible_grid_height + border_width
);
context.stroke();
if self.config.allow_overflow {
} else {
}
// draw dividing lines
context.begin_path();
context.set_stroke_style(&JsValue::from(self.config.get_line_color()));
context.set_line_width(line_width);
for i in 1..(self.visible_columns) {
context.move_to(
x_offset + line_width / 2.0 + i as f64 * (cell_size + line_width) - line_width,
y_offset,
);
context.line_to(
x_offset + line_width / 2.0 + i as f64 * (cell_size + line_width) - line_width,
y_offset + visible_grid_height,
);
}
for i in 1..(self.visible_rows) {
context.move_to(
x_offset,
y_offset + line_width / 2.0 + i as f64 * (cell_size + line_width) - line_width,
);
context.line_to(
x_offset + visible_grid_width,
y_offset + line_width / 2.0 + i as f64 * (cell_size + line_width) - line_width,
);
}
context.stroke();
// // draw cells
// context.begin_path();
// context.set_fill_style(&JsValue::from(self.config.get_cell_alive_color()));
// for col in 0..self.visible_columns {
// for row in 0..self.visible_rows {
// context.fill_rect(
// x_offset + col as f64 * (cell_size + line_width),
// y_offset + row as f64 * (cell_size + line_width),
// cell_size,
// cell_size
// );
// }
// }
// context.stroke();
// draw all dead cells
context.begin_path();
context.set_fill_style(&JsValue::from(self.config.get_cell_dead_color()));
for col in 0..self.width {
for row in 0..self.height {
if ! self.is_visible(row, col) {
continue;
}
if *self.cells.get(self.get_index(row, col)).unwrap() == Cell::Alive {
continue;
}
let (row, col) = self.translate_to_visible_row_col(row, col);
context.fill_rect(
x_offset + col as f64 * (cell_size + line_width),
y_offset + row as f64 * (cell_size + line_width),
cell_size,
cell_size
);
}
}
context.stroke();
// draw all alive cells
context.begin_path();
context.set_fill_style(&JsValue::from(self.config.get_cell_alive_color()));
for col in 0..self.width {
for row in 0..self.height {
if ! self.is_visible(row, col) {
continue;
}
if *self.cells.get(self.get_index(row, col)).unwrap() == Cell::Dead {
continue;
}
let (row, col) = self.translate_to_visible_row_col(row, col);
context.fill_rect(
x_offset + col as f64 * (cell_size + line_width),
y_offset + row as f64 * (cell_size + line_width),
cell_size,
cell_size
);
}
}
context.stroke();
}
}
pub fn tick(&mut self) {
let mut next = self.cells.clone();
for row in 0..self.height {
for col in 0..self.width {
let idx = self.get_index(row, col);
let cell = self.cells[idx];
let live_neighbors = self.living_neighbor_count(row, col);
let next_cell = match (cell, live_neighbors) {
(Cell::Alive, x) if x < 2 => Cell::Dead,
(Cell::Alive, 2) | (Cell::Alive, 3) => Cell::Alive,
(Cell::Alive, x) if x > 3 => Cell::Dead,
(Cell::Dead, 3) => Cell::Alive,
(otherwise, _) => otherwise,
};
next[idx] = next_cell;
}
}
self.cells = next
}
pub fn cells(&self) -> *const Cell {
self.cells.as_ptr()
}
}
| true |
bcdb04e86072b86af5c63915f9f11a3c48230524
|
Rust
|
llogiq/shoggoth.rs
|
/src/hlist.rs
|
UTF-8
| 2,063 | 3.171875 | 3 |
[
"MIT"
] |
permissive
|
/// Heterogeneous lists
#[rustc_on_unimplemented = "`{Self}` is not a heterogeneous list"]
pub trait HList {}
/// Empty heterogeneous list
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct Nil;
impl HList for Nil {}
/// Cons heterogeneous list
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct Cons<H, T>(pub H, pub T);
impl<H, T: HList> HList for Cons<H, T> {}
/// `HList` predicate implemented when `Self` is heterogeneous cons
#[rustc_on_unimplemented = "`{Self}` is not a heterogeneous cons"]
pub trait IsCons: HList {
type H;
type T: HList;
#[inline] fn head(self) -> Self::H;
#[inline] fn tail(self) -> Self::T;
}
impl<H, T: HList> IsCons for Cons<H, T> {
type H = H;
type T = T;
#[inline] fn head(self) -> H { self.0 }
#[inline] fn tail(self) -> T { self.1 }
}
/// Prepend for heterogeneous lists
pub trait Prepend<R> {
type Out;
}
impl<R> Prepend<R> for Nil {
type Out = R;
}
impl<H, R, T: HList> Prepend<R> for Cons<H, T> where T: Prepend<R> {
type Out = Cons<H, <T as Prepend<R>>::Out>;
}
/// Snoc (cons to tail) for heterogeneous lists
pub trait Snoc<H> {
type Out;
}
impl<X> Snoc<X> for Nil {
type Out = Cons<X, Nil>;
}
impl<H, T: HList, X> Snoc<X> for Cons<H, T> where T: Snoc<X> {
type Out = Cons<H, <T as Snoc<X>>::Out>;
}
/// Reverse prepend for heterogeneous lists
pub trait ReversePrepend<Acc> {
type Out;
}
impl<Acc> ReversePrepend<Acc> for Nil {
type Out = Acc;
}
impl<Acc, H, T: HList> ReversePrepend<Acc> for Cons<H, T> where
T: ReversePrepend<Cons<H, Acc>>,
{
type Out = <T as ReversePrepend<Cons<H, Acc>>>::Out;
}
/// Reverse prepend for heterogeneous lists
pub trait Reverse {
type Out;
}
impl<Xs> Reverse for Xs where Xs: ReversePrepend<Nil> {
type Out = <Xs as ReversePrepend<Nil>>::Out;
}
/// Alias for heterogeneous nil
pub type HN = Nil;
/// Alias for heterogeneous cons
pub type HC<H, T> = Cons<H, T>;
/// Alias for heterogeneous snoc
pub type HS<T, H> = <T as Snoc<H>>::Out;
| true |
934a5f168a3b85d444f308cd5e30cd9696b75048
|
Rust
|
Garvys/rustfst-images-doc
|
/src/closure.rs
|
UTF-8
| 915 | 2.671875 | 3 |
[
"Apache-2.0"
] |
permissive
|
use std::path::Path;
use failure::Fallible;
use rustfst::algorithms::{closure, ClosureType};
use rustfst::DrawingConfig;
use crate::fsts::fst_002;
use crate::utils::generate_image;
pub fn generate_closure_images<P: AsRef<Path>>(path_images: P) -> Fallible<()> {
let path_images = path_images.as_ref();
let fst = fst_002()?;
let mut config = DrawingConfig::default();
config.portrait = true;
config.vertical = false;
generate_image(path_images, &fst, "closure_in", &config)?;
{
let mut fst_copy = fst.clone();
closure(&mut fst_copy, ClosureType::ClosureStar);
generate_image(path_images, &fst_copy, "closure_out_closure_star", &config)?;
}
{
let mut fst_copy = fst.clone();
closure(&mut fst_copy, ClosureType::ClosurePlus);
generate_image(path_images, &fst_copy, "closure_out_closure_plus", &config)?;
}
Ok(())
}
| true |
8663f6f15db778ed05403f2bfa645ccb7ffa5ce1
|
Rust
|
JetASAP/firestore-db-and-auth-rs
|
/src/credentials.rs
|
UTF-8
| 10,723 | 2.71875 | 3 |
[
"MIT"
] |
permissive
|
//! # Credentials for accessing the Firebase REST API
//! This module contains the [`crate::credentials::Credentials`] type, used by [`crate::sessions`] to create and maintain
//! authentication tokens for accessing the Firebase REST API.
use chrono::Duration;
use serde::{Deserialize, Serialize};
use serde_json;
use std::collections::BTreeMap;
use std::fs::File;
use std::sync::Arc;
use super::jwt::{create_jwt_encoded, download_google_jwks, verify_access_token, JWKSet, JWT_AUDIENCE_IDENTITY};
use crate::errors::FirebaseError;
use std::io::BufReader;
type Error = super::errors::FirebaseError;
/// This is not defined in the json file and computed
#[derive(Default, Clone)]
pub(crate) struct Keys {
pub pub_key: BTreeMap<String, Arc<biscuit::jws::Secret>>,
pub secret: Option<Arc<biscuit::jws::Secret>>,
}
/// Service account credentials
///
/// Especially the service account email is required to retrieve the public java web key set (jwks)
/// for verifying Google Firestore tokens.
///
/// The api_key is necessary for interacting with the Firestore REST API.
///
/// Internals:
///
/// The private key is used for signing JWTs (javascript web token).
/// A signed jwt, encoded as a base64 string, can be exchanged into a refresh and access token.
#[derive(Serialize, Deserialize, Default, Clone)]
pub struct Credentials {
pub project_id: String,
pub private_key_id: String,
pub private_key: String,
pub client_email: String,
pub client_id: String,
pub api_key: String,
#[serde(default, skip)]
pub(crate) keys: Keys,
}
/// Converts a PEM (ascii base64) encoded private key into the binary der representation
pub fn pem_to_der(pem_file_contents: &str) -> Result<Vec<u8>, Error> {
use base64::decode;
let pem_file_contents = pem_file_contents
.find("-----BEGIN")
// Cut off the first BEGIN part
.and_then(|i| Some(&pem_file_contents[i + 10..]))
// Find the trailing ---- after BEGIN and cut that off
.and_then(|str| str.find("-----").and_then(|i| Some(&str[i + 5..])))
// Cut off -----END
.and_then(|str| str.rfind("-----END").and_then(|i| Some(&str[..i])));
if pem_file_contents.is_none() {
return Err(FirebaseError::Generic(
"Invalid private key in credentials file. Must be valid PEM.",
));
}
let base64_body = pem_file_contents.unwrap().replace("\n", "");
Ok(decode(&base64_body)
.map_err(|_| FirebaseError::Generic("Invalid private key in credentials file. Expected Base64 data."))?)
}
#[test]
fn pem_to_der_test() {
const INPUT: &str = r#"-----BEGIN PRIVATE KEY-----
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCTbt9Rs2niyIRE
FIdrhIN757eq/1Ry/VhZALBXAveg+lt+ui/9EHtYPJH1A9NyyAwChs0UCRWqkkEo
Amtz4dJQ1YlGi0/BGhK2lg==
-----END PRIVATE KEY-----
"#;
const EXPECTED: [u8; 112] = [
48, 130, 4, 188, 2, 1, 0, 48, 13, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 1, 5, 0, 4, 130, 4, 166, 48, 130, 4,
162, 2, 1, 0, 2, 130, 1, 1, 0, 147, 110, 223, 81, 179, 105, 226, 200, 132, 68, 20, 135, 107, 132, 131, 123,
231, 183, 170, 255, 84, 114, 253, 88, 89, 0, 176, 87, 2, 247, 160, 250, 91, 126, 186, 47, 253, 16, 123, 88, 60,
145, 245, 3, 211, 114, 200, 12, 2, 134, 205, 20, 9, 21, 170, 146, 65, 40, 2, 107, 115, 225, 210, 80, 213, 137,
70, 139, 79, 193, 26, 18, 182, 150,
];
assert_eq!(&EXPECTED[..], &pem_to_der(INPUT).unwrap()[..]);
}
impl Credentials {
/// Create a [`Credentials`] object by parsing a google-service-account json string
///
/// Example:
///
/// Assuming that your firebase service account credentials file is called "service-account-test.json" and
/// a downloaded jwk-set file is called "service-account-test.jwks" this example embeds
/// the file content during compile time. This avoids and http or io calls.
///
/// ```
/// use firestore_db_and_auth::{Credentials};
/// use firestore_db_and_auth::jwt::JWKSet;
///
/// let c: Credentials = Credentials::new(include_str!("../tests/service-account-test.json"))?
/// .with_jwkset(&JWKSet::new(include_str!("../tests/service-account-test.jwks"))?)?;
/// # Ok::<(), firestore_db_and_auth::errors::FirebaseError>(())
/// ```
///
/// You need two JWKS files for this crate to work:
/// * https://www.googleapis.com/service_accounts/v1/jwk/[email protected]
/// * https://www.googleapis.com/service_accounts/v1/jwk/{your-service-account-email}
pub fn new(credentials_file_content: &str) -> Result<Credentials, Error> {
let mut credentials: Credentials = serde_json::from_str(credentials_file_content)?;
credentials.compute_secret()?;
Ok(credentials)
}
/// Create a [`Credentials`] object by reading and parsing a google-service-account json file.
///
/// This is a convenience method, that reads in the given credentials file and acts otherwise the same as
/// the [`Credentials::new`] method.
pub fn from_file(credential_file: &str) -> Result<Self, Error> {
let f = BufReader::new(File::open(credential_file)?);
let mut credentials: Credentials = serde_json::from_reader(f)?;
credentials.compute_secret()?;
Ok(credentials)
}
/// Adds public-key JWKs to a credentials instance and returns it.
///
/// This method will also verify that the given JWKs files allow verification of Google access tokens.
/// This is a convenience method, you may also just use [`Credentials::add_jwks_public_keys`].
pub fn with_jwkset(mut self, jwks: &JWKSet) -> Result<Credentials, Error> {
self.add_jwks_public_keys(jwks);
self.verify()?;
Ok(self)
}
/// The public keys to verify generated tokens will be downloaded, for the given service account as well as
/// for "[email protected]".
/// Do not use this option if additional downloads are not desired,
/// for example in cloud functions that require fast cold boot start times.
///
/// You can use [`Credentials::add_jwks_public_keys`] to manually add/replace public keys later on.
///
/// Example:
///
/// Assuming that your firebase service account credentials file is called "service-account-test.json".
///
/// ```no_run
/// use firestore_db_and_auth::{Credentials};
///
/// let c: Credentials = Credentials::new(include_str!("../tests/service-account-test.json"))?
/// .download_jwkset()?;
/// # Ok::<(), firestore_db_and_auth::errors::FirebaseError>(())
/// ```
pub fn download_jwkset(mut self) -> Result<Credentials, Error> {
self.download_google_jwks()?;
self.verify()?;
Ok(self)
}
/// Verifies that creating access tokens is possible with the given credentials and public keys.
/// Returns an empty result type on success.
pub fn verify(&self) -> Result<(), Error> {
let access_token = create_jwt_encoded(
&self,
Some(["admin"].iter()),
Duration::hours(1),
Some(self.client_id.clone()),
None,
JWT_AUDIENCE_IDENTITY,
)?;
verify_access_token(&self, &access_token)?;
Ok(())
}
/// Find the secret in the jwt set that matches the given key id, if any.
/// Used for jws validation
pub fn decode_secret(&self, kid: &str) -> Option<Arc<biscuit::jws::Secret>> {
self.keys.pub_key.get(kid).and_then(|f| Some(f.clone()))
}
/// Add a JSON Web Key Set (JWKS) to allow verification of Google access tokens.
///
/// Example:
///
/// ```
/// use firestore_db_and_auth::credentials::Credentials;
/// use firestore_db_and_auth::JWKSet;
///
/// let mut c : Credentials = serde_json::from_str(include_str!("../tests/service-account-test.json"))?;
/// c.add_jwks_public_keys(&JWKSet::new(include_str!("../tests/service-account-test.jwks"))?);
/// c.compute_secret()?;
/// c.verify()?;
/// # Ok::<(), firestore_db_and_auth::errors::FirebaseError>(())
/// ```
pub fn add_jwks_public_keys(&mut self, jwkset: &JWKSet) {
for entry in jwkset.keys.iter() {
if !entry.headers.key_id.is_some() {
continue;
}
let key_id = entry.headers.key_id.as_ref().unwrap().to_owned();
self.keys
.pub_key
.insert(key_id, Arc::new(entry.ne.jws_public_key_secret()));
}
}
/// If you haven't called [`Credentials::add_jwks_public_keys`] to manually add public keys,
/// this method will download one for your google service account and one for the oauth related
/// [email protected] service account.
pub fn download_google_jwks(&mut self) -> Result<(), Error> {
let jwks = download_google_jwks(&self.client_email)?;
self.add_jwks_public_keys(&JWKSet::new(&jwks)?);
let jwks = download_google_jwks("[email protected]")?;
self.add_jwks_public_keys(&JWKSet::new(&jwks)?);
Ok(())
}
/// Compute the Rsa keypair by using the private_key of the credentials file.
/// You must call this if you have manually created a credentials object.
///
/// This is automatically invoked if you use [`Credentials::new`] or [`Credentials::from_file`].
pub fn compute_secret(&mut self) -> Result<(), Error> {
use biscuit::jws::Secret;
use ring::signature;
let vec = pem_to_der(&self.private_key)?;
let key_pair = signature::RsaKeyPair::from_pkcs8(&vec)?;
self.keys.secret = Some(Arc::new(Secret::RsaKeyPair(Arc::new(key_pair))));
Ok(())
}
}
#[doc(hidden)]
#[allow(dead_code)]
pub fn doctest_credentials() -> Credentials {
let jwk_list = JWKSet::new(include_str!("../tests/service-account-test.jwks")).unwrap();
Credentials::new(include_str!("../tests/service-account-test.json"))
.expect("Failed to deserialize credentials")
.with_jwkset(&jwk_list)
.expect("JWK public keys verification failed")
}
#[test]
fn deserialize_credentials() {
let jwk_list = JWKSet::new(include_str!("../tests/service-account-test.jwks")).unwrap();
let c: Credentials = Credentials::new(include_str!("../tests/service-account-test.json"))
.expect("Failed to deserialize credentials")
.with_jwkset(&jwk_list)
.expect("JWK public keys verification failed");
assert_eq!(c.api_key, "api_key");
use std::path::PathBuf;
let mut credential_file = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
credential_file.push("tests/service-account-test.json");
let c = Credentials::from_file(credential_file.to_str().unwrap())
.expect("Failed to open credentials file")
.with_jwkset(&jwk_list)
.expect("JWK public keys verification failed");
assert_eq!(c.api_key, "api_key");
}
| true |
456c81cd8f6aa2e1b26cc0e36bbb954d29974473
|
Rust
|
mxinden/paxos-simulator
|
/src/nack/proposer.rs
|
UTF-8
| 10,457 | 2.65625 | 3 |
[] |
no_license
|
use super::Body;
use crate::{Address, Epoch, Header, Instant, Msg, Node, Value};
use std::collections::VecDeque;
const TIMEOUT: Instant = Instant(10);
/// A sequential proposer, handling a single request at a time.
#[derive(Debug)]
pub struct Proposer {
address: Address,
pub acceptors: Vec<Address>,
inbox: VecDeque<Msg<Body>>,
epoch: Epoch,
state: ProposerState,
}
impl Node<Body> for Proposer {
fn receive(&mut self, m: Msg<Body>) {
self.inbox.push_back(m);
}
fn process(&mut self, now: Instant) -> Vec<Msg<Body>> {
self.process(now)
}
}
impl crate::Proposer<Body> for Proposer {}
impl Proposer {
pub fn new(address: Address, initial_epoch: Epoch, acceptors: Vec<Address>) -> Self {
Self {
address,
acceptors,
inbox: Default::default(),
epoch: initial_epoch,
state: ProposerState::Idle,
}
}
fn process(&mut self, now: Instant) -> Vec<Msg<Body>> {
let messages: Vec<Msg<Body>> = self.inbox.drain(0..).collect();
let responses: Vec<Msg<Body>> = messages
.into_iter()
.map(|m| self.process_msg(m, now))
.flatten()
.collect();
if !responses.is_empty() {
// We made progress, thus returning.
return responses;
}
// Check whether we are still within the timeout.
if self
.state
.last_progress_at()
.map(|t| now - t < TIMEOUT)
.unwrap_or(true)
{
return vec![];
}
// We timed out - going back to preparing.
self.epoch = Epoch::new(self.epoch.epoch + 1, self.epoch.identifier);
self.retry(now)
}
fn process_msg(&mut self, m: Msg<Body>, now: Instant) -> Vec<Msg<Body>> {
match m.body {
Body::Request(v) => self.process_request(m.header, v, now),
Body::Promise(promised_epoch, accepted) => {
self.process_promise(promised_epoch, accepted, now)
}
Body::Accept(epoch) => self.process_accept(epoch, now),
Body::Nack(e, f) => self.process_nack(e, f, now),
Body::Prepare(_) | Body::Propose(_, _) | Body::Response(_) => unreachable!(),
}
}
fn process_request(&mut self, header: Header, value: Value, now: Instant) -> Vec<Msg<Body>> {
match self.state {
ProposerState::Unreachable => unreachable!(),
ProposerState::Preparing { .. } | ProposerState::Proposing { .. } => {
self.inbox.push_back(Msg {
header,
body: Body::Request(value),
});
return vec![];
}
ProposerState::Idle => {
self.state = ProposerState::Preparing {
last_progress_at: now,
value,
promises: vec![],
};
let body = Body::Prepare(self.epoch);
self.broadcast_to_acceptors(body, now)
}
}
}
fn process_promise(
&mut self,
promised_epoch: Epoch,
accepted: Option<(Epoch, Value)>,
now: Instant,
) -> Vec<Msg<Body>> {
// Ignore any messages outside our current epoch.
if promised_epoch != self.epoch {
return vec![];
}
let state = std::mem::replace(&mut self.state, ProposerState::Unreachable);
match state {
ProposerState::Unreachable => unreachable!(),
ProposerState::Idle | ProposerState::Proposing { .. } => {
self.state = state;
return vec![];
}
ProposerState::Preparing {
value,
mut promises,
..
} => {
promises.push(Promise {
epoch: promised_epoch,
accepted,
});
if promises.len() < self.acceptors.len() / 2 + 1 {
self.state = ProposerState::Preparing {
last_progress_at: now,
value,
promises,
};
return vec![];
}
let highest_accepted: Option<(Epoch, Value)> =
promises
.into_iter()
.fold(None, |highest, Promise { accepted, .. }| match highest {
Some((h_e, h_v)) => match accepted {
Some((a_e, a_v)) => {
if h_e > a_e {
Some((h_e, h_v))
} else {
Some((a_e, a_v))
}
}
None => Some((h_e, h_v)),
},
None => accepted,
});
self.state = ProposerState::Proposing {
last_progress_at: now,
value: highest_accepted.map(|a| a.1).unwrap_or(value),
received_accepts: 0,
};
let propose_body = Body::Propose(self.epoch, self.state.value().unwrap());
self.broadcast_to_acceptors(propose_body, now)
}
}
}
fn process_accept(&mut self, epoch: Epoch, now: Instant) -> Vec<Msg<Body>> {
// Ignore any messages outside our current epoch.
if epoch != self.epoch {
return vec![];
}
let state = std::mem::replace(&mut self.state, ProposerState::Unreachable);
match state {
ProposerState::Unreachable => unreachable!(),
ProposerState::Idle | ProposerState::Preparing { .. } => {
self.state = state;
return vec![];
}
ProposerState::Proposing {
value,
received_accepts,
..
} => {
let received_accepts = received_accepts + 1;
if received_accepts < self.acceptors.len() / 2 + 1 {
self.state = ProposerState::Proposing {
value,
received_accepts,
last_progress_at: now,
};
return vec![];
}
self.epoch = Epoch::new(self.epoch.epoch + 1, self.epoch.identifier);
self.state = ProposerState::Idle;
return vec![Msg {
header: Header {
from: self.address.clone(),
// TODO: We need to track the client address along the way.
to: Address::new(""),
at: now + 1,
},
body: Body::Response(value),
}];
}
}
}
// TODO: Do we need to retry always, or only if we got a majority of nacks
// back?
fn process_nack(
&mut self,
our_epoch: Epoch,
higher_epoch: Epoch,
now: Instant,
) -> Vec<Msg<Body>> {
// Ignore any messages outside our current epoch.
if our_epoch != self.epoch {
return vec![];
}
let state = std::mem::replace(&mut self.state, ProposerState::Unreachable);
match state {
ProposerState::Unreachable => unreachable!(),
ProposerState::Idle => {
self.state = state;
vec![]
}
ProposerState::Preparing { .. } | ProposerState::Proposing {..} => {
// self.retry() extracts the value from the current scope, but
// we replaced it above with ProposerState::Unreachable. Make
// sure to switch it back.
self.state = state;
self.epoch = Epoch::new(higher_epoch.epoch + 1, self.epoch.identifier);
self.retry(now)
}
}
}
fn broadcast_to_acceptors(&mut self, b: Body, now: Instant) -> Vec<Msg<Body>> {
self.acceptors
.iter()
.map(|a| Msg {
header: Header {
from: self.address.clone(),
to: a.clone(),
at: now + 1,
},
body: b.clone(),
})
.collect()
}
/// Try to serve the client request by starting all over with a Prepare.
/// This is necessary on a timeout or e.g. a retry.
fn retry(&mut self, now: Instant) -> Vec<Msg<Body>> {
let value = self
.state
.value()
.expect("can't be reached from idle state, thus there is a value");
self.state = ProposerState::Preparing {
last_progress_at: now,
value,
promises: vec![],
};
let body = Body::Prepare(self.epoch);
self.broadcast_to_acceptors(body, now)
}
}
#[derive(Clone, Debug)]
enum ProposerState {
Idle,
/// Epoch and value to propose and promises received so far.
Preparing {
last_progress_at: Instant,
value: Value,
promises: Vec<Promise>,
},
Proposing {
last_progress_at: Instant,
value: Value,
received_accepts: usize,
},
Unreachable,
}
impl ProposerState {
fn last_progress_at(&self) -> Option<Instant> {
match self {
ProposerState::Unreachable => unreachable!(),
ProposerState::Idle => None,
ProposerState::Preparing {
last_progress_at, ..
} => Some(*last_progress_at),
ProposerState::Proposing {
last_progress_at, ..
} => Some(*last_progress_at),
}
}
fn value(&self) -> Option<Value> {
match self {
ProposerState::Unreachable => unreachable!(),
ProposerState::Idle => None,
ProposerState::Preparing { value, .. } => Some(value.clone()),
ProposerState::Proposing { value, .. } => Some(value.clone()),
}
}
}
#[derive(Clone, Debug)]
struct Promise {
epoch: Epoch,
accepted: Option<(Epoch, Value)>,
}
| true |
70d2ed9989426720e9e3b6489273038342b36739
|
Rust
|
rayon-rs/rayon
|
/rayon-core/src/scope/test.rs
|
UTF-8
| 19,034 | 2.625 | 3 |
[
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
use crate::unwind;
use crate::ThreadPoolBuilder;
use crate::{scope, scope_fifo, Scope, ScopeFifo};
use rand::{Rng, SeedableRng};
use rand_xorshift::XorShiftRng;
use std::cmp;
use std::iter::once;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Barrier, Mutex};
use std::vec;
#[test]
fn scope_empty() {
scope(|_| {});
}
#[test]
fn scope_result() {
let x = scope(|_| 22);
assert_eq!(x, 22);
}
#[test]
fn scope_two() {
let counter = &AtomicUsize::new(0);
scope(|s| {
s.spawn(move |_| {
counter.fetch_add(1, Ordering::SeqCst);
});
s.spawn(move |_| {
counter.fetch_add(10, Ordering::SeqCst);
});
});
let v = counter.load(Ordering::SeqCst);
assert_eq!(v, 11);
}
#[test]
fn scope_divide_and_conquer() {
let counter_p = &AtomicUsize::new(0);
scope(|s| s.spawn(move |s| divide_and_conquer(s, counter_p, 1024)));
let counter_s = &AtomicUsize::new(0);
divide_and_conquer_seq(counter_s, 1024);
let p = counter_p.load(Ordering::SeqCst);
let s = counter_s.load(Ordering::SeqCst);
assert_eq!(p, s);
}
fn divide_and_conquer<'scope>(scope: &Scope<'scope>, counter: &'scope AtomicUsize, size: usize) {
if size > 1 {
scope.spawn(move |scope| divide_and_conquer(scope, counter, size / 2));
scope.spawn(move |scope| divide_and_conquer(scope, counter, size / 2));
} else {
// count the leaves
counter.fetch_add(1, Ordering::SeqCst);
}
}
fn divide_and_conquer_seq(counter: &AtomicUsize, size: usize) {
if size > 1 {
divide_and_conquer_seq(counter, size / 2);
divide_and_conquer_seq(counter, size / 2);
} else {
// count the leaves
counter.fetch_add(1, Ordering::SeqCst);
}
}
struct Tree<T: Send> {
value: T,
children: Vec<Tree<T>>,
}
impl<T: Send> Tree<T> {
fn iter(&self) -> vec::IntoIter<&T> {
once(&self.value)
.chain(self.children.iter().flat_map(Tree::iter))
.collect::<Vec<_>>() // seems like it shouldn't be needed... but prevents overflow
.into_iter()
}
fn update<OP>(&mut self, op: OP)
where
OP: Fn(&mut T) + Sync,
T: Send,
{
scope(|s| self.update_in_scope(&op, s));
}
fn update_in_scope<'scope, OP>(&'scope mut self, op: &'scope OP, scope: &Scope<'scope>)
where
OP: Fn(&mut T) + Sync,
{
let Tree {
ref mut value,
ref mut children,
} = *self;
scope.spawn(move |scope| {
for child in children {
scope.spawn(move |scope| child.update_in_scope(op, scope));
}
});
op(value);
}
}
fn random_tree(depth: usize) -> Tree<u32> {
assert!(depth > 0);
let mut seed = <XorShiftRng as SeedableRng>::Seed::default();
(0..).zip(seed.as_mut()).for_each(|(i, x)| *x = i);
let mut rng = XorShiftRng::from_seed(seed);
random_tree1(depth, &mut rng)
}
fn random_tree1(depth: usize, rng: &mut XorShiftRng) -> Tree<u32> {
let children = if depth == 0 {
vec![]
} else {
(0..rng.gen_range(0..4)) // somewhere between 0 and 3 children at each level
.map(|_| random_tree1(depth - 1, rng))
.collect()
};
Tree {
value: rng.gen_range(0..1_000_000),
children,
}
}
#[test]
fn update_tree() {
let mut tree: Tree<u32> = random_tree(10);
let values: Vec<u32> = tree.iter().cloned().collect();
tree.update(|v| *v += 1);
let new_values: Vec<u32> = tree.iter().cloned().collect();
assert_eq!(values.len(), new_values.len());
for (&i, &j) in values.iter().zip(&new_values) {
assert_eq!(i + 1, j);
}
}
/// Check that if you have a chain of scoped tasks where T0 spawns T1
/// spawns T2 and so forth down to Tn, the stack space should not grow
/// linearly with N. We test this by some unsafe hackery and
/// permitting an approx 10% change with a 10x input change.
#[test]
#[cfg_attr(any(target_os = "emscripten", target_family = "wasm"), ignore)]
fn linear_stack_growth() {
let builder = ThreadPoolBuilder::new().num_threads(1);
let pool = builder.build().unwrap();
pool.install(|| {
let mut max_diff = Mutex::new(0);
let bottom_of_stack = 0;
scope(|s| the_final_countdown(s, &bottom_of_stack, &max_diff, 5));
let diff_when_5 = *max_diff.get_mut().unwrap() as f64;
scope(|s| the_final_countdown(s, &bottom_of_stack, &max_diff, 500));
let diff_when_500 = *max_diff.get_mut().unwrap() as f64;
let ratio = diff_when_5 / diff_when_500;
assert!(
ratio > 0.9 && ratio < 1.1,
"stack usage ratio out of bounds: {}",
ratio
);
});
}
fn the_final_countdown<'scope>(
s: &Scope<'scope>,
bottom_of_stack: &'scope i32,
max: &'scope Mutex<usize>,
n: usize,
) {
let top_of_stack = 0;
let p = bottom_of_stack as *const i32 as usize;
let q = &top_of_stack as *const i32 as usize;
let diff = if p > q { p - q } else { q - p };
let mut data = max.lock().unwrap();
*data = cmp::max(diff, *data);
if n > 0 {
s.spawn(move |s| the_final_countdown(s, bottom_of_stack, max, n - 1));
}
}
#[test]
#[should_panic(expected = "Hello, world!")]
fn panic_propagate_scope() {
scope(|_| panic!("Hello, world!"));
}
#[test]
#[should_panic(expected = "Hello, world!")]
fn panic_propagate_spawn() {
scope(|s| s.spawn(|_| panic!("Hello, world!")));
}
#[test]
#[should_panic(expected = "Hello, world!")]
fn panic_propagate_nested_spawn() {
scope(|s| s.spawn(|s| s.spawn(|s| s.spawn(|_| panic!("Hello, world!")))));
}
#[test]
#[should_panic(expected = "Hello, world!")]
fn panic_propagate_nested_scope_spawn() {
scope(|s| s.spawn(|_| scope(|s| s.spawn(|_| panic!("Hello, world!")))));
}
#[test]
#[cfg_attr(not(panic = "unwind"), ignore)]
fn panic_propagate_still_execute_1() {
let mut x = false;
match unwind::halt_unwinding(|| {
scope(|s| {
s.spawn(|_| panic!("Hello, world!")); // job A
s.spawn(|_| x = true); // job B, should still execute even though A panics
});
}) {
Ok(_) => panic!("failed to propagate panic"),
Err(_) => assert!(x, "job b failed to execute"),
}
}
#[test]
#[cfg_attr(not(panic = "unwind"), ignore)]
fn panic_propagate_still_execute_2() {
let mut x = false;
match unwind::halt_unwinding(|| {
scope(|s| {
s.spawn(|_| x = true); // job B, should still execute even though A panics
s.spawn(|_| panic!("Hello, world!")); // job A
});
}) {
Ok(_) => panic!("failed to propagate panic"),
Err(_) => assert!(x, "job b failed to execute"),
}
}
#[test]
#[cfg_attr(not(panic = "unwind"), ignore)]
fn panic_propagate_still_execute_3() {
let mut x = false;
match unwind::halt_unwinding(|| {
scope(|s| {
s.spawn(|_| x = true); // spawned job should still execute despite later panic
panic!("Hello, world!");
});
}) {
Ok(_) => panic!("failed to propagate panic"),
Err(_) => assert!(x, "panic after spawn, spawn failed to execute"),
}
}
#[test]
#[cfg_attr(not(panic = "unwind"), ignore)]
fn panic_propagate_still_execute_4() {
let mut x = false;
match unwind::halt_unwinding(|| {
scope(|s| {
s.spawn(|_| panic!("Hello, world!"));
x = true;
});
}) {
Ok(_) => panic!("failed to propagate panic"),
Err(_) => assert!(x, "panic in spawn tainted scope"),
}
}
macro_rules! test_order {
($scope:ident => $spawn:ident) => {{
let builder = ThreadPoolBuilder::new().num_threads(1);
let pool = builder.build().unwrap();
pool.install(|| {
let vec = Mutex::new(vec![]);
$scope(|scope| {
let vec = &vec;
for i in 0..10 {
scope.$spawn(move |scope| {
for j in 0..10 {
scope.$spawn(move |_| {
vec.lock().unwrap().push(i * 10 + j);
});
}
});
}
});
vec.into_inner().unwrap()
})
}};
}
#[test]
#[cfg_attr(any(target_os = "emscripten", target_family = "wasm"), ignore)]
fn lifo_order() {
// In the absence of stealing, `scope()` runs its `spawn()` jobs in LIFO order.
let vec = test_order!(scope => spawn);
let expected: Vec<i32> = (0..100).rev().collect(); // LIFO -> reversed
assert_eq!(vec, expected);
}
#[test]
#[cfg_attr(any(target_os = "emscripten", target_family = "wasm"), ignore)]
fn fifo_order() {
// In the absence of stealing, `scope_fifo()` runs its `spawn_fifo()` jobs in FIFO order.
let vec = test_order!(scope_fifo => spawn_fifo);
let expected: Vec<i32> = (0..100).collect(); // FIFO -> natural order
assert_eq!(vec, expected);
}
macro_rules! test_nested_order {
($outer_scope:ident => $outer_spawn:ident,
$inner_scope:ident => $inner_spawn:ident) => {{
let builder = ThreadPoolBuilder::new().num_threads(1);
let pool = builder.build().unwrap();
pool.install(|| {
let vec = Mutex::new(vec![]);
$outer_scope(|scope| {
let vec = &vec;
for i in 0..10 {
scope.$outer_spawn(move |_| {
$inner_scope(|scope| {
for j in 0..10 {
scope.$inner_spawn(move |_| {
vec.lock().unwrap().push(i * 10 + j);
});
}
});
});
}
});
vec.into_inner().unwrap()
})
}};
}
#[test]
#[cfg_attr(any(target_os = "emscripten", target_family = "wasm"), ignore)]
fn nested_lifo_order() {
// In the absence of stealing, `scope()` runs its `spawn()` jobs in LIFO order.
let vec = test_nested_order!(scope => spawn, scope => spawn);
let expected: Vec<i32> = (0..100).rev().collect(); // LIFO -> reversed
assert_eq!(vec, expected);
}
#[test]
#[cfg_attr(any(target_os = "emscripten", target_family = "wasm"), ignore)]
fn nested_fifo_order() {
// In the absence of stealing, `scope_fifo()` runs its `spawn_fifo()` jobs in FIFO order.
let vec = test_nested_order!(scope_fifo => spawn_fifo, scope_fifo => spawn_fifo);
let expected: Vec<i32> = (0..100).collect(); // FIFO -> natural order
assert_eq!(vec, expected);
}
#[test]
#[cfg_attr(any(target_os = "emscripten", target_family = "wasm"), ignore)]
fn nested_lifo_fifo_order() {
// LIFO on the outside, FIFO on the inside
let vec = test_nested_order!(scope => spawn, scope_fifo => spawn_fifo);
let expected: Vec<i32> = (0..10)
.rev()
.flat_map(|i| (0..10).map(move |j| i * 10 + j))
.collect();
assert_eq!(vec, expected);
}
#[test]
#[cfg_attr(any(target_os = "emscripten", target_family = "wasm"), ignore)]
fn nested_fifo_lifo_order() {
// FIFO on the outside, LIFO on the inside
let vec = test_nested_order!(scope_fifo => spawn_fifo, scope => spawn);
let expected: Vec<i32> = (0..10)
.flat_map(|i| (0..10).rev().map(move |j| i * 10 + j))
.collect();
assert_eq!(vec, expected);
}
macro_rules! spawn_push {
($scope:ident . $spawn:ident, $vec:ident, $i:expr) => {{
$scope.$spawn(move |_| $vec.lock().unwrap().push($i));
}};
}
/// Test spawns pushing a series of numbers, interleaved
/// such that negative values are using an inner scope.
macro_rules! test_mixed_order {
($outer_scope:ident => $outer_spawn:ident,
$inner_scope:ident => $inner_spawn:ident) => {{
let builder = ThreadPoolBuilder::new().num_threads(1);
let pool = builder.build().unwrap();
pool.install(|| {
let vec = Mutex::new(vec![]);
$outer_scope(|outer_scope| {
let vec = &vec;
spawn_push!(outer_scope.$outer_spawn, vec, 0);
$inner_scope(|inner_scope| {
spawn_push!(inner_scope.$inner_spawn, vec, -1);
spawn_push!(outer_scope.$outer_spawn, vec, 1);
spawn_push!(inner_scope.$inner_spawn, vec, -2);
spawn_push!(outer_scope.$outer_spawn, vec, 2);
spawn_push!(inner_scope.$inner_spawn, vec, -3);
});
spawn_push!(outer_scope.$outer_spawn, vec, 3);
});
vec.into_inner().unwrap()
})
}};
}
#[test]
#[cfg_attr(any(target_os = "emscripten", target_family = "wasm"), ignore)]
fn mixed_lifo_order() {
// NB: the end of the inner scope makes us execute some of the outer scope
// before they've all been spawned, so they're not perfectly LIFO.
let vec = test_mixed_order!(scope => spawn, scope => spawn);
let expected = vec![-3, 2, -2, 1, -1, 3, 0];
assert_eq!(vec, expected);
}
#[test]
#[cfg_attr(any(target_os = "emscripten", target_family = "wasm"), ignore)]
fn mixed_fifo_order() {
let vec = test_mixed_order!(scope_fifo => spawn_fifo, scope_fifo => spawn_fifo);
let expected = vec![-1, 0, -2, 1, -3, 2, 3];
assert_eq!(vec, expected);
}
#[test]
#[cfg_attr(any(target_os = "emscripten", target_family = "wasm"), ignore)]
fn mixed_lifo_fifo_order() {
// NB: the end of the inner scope makes us execute some of the outer scope
// before they've all been spawned, so they're not perfectly LIFO.
let vec = test_mixed_order!(scope => spawn, scope_fifo => spawn_fifo);
let expected = vec![-1, 2, -2, 1, -3, 3, 0];
assert_eq!(vec, expected);
}
#[test]
#[cfg_attr(any(target_os = "emscripten", target_family = "wasm"), ignore)]
fn mixed_fifo_lifo_order() {
let vec = test_mixed_order!(scope_fifo => spawn_fifo, scope => spawn);
let expected = vec![-3, 0, -2, 1, -1, 2, 3];
assert_eq!(vec, expected);
}
#[test]
fn static_scope() {
static COUNTER: AtomicUsize = AtomicUsize::new(0);
let mut range = 0..100;
let sum = range.clone().sum();
let iter = &mut range;
COUNTER.store(0, Ordering::Relaxed);
scope(|s: &Scope<'static>| {
// While we're allowed the locally borrowed iterator,
// the spawns must be static.
for i in iter {
s.spawn(move |_| {
COUNTER.fetch_add(i, Ordering::Relaxed);
});
}
});
assert_eq!(COUNTER.load(Ordering::Relaxed), sum);
}
#[test]
fn static_scope_fifo() {
static COUNTER: AtomicUsize = AtomicUsize::new(0);
let mut range = 0..100;
let sum = range.clone().sum();
let iter = &mut range;
COUNTER.store(0, Ordering::Relaxed);
scope_fifo(|s: &ScopeFifo<'static>| {
// While we're allowed the locally borrowed iterator,
// the spawns must be static.
for i in iter {
s.spawn_fifo(move |_| {
COUNTER.fetch_add(i, Ordering::Relaxed);
});
}
});
assert_eq!(COUNTER.load(Ordering::Relaxed), sum);
}
#[test]
fn mixed_lifetime_scope() {
fn increment<'slice, 'counter>(counters: &'slice [&'counter AtomicUsize]) {
scope(move |s: &Scope<'counter>| {
// We can borrow 'slice here, but the spawns can only borrow 'counter.
for &c in counters {
s.spawn(move |_| {
c.fetch_add(1, Ordering::Relaxed);
});
}
});
}
let counter = AtomicUsize::new(0);
increment(&[&counter; 100]);
assert_eq!(counter.into_inner(), 100);
}
#[test]
fn mixed_lifetime_scope_fifo() {
fn increment<'slice, 'counter>(counters: &'slice [&'counter AtomicUsize]) {
scope_fifo(move |s: &ScopeFifo<'counter>| {
// We can borrow 'slice here, but the spawns can only borrow 'counter.
for &c in counters {
s.spawn_fifo(move |_| {
c.fetch_add(1, Ordering::Relaxed);
});
}
});
}
let counter = AtomicUsize::new(0);
increment(&[&counter; 100]);
assert_eq!(counter.into_inner(), 100);
}
#[test]
fn scope_spawn_broadcast() {
let sum = AtomicUsize::new(0);
let n = scope(|s| {
s.spawn_broadcast(|_, ctx| {
sum.fetch_add(ctx.index(), Ordering::Relaxed);
});
crate::current_num_threads()
});
assert_eq!(sum.into_inner(), n * (n - 1) / 2);
}
#[test]
fn scope_fifo_spawn_broadcast() {
let sum = AtomicUsize::new(0);
let n = scope_fifo(|s| {
s.spawn_broadcast(|_, ctx| {
sum.fetch_add(ctx.index(), Ordering::Relaxed);
});
crate::current_num_threads()
});
assert_eq!(sum.into_inner(), n * (n - 1) / 2);
}
#[test]
fn scope_spawn_broadcast_nested() {
let sum = AtomicUsize::new(0);
let n = scope(|s| {
s.spawn_broadcast(|s, _| {
s.spawn_broadcast(|_, ctx| {
sum.fetch_add(ctx.index(), Ordering::Relaxed);
});
});
crate::current_num_threads()
});
assert_eq!(sum.into_inner(), n * n * (n - 1) / 2);
}
#[test]
#[cfg_attr(any(target_os = "emscripten", target_family = "wasm"), ignore)]
fn scope_spawn_broadcast_barrier() {
let barrier = Barrier::new(8);
let pool = ThreadPoolBuilder::new().num_threads(7).build().unwrap();
pool.in_place_scope(|s| {
s.spawn_broadcast(|_, _| {
barrier.wait();
});
barrier.wait();
});
}
#[test]
#[cfg_attr(any(target_os = "emscripten", target_family = "wasm"), ignore)]
fn scope_spawn_broadcast_panic_one() {
let count = AtomicUsize::new(0);
let pool = ThreadPoolBuilder::new().num_threads(7).build().unwrap();
let result = crate::unwind::halt_unwinding(|| {
pool.scope(|s| {
s.spawn_broadcast(|_, ctx| {
count.fetch_add(1, Ordering::Relaxed);
if ctx.index() == 3 {
panic!("Hello, world!");
}
});
});
});
assert_eq!(count.into_inner(), 7);
assert!(result.is_err(), "broadcast panic should propagate!");
}
#[test]
#[cfg_attr(any(target_os = "emscripten", target_family = "wasm"), ignore)]
fn scope_spawn_broadcast_panic_many() {
let count = AtomicUsize::new(0);
let pool = ThreadPoolBuilder::new().num_threads(7).build().unwrap();
let result = crate::unwind::halt_unwinding(|| {
pool.scope(|s| {
s.spawn_broadcast(|_, ctx| {
count.fetch_add(1, Ordering::Relaxed);
if ctx.index() % 2 == 0 {
panic!("Hello, world!");
}
});
});
});
assert_eq!(count.into_inner(), 7);
assert!(result.is_err(), "broadcast panic should propagate!");
}
| true |
0a3ec555c7e93f68515a353f35cb8183488ad684
|
Rust
|
sunjay/async-std
|
/src/stream/stream/take.rs
|
UTF-8
| 933 | 3.078125 | 3 |
[
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
use std::pin::Pin;
use crate::stream::Stream;
use crate::task::{Context, Poll};
/// A stream that yields the first `n` items of another stream.
#[derive(Clone, Debug)]
pub struct Take<S> {
pub(crate) stream: S,
pub(crate) remaining: usize,
}
impl<S: Unpin> Unpin for Take<S> {}
impl<S: Stream> Take<S> {
pin_utils::unsafe_pinned!(stream: S);
pin_utils::unsafe_unpinned!(remaining: usize);
}
impl<S: Stream> Stream for Take<S> {
type Item = S::Item;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<S::Item>> {
if self.remaining == 0 {
Poll::Ready(None)
} else {
let next = futures_core::ready!(self.as_mut().stream().poll_next(cx));
match next {
Some(_) => *self.as_mut().remaining() -= 1,
None => *self.as_mut().remaining() = 0,
}
Poll::Ready(next)
}
}
}
| true |
57a5b7fdeeb8f9dd22278aef2981397937e1c5d0
|
Rust
|
kwsm114514/typical90
|
/MyAnswers/ans027.rs
|
UTF-8
| 346 | 2.59375 | 3 |
[] |
no_license
|
use proconio::{input, fastout};
#[fastout]
fn main() {
input!{n: usize, users: [String; n]}
// hashsetで計算量を改善
let mut hs = std::collections::HashSet::new();
for i in 0..n {
if hs.contains(&users[i]) {
continue;
}
println!("{}", i + 1);
hs.insert(&users[i]);
}
}
| true |
56d4428eebbb5e80a65e4e90645021e4337fdf3e
|
Rust
|
wezm/dslite2svd
|
/crates/tm4c123x/src/sysctl/rcgc0/mod.rs
|
UTF-8
| 9,882 | 2.625 | 3 |
[
"0BSD",
"BSD-3-Clause"
] |
permissive
|
#[doc = r" Value read from the register"]
pub struct R {
bits: u32,
}
impl super::RCGC0 {
#[doc = r" Reads the contents of the register"]
#[inline]
pub fn read(&self) -> R {
R { bits: self.register.get() }
}
}
#[doc = r" Value of the field"]
pub struct WDT0R {
bits: bool,
}
impl WDT0R {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct HIBR {
bits: bool,
}
impl HIBR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = "Possible values of the field `ADC0SPD`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ADC0SPDR {
#[doc = "125K samples/second"]
_125K,
#[doc = "250K samples/second"]
_250K,
#[doc = "500K samples/second"]
_500K,
#[doc = "1M samples/second"]
_1M,
}
impl ADC0SPDR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
match *self {
ADC0SPDR::_125K => 0,
ADC0SPDR::_250K => 1,
ADC0SPDR::_500K => 2,
ADC0SPDR::_1M => 3,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: u8) -> ADC0SPDR {
match value {
0 => ADC0SPDR::_125K,
1 => ADC0SPDR::_250K,
2 => ADC0SPDR::_500K,
3 => ADC0SPDR::_1M,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `_125K`"]
#[inline]
pub fn is_125k(&self) -> bool {
*self == ADC0SPDR::_125K
}
#[doc = "Checks if the value of the field is `_250K`"]
#[inline]
pub fn is_250k(&self) -> bool {
*self == ADC0SPDR::_250K
}
#[doc = "Checks if the value of the field is `_500K`"]
#[inline]
pub fn is_500k(&self) -> bool {
*self == ADC0SPDR::_500K
}
#[doc = "Checks if the value of the field is `_1M`"]
#[inline]
pub fn is_1m(&self) -> bool {
*self == ADC0SPDR::_1M
}
}
#[doc = "Possible values of the field `ADC1SPD`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ADC1SPDR {
#[doc = "125K samples/second"]
_125K,
#[doc = "250K samples/second"]
_250K,
#[doc = "500K samples/second"]
_500K,
#[doc = "1M samples/second"]
_1M,
}
impl ADC1SPDR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
match *self {
ADC1SPDR::_125K => 0,
ADC1SPDR::_250K => 1,
ADC1SPDR::_500K => 2,
ADC1SPDR::_1M => 3,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: u8) -> ADC1SPDR {
match value {
0 => ADC1SPDR::_125K,
1 => ADC1SPDR::_250K,
2 => ADC1SPDR::_500K,
3 => ADC1SPDR::_1M,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `_125K`"]
#[inline]
pub fn is_125k(&self) -> bool {
*self == ADC1SPDR::_125K
}
#[doc = "Checks if the value of the field is `_250K`"]
#[inline]
pub fn is_250k(&self) -> bool {
*self == ADC1SPDR::_250K
}
#[doc = "Checks if the value of the field is `_500K`"]
#[inline]
pub fn is_500k(&self) -> bool {
*self == ADC1SPDR::_500K
}
#[doc = "Checks if the value of the field is `_1M`"]
#[inline]
pub fn is_1m(&self) -> bool {
*self == ADC1SPDR::_1M
}
}
#[doc = r" Value of the field"]
pub struct ADC0R {
bits: bool,
}
impl ADC0R {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct ADC1R {
bits: bool,
}
impl ADC1R {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct PWM0R {
bits: bool,
}
impl PWM0R {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct CAN0R {
bits: bool,
}
impl CAN0R {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct CAN1R {
bits: bool,
}
impl CAN1R {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct WDT1R {
bits: bool,
}
impl WDT1R {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
impl R {
#[doc = r" Value of the register as raw bits"]
#[inline]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bit 3 - WDT0 Clock Gating Control"]
#[inline]
pub fn wdt0(&self) -> WDT0R {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 3;
((self.bits >> OFFSET) & MASK as u32) != 0
};
WDT0R { bits }
}
#[doc = "Bit 6 - HIB Clock Gating Control"]
#[inline]
pub fn hib(&self) -> HIBR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 6;
((self.bits >> OFFSET) & MASK as u32) != 0
};
HIBR { bits }
}
#[doc = "Bits 8:9 - ADC0 Sample Speed"]
#[inline]
pub fn adc0spd(&self) -> ADC0SPDR {
ADC0SPDR::_from({
const MASK: u8 = 3;
const OFFSET: u8 = 8;
((self.bits >> OFFSET) & MASK as u32) as u8
})
}
#[doc = "Bits 10:11 - ADC1 Sample Speed"]
#[inline]
pub fn adc1spd(&self) -> ADC1SPDR {
ADC1SPDR::_from({
const MASK: u8 = 3;
const OFFSET: u8 = 10;
((self.bits >> OFFSET) & MASK as u32) as u8
})
}
#[doc = "Bit 16 - ADC0 Clock Gating Control"]
#[inline]
pub fn adc0(&self) -> ADC0R {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 16;
((self.bits >> OFFSET) & MASK as u32) != 0
};
ADC0R { bits }
}
#[doc = "Bit 17 - ADC1 Clock Gating Control"]
#[inline]
pub fn adc1(&self) -> ADC1R {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 17;
((self.bits >> OFFSET) & MASK as u32) != 0
};
ADC1R { bits }
}
#[doc = "Bit 20 - PWM Clock Gating Control"]
#[inline]
pub fn pwm0(&self) -> PWM0R {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 20;
((self.bits >> OFFSET) & MASK as u32) != 0
};
PWM0R { bits }
}
#[doc = "Bit 24 - CAN0 Clock Gating Control"]
#[inline]
pub fn can0(&self) -> CAN0R {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 24;
((self.bits >> OFFSET) & MASK as u32) != 0
};
CAN0R { bits }
}
#[doc = "Bit 25 - CAN1 Clock Gating Control"]
#[inline]
pub fn can1(&self) -> CAN1R {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 25;
((self.bits >> OFFSET) & MASK as u32) != 0
};
CAN1R { bits }
}
#[doc = "Bit 28 - WDT1 Clock Gating Control"]
#[inline]
pub fn wdt1(&self) -> WDT1R {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 28;
((self.bits >> OFFSET) & MASK as u32) != 0
};
WDT1R { bits }
}
}
| true |
102886f3b68c0e784232dd641457acb0533b6a46
|
Rust
|
ggez/ggez
|
/examples/graphics_settings.rs
|
UTF-8
| 7,723 | 2.828125 | 3 |
[
"MIT"
] |
permissive
|
//! An example of how to play with various graphics modes settings,
//! resize windows, etc.
//!
//! Prints instructions to the console.
use std::convert::TryFrom;
use ggez::conf;
use ggez::event;
use ggez::graphics::Rect;
use ggez::graphics::{self, Color, DrawMode, DrawParam};
use ggez::input::keyboard::KeyCode;
use ggez::{Context, GameResult};
use argh::FromArgs;
use ggez::input::keyboard::KeyInput;
use std::env;
use std::path;
type Point2 = ggez::glam::Vec2;
struct WindowSettings {
toggle_fullscreen: bool,
is_fullscreen: bool,
resize_projection: bool,
}
struct MainState {
angle: f32, // in radians
zoom: f32,
image: graphics::Image,
window_settings: WindowSettings,
screen_coords: Rect,
}
impl MainState {
fn new(ctx: &mut Context) -> GameResult<MainState> {
let s = MainState {
angle: 0.0,
zoom: 1.0,
image: graphics::Image::from_path(ctx, "/tile.png")?,
window_settings: WindowSettings {
toggle_fullscreen: false,
is_fullscreen: false,
resize_projection: false,
},
screen_coords: Rect {
x: 0.,
y: 0.,
w: ctx.gfx.drawable_size().0,
h: ctx.gfx.drawable_size().1,
},
};
Ok(s)
}
}
impl event::EventHandler<ggez::GameError> for MainState {
fn update(&mut self, ctx: &mut Context) -> GameResult {
const DESIRED_FPS: u32 = 60;
while ctx.time.check_update_time(DESIRED_FPS) {
self.angle += 0.01;
if self.window_settings.toggle_fullscreen {
let fullscreen_type = if self.window_settings.is_fullscreen {
conf::FullscreenType::Desktop
} else {
conf::FullscreenType::Windowed
};
ctx.gfx.set_fullscreen(fullscreen_type)?;
self.window_settings.toggle_fullscreen = false;
}
}
Ok(())
}
fn draw(&mut self, ctx: &mut Context) -> GameResult {
let mut canvas = graphics::Canvas::from_frame(ctx, Color::BLACK);
canvas.set_screen_coordinates(self.screen_coords);
canvas.draw(
&self.image,
DrawParam::new()
.dest(Point2::new(400.0, 300.0))
.color(Color::WHITE), //.offset([0.5, 0.5]),
);
let rotation = ctx.time.ticks() % 1000;
let circle = graphics::Mesh::new_circle(
ctx,
DrawMode::stroke(3.0),
Point2::new(0.0, 0.0),
100.0,
4.0,
Color::WHITE,
)?;
canvas.draw(
&circle,
DrawParam::new()
.dest(Point2::new(400.0, 300.0))
.rotation(rotation as f32)
.color(Color::WHITE),
);
// Let's draw a grid so we can see where the window bounds are.
const COUNT: i32 = 10;
let mut mb = graphics::MeshBuilder::new();
for x in -COUNT..COUNT {
for y in -COUNT..COUNT {
const SPACING: i32 = 100;
let fx = (x * SPACING) as f32;
let fy = (y * SPACING) as f32;
// println!("POS: {},{}", fx, fy);
let r = (x as f32) / (COUNT as f32);
let b = (y as f32) / (COUNT as f32);
// println!("R: {}", r);
let color = graphics::Color::new(r, 0.0, b, 1.0);
// graphics::rectangle(
// ctx,
// color,
// graphics::DrawMode::fill(),
// graphics::Rect::new(fx, fy, 5.0, 5.0),
// )?
mb.rectangle(
DrawMode::fill(),
graphics::Rect::new(fx, fy, 5.0, 5.0),
color,
)?;
}
}
let mesh = graphics::Mesh::from_data(ctx, mb.build());
canvas.draw(&mesh, ggez::mint::Point2 { x: 0.0, y: 0.0 });
canvas.finish(ctx)?;
Ok(())
}
fn mouse_button_down_event(
&mut self,
_ctx: &mut Context,
_btn: event::MouseButton,
x: f32,
y: f32,
) -> GameResult {
println!("Button clicked at: {x} {y}");
Ok(())
}
fn key_up_event(&mut self, ctx: &mut Context, input: KeyInput) -> GameResult {
match input.keycode {
Some(KeyCode::F) => {
self.window_settings.toggle_fullscreen = true;
self.window_settings.is_fullscreen = !self.window_settings.is_fullscreen;
}
Some(KeyCode::Up) => {
self.zoom += 0.1;
println!("Zoom is now {}", self.zoom);
let (w, h) = ctx.gfx.drawable_size();
let new_rect = graphics::Rect::new(0.0, 0.0, w * self.zoom, h * self.zoom);
self.screen_coords = new_rect;
}
Some(KeyCode::Down) => {
self.zoom -= 0.1;
println!("Zoom is now {}", self.zoom);
let (w, h) = ctx.gfx.drawable_size();
let new_rect = graphics::Rect::new(0.0, 0.0, w * self.zoom, h * self.zoom);
self.screen_coords = new_rect;
}
Some(KeyCode::Space) => {
self.window_settings.resize_projection = !self.window_settings.resize_projection;
println!(
"Resizing the projection on window resize is now: {}",
self.window_settings.resize_projection
);
}
_ => {}
}
Ok(())
}
fn resize_event(&mut self, _ctx: &mut Context, width: f32, height: f32) -> GameResult {
println!("Resized screen to {width}, {height}");
if self.window_settings.resize_projection {
let new_rect = graphics::Rect::new(0.0, 0.0, width * self.zoom, height * self.zoom);
self.screen_coords = new_rect;
}
Ok(())
}
}
fn print_help() {
println!("GRAPHICS SETTING EXAMPLE:");
println!(" F: toggle fullscreen");
println!(" Up/Down: Zoom in/out");
println!(
" Spacebar: Toggle whether or not to resize the projection when the window is resized"
);
println!(" ");
println!(" To see command-line options, run with `cargo run --example graphics_settings -- --help`");
println!(" ");
}
/// Print out graphics settings.
#[derive(FromArgs, Debug)]
struct Opt {
/// what level of MSAA to try to use (1 or 4)
#[argh(option, short = 'm', long = "msaa", default = "1")]
msaa: u8,
}
pub fn main() -> GameResult {
let opt: Opt = argh::from_env();
let resource_dir = if let Ok(manifest_dir) = env::var("CARGO_MANIFEST_DIR") {
let mut path = path::PathBuf::from(manifest_dir);
path.push("resources");
path
} else {
path::PathBuf::from("./resources")
};
let backend = conf::Backend::default();
let cb = ggez::ContextBuilder::new("graphics_settings", "ggez")
.window_mode(
conf::WindowMode::default()
.fullscreen_type(conf::FullscreenType::Windowed)
.resizable(true),
)
.window_setup(conf::WindowSetup::default().samples(
conf::NumSamples::try_from(opt.msaa).expect("Option msaa needs to be 1 or 4!"),
))
.backend(backend)
.add_resource_path(resource_dir);
let (mut ctx, events_loop) = cb.build()?;
print_help();
let state = MainState::new(&mut ctx)?;
event::run(ctx, events_loop, state)
}
| true |
3265012c5ac233e835171e119656af7067d124c8
|
Rust
|
mmn-siddiqui/IOT-Rust-Language
|
/Assignment 3.rs
|
UTF-8
| 568 | 3.546875 | 4 |
[] |
no_license
|
#[derive(Debug)]
struct Student {
name : String,
age : u8,
grade : String,
percentage : f32
}
impl Student {
fn construct(name:String,age:u8,grade:String,percentage:f32)-> Student {
Student {
name,
age,
grade ,
percentage
}
}
fn ppt(&self){
println!("{}",self.percentage);
}
}
fn main() {
let student1 = Student::construct(String::from("Mubashir"),23,String::from("A-1"),93.4);
println!("{:#?}",student1);
student1.ppt();
}
| true |
05575028d40ea95b9664f1dee7e50e64c35a9fc0
|
Rust
|
ftilde/rust-x86asm
|
/src/test/instruction_tests/instr_cmpxchg8b.rs
|
UTF-8
| 2,005 | 2.578125 | 3 |
[
"MIT"
] |
permissive
|
use instruction_def::*;
use test::run_test;
use Operand::*;
use Reg::*;
use RegScale::*;
use RegType::*;
use {BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
#[test]
fn cmpxchg8b_1() {
run_test(
&Instruction {
mnemonic: Mnemonic::CMPXCHG8B,
operand1: Some(Indirect(SI, Some(OperandSize::Qword), None)),
operand2: None,
operand3: None,
operand4: None,
lock: false,
rounding_mode: None,
merge_mode: None,
sae: false,
mask: None,
broadcast: None,
},
&[15, 199, 12],
OperandSize::Word,
)
}
#[test]
fn cmpxchg8b_2() {
run_test(
&Instruction {
mnemonic: Mnemonic::CMPXCHG8B,
operand1: Some(IndirectScaledIndexedDisplaced(
ESI,
ECX,
Four,
1759335804,
Some(OperandSize::Qword),
None,
)),
operand2: None,
operand3: None,
operand4: None,
lock: false,
rounding_mode: None,
merge_mode: None,
sae: false,
mask: None,
broadcast: None,
},
&[15, 199, 140, 142, 124, 85, 221, 104],
OperandSize::Dword,
)
}
#[test]
fn cmpxchg8b_3() {
run_test(
&Instruction {
mnemonic: Mnemonic::CMPXCHG8B,
operand1: Some(IndirectDisplaced(
RDX,
76495837,
Some(OperandSize::Qword),
None,
)),
operand2: None,
operand3: None,
operand4: None,
lock: false,
rounding_mode: None,
merge_mode: None,
sae: false,
mask: None,
broadcast: None,
},
&[15, 199, 138, 221, 59, 143, 4],
OperandSize::Qword,
)
}
| true |
d176d55d9d06ca1f2e784f2932185bc8183a55a0
|
Rust
|
Atul9/sqelf
|
/sqelf/src/server.rs
|
UTF-8
| 19,980 | 2.71875 | 3 |
[
"Apache-2.0"
] |
permissive
|
use std::{
marker::Unpin,
net::SocketAddr,
str::FromStr,
time::Duration,
};
use futures::{
future::{
BoxFuture,
Either,
},
select,
};
use tokio::{
net::signal::ctrl_c,
prelude::*,
runtime::Runtime,
sync::oneshot,
};
use bytes::{
Bytes,
BytesMut,
};
use crate::{
diagnostics::*,
error::Error,
receive::Message,
};
metrics! {
receive_ok,
receive_err,
process_ok,
process_err,
tcp_conn_accept,
tcp_conn_close,
tcp_conn_timeout,
tcp_msg_overflow
}
/**
Server configuration.
*/
#[derive(Debug, Clone)]
pub struct Config {
/**
The address to bind the server to.
*/
pub bind: Bind,
/**
The duration to keep client TCP connections alive for.
If the client doesn't complete a message within the period
then the connection will be closed.
*/
pub tcp_keep_alive_secs: u64,
/**
The maximum size of a single event before it'll be discarded.
*/
pub tcp_max_size_bytes: u64,
}
#[derive(Debug, Clone)]
pub struct Bind {
pub addr: String,
pub protocol: Protocol,
}
#[derive(Debug, Clone, Copy)]
pub enum Protocol {
Udp,
Tcp,
}
impl FromStr for Bind {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.get(0..6) {
Some("tcp://") => Ok(Bind {
addr: s[6..].to_owned(),
protocol: Protocol::Tcp,
}),
Some("udp://") => Ok(Bind {
addr: s[6..].to_owned(),
protocol: Protocol::Udp,
}),
_ => Ok(Bind {
addr: s.to_owned(),
protocol: Protocol::Udp,
}),
}
}
}
impl Default for Config {
fn default() -> Self {
Config {
bind: Bind {
addr: "0.0.0.0:12201".to_owned(),
protocol: Protocol::Udp,
},
tcp_keep_alive_secs: 2 * 60, // 2 minutes
tcp_max_size_bytes: 1024 * 256, // 256kiB
}
}
}
/**
A GELF server.
*/
pub struct Server {
fut: BoxFuture<'static, ()>,
handle: Option<Handle>,
}
impl Server {
pub fn take_handle(&mut self) -> Option<Handle> {
self.handle.take()
}
pub fn run(self) -> Result<(), Error> {
// Run the server on a fresh runtime
// We attempt to shut this runtime down cleanly to release
// any used resources
let runtime = Runtime::new().expect("failed to start new Runtime");
runtime.block_on(self.fut);
runtime.shutdown_now();
Ok(())
}
}
/**
A handle to a running GELF server that can be used to interact with it
programmatically.
*/
pub struct Handle {
close: oneshot::Sender<()>,
}
impl Handle {
/**
Close the server.
*/
pub fn close(self) -> bool {
self.close.send(()).is_ok()
}
}
/**
Build a server to receive GELF messages and process them.
*/
pub fn build(
config: Config,
receive: impl FnMut(Bytes) -> Result<Option<Message>, Error> + Send + Sync + Unpin + Clone + 'static,
mut process: impl FnMut(Message) -> Result<(), Error> + Send + Sync + Unpin + Clone + 'static,
) -> Result<Server, Error> {
emit("Starting GELF server");
let addr = config.bind.addr.parse()?;
let (handle_tx, handle_rx) = oneshot::channel();
// Build a handle
let handle = Some(Handle { close: handle_tx });
let ctrl_c = ctrl_c()?;
let server = async move {
let incoming = match config.bind.protocol {
Protocol::Udp => {
let server = udp::Server::bind(&addr).await?.build(receive);
Either::Left(server)
}
Protocol::Tcp => {
let server = tcp::Server::bind(&addr).await?.build(
Duration::from_secs(config.tcp_keep_alive_secs),
config.tcp_max_size_bytes as usize,
receive,
);
Either::Right(server)
}
};
let mut close = handle_rx.fuse();
let mut ctrl_c = ctrl_c.fuse();
let mut incoming = incoming.fuse();
// NOTE: We don't use `?` here because we never want to carry results
// We always want to match them and deal with error cases directly
loop {
select! {
// A message that's ready to process
msg = incoming.next() => match msg {
// A complete message has been received
Some(Ok(Received::Complete(msg))) => {
increment!(server.receive_ok);
// Process the received message
match process(msg) {
Ok(()) => {
increment!(server.process_ok);
}
Err(err) => {
increment!(server.process_err);
emit_err(&err, "GELF processing failed");
}
}
},
// A chunk of a message has been received
Some(Ok(Received::Incomplete)) => {
continue;
},
// An error occurred receiving a chunk
Some(Err(err)) => {
increment!(server.receive_err);
emit_err(&err, "GELF processing failed");
},
None => {
unreachable!("receiver stream should never terminate")
},
},
// A termination signal from the programmatic handle
_ = close => {
emit("Handle closed; shutting down");
break;
},
// A termination signal from the environment
_ = ctrl_c.next() => {
emit("Termination signal received; shutting down");
break;
},
};
}
emit("Stopping GELF server");
Result::Ok::<(), Error>(())
};
Ok(Server {
fut: Box::pin(async move {
if let Err(err) = server.await {
emit_err(&err, "GELF server failed");
}
}),
handle,
})
}
enum Received {
Incomplete,
Complete(Message),
}
trait OptionMessageExt {
fn into_received(self) -> Option<Received>;
}
impl OptionMessageExt for Option<Message> {
fn into_received(self) -> Option<Received> {
match self {
Some(msg) => Some(Received::Complete(msg)),
None => Some(Received::Incomplete),
}
}
}
mod udp {
use super::*;
use tokio::{
codec::Decoder,
net::udp::{
UdpFramed,
UdpSocket,
},
};
pub(super) struct Server(UdpSocket);
impl Server {
pub(super) async fn bind(addr: &SocketAddr) -> Result<Self, Error> {
let sock = UdpSocket::bind(&addr).await?;
Ok(Server(sock))
}
pub(super) fn build(
self,
receive: impl FnMut(Bytes) -> Result<Option<Message>, Error> + Unpin,
) -> impl Stream<Item = Result<Received, Error>> {
emit("Setting up for UDP");
UdpFramed::new(self.0, Decode(receive)).map(|r| r.map(|(msg, _)| msg))
}
}
struct Decode<F>(F);
impl<F> Decoder for Decode<F>
where
F: FnMut(Bytes) -> Result<Option<Message>, Error> + Unpin,
{
type Item = Received;
type Error = Error;
fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
// All datagrams are considered a valid message
let src = src.take().freeze();
Ok((self.0)(src)?.into_received())
}
}
}
mod tcp {
use super::*;
use std::{
cmp,
pin::Pin,
};
use futures::{
future,
stream::{
futures_unordered::FuturesUnordered,
Fuse,
Stream,
StreamFuture,
},
task::{
Context,
Poll,
},
};
use pin_utils::unsafe_pinned;
use tokio::{
codec::{
Decoder,
FramedRead,
},
net::tcp::TcpListener,
timer::Timeout,
};
pub(super) struct Server(TcpListener);
impl Server {
pub(super) async fn bind(addr: &SocketAddr) -> Result<Self, Error> {
let listener = TcpListener::bind(&addr).await?;
Ok(Server(listener))
}
pub(super) fn build(
self,
keep_alive: Duration,
max_size_bytes: usize,
receive: impl FnMut(Bytes) -> Result<Option<Message>, Error>
+ Send
+ Sync
+ Unpin
+ Clone
+ 'static,
) -> impl Stream<Item = Result<Received, Error>> {
emit("Setting up for TCP");
self.0
.incoming()
.filter_map(move |conn| {
match conn {
// The connection was successfully established
// Create a new protocol reader over it
// It'll get added to the connection pool
Ok(conn) => {
let decode = Decode::new(max_size_bytes, receive.clone());
let protocol = FramedRead::new(conn, decode);
// NOTE: The timeout stream wraps _the protocol_
// That means it'll close the connection if it doesn't
// produce a valid message within the timeframe, not just
// whether or not it writes to the stream
future::ready(Some(TimeoutStream::new(protocol, keep_alive)))
}
// The connection could not be established
// Just ignore it
Err(_) => future::ready(None),
}
})
.listen(1024)
}
}
struct Listen<S>
where
S: Stream,
S::Item: Stream,
{
accept: Fuse<S>,
connections: FuturesUnordered<StreamFuture<S::Item>>,
max: usize,
}
impl<S> Listen<S>
where
S: Stream,
S::Item: Stream,
{
unsafe_pinned!(accept: Fuse<S>);
unsafe_pinned!(connections: FuturesUnordered<StreamFuture<S::Item>>);
}
impl<S, T> Stream for Listen<S>
where
S: Stream + Unpin,
S::Item: Stream<Item = Result<T, Error>> + Unpin,
{
type Item = Result<T, Error>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
'poll_conns: loop {
// Fill up our accepted connections
'fill_conns: while self.connections.len() < self.max {
let conn = match self.as_mut().accept().poll_next(cx) {
Poll::Ready(Some(s)) => s.into_future(),
Poll::Ready(None) | Poll::Pending => break 'fill_conns,
};
self.connections.push(conn);
}
// Try polling the stream
// NOTE: We're assuming the unordered list will
// always make forward progress polling futures
// even if one future is particularly chatty
match self.as_mut().connections().poll_next(cx) {
// We have an item from a connection
Poll::Ready(Some((Some(item), conn))) => {
match item {
// A valid item was produced
// Return it and put the connection back in the pool.
Ok(item) => {
self.connections.push(conn.into_future());
return Poll::Ready(Some(Ok(item)));
}
// An error occurred, probably IO-related
// In this case the connection isn't returned to the pool.
// It's closed on drop and the error is returned.
Err(err) => {
return Poll::Ready(Some(Err(err.into())));
}
}
}
// A connection has closed
// Drop the connection and loop back
// This will mean attempting to accept a new connection
Poll::Ready(Some((None, _conn))) => continue 'poll_conns,
// The queue is empty or nothing is ready
Poll::Ready(None) | Poll::Pending => break 'poll_conns,
}
}
// If we've gotten this far, then there are no events for us to process
// and nothing was ready, so figure out if we're not done yet or if
// we've reached the end.
if self.accept.is_done() {
Poll::Ready(None)
} else {
Poll::Pending
}
}
}
trait StreamListenExt: Stream {
fn listen(self, max_connections: usize) -> Listen<Self>
where
Self: Sized + Unpin,
Self::Item: Stream + Unpin,
{
Listen {
accept: self.fuse(),
connections: FuturesUnordered::new(),
max: max_connections,
}
}
}
impl<S> StreamListenExt for S where S: Stream {}
struct Decode<F> {
max_size_bytes: usize,
read_head: usize,
discarding: bool,
receive: F,
}
impl<F> Decode<F> {
pub fn new(max_size_bytes: usize, receive: F) -> Self {
Decode {
read_head: 0,
discarding: false,
max_size_bytes,
receive,
}
}
}
impl<F> Decoder for Decode<F>
where
F: FnMut(Bytes) -> Result<Option<Message>, Error>,
{
type Item = Received;
type Error = Error;
fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
'read_frame: loop {
let read_to = cmp::min(self.max_size_bytes.saturating_add(1), src.len());
// Messages are separated by null bytes
let sep_offset = src[self.read_head..].iter().position(|b| *b == b'\0');
match (self.discarding, sep_offset) {
// A delimiter was found
// Split it from the buffer and return
(false, Some(offset)) => {
let frame_end = offset + self.read_head;
// The message is technically sitting right there
// for us, but since it's bigger than our max capacity
// we still discard it
if frame_end > self.max_size_bytes {
increment!(server.tcp_msg_overflow);
self.discarding = true;
continue 'read_frame;
}
self.read_head = 0;
let src = src.split_to(frame_end + 1).freeze();
return Ok((self.receive)(src.slice_to(src.len() - 1))?.into_received());
}
// A delimiter wasn't found, but the incomplete
// message is too big. Start discarding the input
(false, None) if src.len() > self.max_size_bytes => {
increment!(server.tcp_msg_overflow);
self.discarding = true;
continue 'read_frame;
}
// A delimiter wasn't found
// Move the read head forward so we'll check
// from that position next time data arrives
(false, None) => {
self.read_head = read_to;
// As per the contract of `Decoder`, we return `None`
// here to indicate more data is needed to complete a frame
return Ok(None);
}
// We're discarding input and have reached the end of the message
// Advance the source buffer to the end of that message and try again
(true, Some(offset)) => {
src.advance(offset + self.read_head + 1);
self.discarding = false;
self.read_head = 0;
continue 'read_frame;
}
// We're discarding input but haven't reached the end of the message yet
(true, None) => {
src.advance(read_to);
self.read_head = 0;
if src.is_empty() {
// We still return `Ok` here, even though we have no intention
// of processing those bytes. Our maximum buffer size should still
// be limited by the initial capacity, since we're responsible for
// reserving additional capacity and aren't doing that
return Ok(None);
}
continue 'read_frame;
}
}
}
}
fn decode_eof(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
Ok(match self.decode(src)? {
Some(frame) => Some(frame),
None => {
if src.is_empty() {
None
} else {
let src = src.take().freeze();
self.read_head = 0;
(self.receive)(src)?.into_received()
}
}
})
}
}
struct TimeoutStream<S> {
stream: Timeout<S>,
}
impl<S> TimeoutStream<S>
where
S: Stream,
{
fn new(stream: S, keep_alive: Duration) -> Self {
increment!(server.tcp_conn_accept);
TimeoutStream {
stream: Timeout::new(stream, keep_alive),
}
}
}
impl<S> Drop for TimeoutStream<S> {
fn drop(&mut self) {
increment!(server.tcp_conn_close);
}
}
impl<S> TimeoutStream<S> {
unsafe_pinned!(stream: Timeout<S>);
}
impl<S> Stream for TimeoutStream<S>
where
S: Stream,
{
type Item = S::Item;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
match self.stream().poll_next(cx) {
// The timeout has elapsed
Poll::Ready(Some(Err(_))) => {
increment!(server.tcp_conn_timeout);
Poll::Ready(None)
}
// The stream has produced an item
Poll::Ready(Some(Ok(item))) => Poll::Ready(Some(item)),
// The stream has completed
Poll::Ready(None) => Poll::Ready(None),
// The timeout hasn't elapsed and the stream hasn't produced an item
Poll::Pending => Poll::Pending,
}
}
}
}
| true |
31feb43160ae36f939139f7cb81fb8ed4a137957
|
Rust
|
Buzzec/kapto_web
|
/src/game/ruleset/starting_positions/placement_area.rs
|
UTF-8
| 3,029 | 3.171875 | 3 |
[] |
no_license
|
use std::collections::HashSet;
use std::error::Error;
use std::fmt::{Debug, Display, Formatter};
use std::fmt;
use serde::{Deserialize, Serialize};
use crate::game::coordinate::{Coordinate, flip_coordinate, rotate_coordinate};
use crate::game::ruleset::board_type::space::Space;
use crate::game::ruleset::Ruleset;
/// Placement area definition.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum PlacementArea {
/// Players can place on half the board.
Half,
/// Players can place on a mirrored set of places.
/// Mirroring will flip.
/// Will error if overlapping.
MirroredFlipped(HashSet<Coordinate>),
/// Players can place on a mirrored set of places.
/// Mirroring will rotate.
/// Will error if overlapping.
MirroredRotated(HashSet<Coordinate>),
/// Players can place on a given set of places based on seat.
/// Must be set for all seats.
NonMirrored(Vec<HashSet<Coordinate>>),
}
impl PlacementArea {
pub fn verify(&self, ruleset: &Ruleset) -> PlacementAreaResult<()> {
match self {
Self::Half => {},
Self::MirroredFlipped(positions) | Self::MirroredRotated(positions) => {
let func = if let Self::MirroredFlipped(_) = self { flip_coordinate } else { rotate_coordinate };
let mut found = positions.clone();
for &position in positions {
if position.row < 0 || position.row >= ruleset.board_type.rows() as i16 || position.column < 0 || position.column >= ruleset.board_type.columns() as i16 {
return Err(PlacementAreaError::PositionCannotPlace(Space::Invalid, position))
}
let opposite = func(&ruleset.board_type, position);
if !found.insert(position) || found.insert(opposite) {
return Err(PlacementAreaError::PositionCollision(position));
}
}
},
Self::NonMirrored(seat_map) => {
let mut found = HashSet::new();
if seat_map.len() as u64 != ruleset.seats{
return Err(PlacementAreaError::InvalidSeatNumber(seat_map.len()));
}
for coordinate_set in seat_map {
for &coordinate in coordinate_set {
if !found.insert(coordinate) {
return Err(PlacementAreaError::PositionCollision(coordinate));
}
}
}
}
}
Ok(())
}
}
pub type PlacementAreaResult<T> = Result<T, PlacementAreaError>;
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
pub enum PlacementAreaError {
PositionCannotPlace(Space, Coordinate),
PositionCollision(Coordinate),
InvalidSeatNumber(usize),
}
impl Display for PlacementAreaError {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
<Self as Debug>::fmt(self, f)
}
}
impl Error for PlacementAreaError {}
| true |
72ad157b1e373f83c03c71dcd40a8d45b01ee2f1
|
Rust
|
art-in/meteos
|
/notifications/src/notification.rs
|
UTF-8
| 2,180 | 2.640625 | 3 |
[] |
no_license
|
use crate::{
backend_api,
config::ReadingRanges,
reading::ReadingOptimality,
sample::Sample,
tg_bot::{GetTgMessage, TgMessage, TgMessageFormat},
utils::beautiful_string_join,
};
use std::{fmt::Debug, time::Duration};
#[derive(Debug)]
pub struct NotOptimalReadingsNotification {
pub not_optimal_readings: Vec<ReadingOptimality>,
pub latest_sample: Sample,
pub optimal_ranges: ReadingRanges,
}
#[derive(Debug)]
pub struct BackendErrorNotification {
pub latest_error: backend_api::BackendApiError,
pub error_period: Duration,
pub error_count: u32,
}
// telegram message is the only representation supported for now.
// work on more notification channels in future may require to extend
// Notification to support more representations. eg.:
// trait Notification: GetTgMessage + GetEmailMessage + GetSmsMessage {}
pub trait Notification: GetTgMessage {}
impl Notification for NotOptimalReadingsNotification {}
impl Notification for BackendErrorNotification {}
impl GetTgMessage for NotOptimalReadingsNotification {
fn get_tg_message(&self) -> TgMessage {
let reading_statuses: Vec<&str> = self
.not_optimal_readings
.iter()
.map(|r| r.format_as_status_string())
.collect();
TgMessage {
format: TgMessageFormat::MarkdownV2,
text: format!(
"{status}\n\n\
{latest_sample_md}",
status = beautiful_string_join(reading_statuses),
latest_sample_md = self.latest_sample.format_as_markdown(&self.optimal_ranges)
),
}
}
}
impl GetTgMessage for BackendErrorNotification {
fn get_tg_message(&self) -> TgMessage {
TgMessage {
format: TgMessageFormat::Html,
text: format!(
"ERROR: \
{count} backend request(s) have failed in the last {period} minute(s). \
Latest error: {latest_error}",
count = self.error_count,
period = (self.error_period.as_secs() / 60) as u32,
latest_error = self.latest_error
),
}
}
}
| true |
3842550a0730f7d908eeda82ea06cb4d13a21cf1
|
Rust
|
skial/back-to-basics
|
/rustlang/types/scalar/integer/assign/src/main.rs
|
UTF-8
| 82 | 2.6875 | 3 |
[
"MIT"
] |
permissive
|
fn main() {
let int:i32 = 33;
println!("The value of int is: {}", int);
}
| true |
623e4007fa92fd25d6066efbab2019a47afae878
|
Rust
|
boylede/rusty-celery
|
/src/beat/mod.rs
|
UTF-8
| 9,393 | 2.78125 | 3 |
[
"Apache-2.0"
] |
permissive
|
/// This module contains the implementation of the Celery **beat**, which is a component
/// that can be used to automatically execute tasks at scheduled times.
///
/// ### Terminology
///
/// This is the terminology used in this module (with references to the corresponding names
/// in the Python implementation):
/// - schedule: the strategy used to decide when a task must be executed (each scheduled
/// task has its own schedule);
/// - scheduled task: a task together with its schedule (it more or less corresponds to
/// a *schedule entry* in Python);
/// - scheduler: the component in charge of keeping track of tasks to execute;
/// - backend: the component that updates the internal state of the scheduler according to
/// to an external source of truth (e.g., a database); there is no equivalent in Python,
/// due to the fact that another pattern is used (see below);
/// - beat: the service that drives the execution, calling the appropriate
/// methods of the scheduler in an infinite loop (called just *service* in Python).
///
/// The main difference with the architecture used in Python is that in Python
/// there is a base scheduler class which contains the scheduling logic, then different
/// implementations use different strategies to synchronize the scheduler.
/// Here instead we have only one scheduler struct, and the different backends
/// correspond to the different scheduler implementations in Python.
use crate::broker::{build_and_connect, configure_task_routes, Broker, BrokerBuilder};
use crate::routing::{self, Rule};
use crate::{
error::{BeatError, CeleryError},
task::{Signature, Task},
};
use log::{debug, info};
use std::time::SystemTime;
use tokio::time;
mod scheduler;
use scheduler::Scheduler;
mod backend;
pub use backend::{DummyBackend, SchedulerBackend};
mod schedule;
pub use schedule::{RegularSchedule, Schedule};
mod scheduled_task;
pub use scheduled_task::ScheduledTask;
struct Config<Bb>
where
Bb: BrokerBuilder,
{
name: String,
broker_builder: Bb,
broker_connection_timeout: u32,
broker_connection_retry: bool,
broker_connection_max_retries: u32,
default_queue: String,
task_routes: Vec<(String, String)>,
}
/// Used to create a `Beat` app with a custom configuration.
pub struct BeatBuilder<Bb, Sb>
where
Bb: BrokerBuilder,
Sb: SchedulerBackend,
{
config: Config<Bb>,
scheduler_backend: Sb,
}
impl<Bb> BeatBuilder<Bb, DummyBackend>
where
Bb: BrokerBuilder,
{
/// Get a `BeatBuilder` for creating a `Beat` app with a default scheduler backend
/// and a custom configuration.
pub fn with_default_scheduler_backend(name: &str, broker_url: &str) -> Self {
Self {
config: Config {
name: name.into(),
broker_builder: Bb::new(broker_url),
broker_connection_timeout: 2,
broker_connection_retry: true,
broker_connection_max_retries: 100,
default_queue: "celery".into(),
task_routes: vec![],
},
scheduler_backend: DummyBackend::new(),
}
}
}
impl<Bb, Sb> BeatBuilder<Bb, Sb>
where
Bb: BrokerBuilder,
Sb: SchedulerBackend,
{
/// Get a `BeatBuilder` for creating a `Beat` app with a custom scheduler backend and
/// a custom configuration.
pub fn with_custom_scheduler_backend(
name: &str,
broker_url: &str,
scheduler_backend: Sb,
) -> Self {
Self {
config: Config {
name: name.into(),
broker_builder: Bb::new(broker_url),
broker_connection_timeout: 2,
broker_connection_retry: true,
broker_connection_max_retries: 100,
default_queue: "celery".into(),
task_routes: vec![],
},
scheduler_backend,
}
}
/// Set the name of the default queue to something other than "celery".
pub fn default_queue(mut self, queue_name: &str) -> Self {
self.config.default_queue = queue_name.into();
self
}
/// Set the broker heartbeat. The default value depends on the broker implementation.
pub fn heartbeat(mut self, heartbeat: Option<u16>) -> Self {
self.config.broker_builder = self.config.broker_builder.heartbeat(heartbeat);
self
}
/// Add a routing rule.
pub fn task_route(mut self, pattern: &str, queue: &str) -> Self {
self.config.task_routes.push((pattern.into(), queue.into()));
self
}
/// Set a timeout in seconds before giving up establishing a connection to a broker.
pub fn broker_connection_timeout(mut self, timeout: u32) -> Self {
self.config.broker_connection_timeout = timeout;
self
}
/// Set whether or not to automatically try to re-establish connection to the AMQP broker.
pub fn broker_connection_retry(mut self, retry: bool) -> Self {
self.config.broker_connection_retry = retry;
self
}
/// Set the maximum number of retries before we give up trying to re-establish connection
/// to the AMQP broker.
pub fn broker_connection_max_retries(mut self, max_retries: u32) -> Self {
self.config.broker_connection_max_retries = max_retries;
self
}
/// Construct a `Beat` app with the current configuration.
pub async fn build(self) -> Result<Beat<Bb::Broker, Sb>, CeleryError> {
// Declare default queue to broker.
let broker_builder = self
.config
.broker_builder
.declare_queue(&self.config.default_queue);
let (broker_builder, task_routes) =
configure_task_routes(broker_builder, &self.config.task_routes)?;
let broker = build_and_connect(
broker_builder,
self.config.broker_connection_timeout,
self.config.broker_connection_retry,
self.config.broker_connection_max_retries,
)
.await?;
let scheduler = Scheduler::new(broker);
Ok(Beat {
name: self.config.name,
scheduler,
scheduler_backend: self.scheduler_backend,
task_routes,
default_queue: self.config.default_queue,
})
}
}
/// A `Beat` app is used to execute scheduled tasks. This is the struct that is
/// created with the [`beat`](macro.beat.html) macro.
///
/// The *beat* is in charge of executing scheduled tasks when
/// they are due and to add or remove tasks as required. It drives execution by
/// making the internal scheduler "tick", and updates the list of scheduled
/// tasks through a customizable scheduler backend.
pub struct Beat<Br: Broker, Sb: SchedulerBackend> {
pub name: String,
scheduler: Scheduler<Br>,
scheduler_backend: Sb,
task_routes: Vec<Rule>,
default_queue: String,
}
impl<Br> Beat<Br, DummyBackend>
where
Br: Broker,
{
/// Get a `BeatBuilder` for creating a `Beat` app with a custom configuration and a
/// default scheduler backend.
pub fn default_builder(name: &str, broker_url: &str) -> BeatBuilder<Br::Builder, DummyBackend> {
BeatBuilder::<Br::Builder, DummyBackend>::with_default_scheduler_backend(name, broker_url)
}
}
impl<Br, Sb> Beat<Br, Sb>
where
Br: Broker,
Sb: SchedulerBackend,
{
/// Get a `BeatBuilder` for creating a `Beat` app with a custom configuration and
/// a custom scheduler backend.
pub fn custom_builder(
name: &str,
broker_url: &str,
scheduler_backend: Sb,
) -> BeatBuilder<Br::Builder, Sb> {
BeatBuilder::<Br::Builder, Sb>::with_custom_scheduler_backend(
name,
broker_url,
scheduler_backend,
)
}
/// Schedule the execution of a task.
pub fn schedule_task<T, S>(&mut self, signature: Signature<T>, schedule: S)
where
T: Task + Clone + 'static,
S: Schedule + 'static,
{
let queue = match &signature.queue {
Some(queue) => queue.to_string(),
None => routing::route(T::NAME, &self.task_routes)
.unwrap_or(&self.default_queue)
.to_string(),
};
let message_factory = Box::new(signature);
self.scheduler.schedule_task(
Signature::<T>::task_name().to_string(),
message_factory,
queue,
schedule,
);
}
/// Start the *beat*. For each error that occurs pause the execution
/// and return the error.
pub async fn start(&mut self) -> Result<(), BeatError> {
info!("Starting beat service");
loop {
let next_tick_at = self.scheduler.tick().await?;
if self.scheduler_backend.should_sync() {
self.scheduler_backend
.sync(self.scheduler.get_scheduled_tasks())?;
}
let now = SystemTime::now();
if now < next_tick_at {
let sleep_interval = next_tick_at.duration_since(now).expect(
"Unexpected error when unwrapping a SystemTime comparison that is not supposed to fail",
);
debug!("Now sleeping for {:?}", sleep_interval);
time::delay_for(sleep_interval).await;
}
}
}
}
#[cfg(test)]
mod tests;
| true |
5c53a52b8b4c839e833b67e1fbf66df4b69c36dd
|
Rust
|
mufeedvh/jam0001
|
/HectorHW/src/execution/objects.rs
|
UTF-8
| 1,834 | 3.171875 | 3 |
[] |
no_license
|
use std::fmt::{Display, Formatter};
use crate::parsing::ast::{Stmt};
use crate::parsing::token::Token;
use crate::execution::predef::RcNative;
#[derive(Clone)]
pub enum Object {
String(String),
Num(i64),
Function(Vec<Stmt>, Vec<Token>),
NativeFunction(RcNative, usize)
}
impl Object {
pub fn is_true(&self) -> bool {
match self {
Object::String(s) => {s.is_empty()}
Object::Num(n) => {*n!=0}
Object::Function(_, _) => {true}
Object::NativeFunction(_, _) => {true}
}
}
pub fn unwrap_num(&self) -> Option<i64> {
match self {
Object::Num(n) => {Some(*n)},
_ => None
}
}
}
impl PartialEq for Object {
fn eq(&self, other: &Self) -> bool {
if std::mem::discriminant(self)!=std::mem::discriminant(other){
return false;
}
use Object::*;
match (self, other) {
(String(s1), String(s2)) => {s1==s2},
(Num(n1), Num(n2)) => {n1==n2},
(Function(f1,arg1), Function(f2,arg2))
=> {f1==f2 && arg1==arg2}
(NativeFunction(f1, a1), NativeFunction(f2, a2))
=> {
a1==a2 && std::ptr::eq(f1, f2)
}
_ => panic!("unimplemented object comparison")
}
}
}
impl Display for Object {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Object::String(s) => {write!(f, "{}", s)}
Object::Num(n) => {write!(f, "{}", n)}
Object::Function(_, args) => {
write!(f, "function with {} arg(s)", args.len())
}
Object::NativeFunction(_, arity) => {
write!(f, "native function with {} arg(s)", arity)
}
}
}
}
| true |
602534f9947aba688ab0e8751d364ca4b6322efc
|
Rust
|
fiz3d/fiz
|
/math/src/unit/m.rs
|
UTF-8
| 2,384 | 3.71875 | 4 |
[
"BSD-3-Clause"
] |
permissive
|
use num::traits::{Num, NumCast};
use super::cm::{CM, ToCM};
use super::mm::{MM, ToMM};
use super::km::{KM, ToKM};
/// ToM is the canonical trait to use for taking input in meters.
///
/// For example the millimeters type (MM) implements the ToM trait and thus
/// millimeters can be given as a parameter to any input that seeks meters.
pub trait ToM{
type Output;
/// to_m returns these units in meters, performing conversion if needed.
///
/// # Examples
///
/// ```
/// use fiz_math::unit::{MM, ToM};
/// use fiz_math::Num;
/// use std::fmt::Debug;
///
/// fn walk<T: ToM<Output=U>, U: Num+Debug>(dist: T) {
/// println!("{:?}", dist.to_m().0)
/// }
/// walk(MM(2.0));
/// walk(MM::<i16>(2));
/// ```
fn to_m(self) -> M<Self::Output>;
}
/// M represents meters (the SI base unit representing distance).
///
/// # Examples
///
/// ```
/// use fiz_math::unit::M;
///
/// let x = M(1.0);
/// println!("{:?}", x);
/// ```
unit!(M);
impl<T: Num + NumCast> ToMM for M<T> {
type Output = T;
/// to_mm returns these meters converted to millimeters.
///
/// # Examples
///
/// ```
/// use fiz_math::unit::{M, MM, ToMM};
///
/// assert_eq!(M(1.0).to_mm(), MM(1000.0));
/// ```
fn to_mm(self) -> MM<T> {
MM(self.0 * T::from(1000).unwrap())
}
}
impl<T: Num + NumCast> ToCM for M<T> {
type Output = T;
/// to_cm returns these meters converted to centimeters.
///
/// # Examples
///
/// ```
/// use fiz_math::unit::{M, CM, ToCM};
///
/// assert_eq!(M(1.0).to_cm(), CM(100.0));
/// ```
fn to_cm(self) -> CM<T> {
CM(self.0 * T::from(100).unwrap())
}
}
impl<T: Num + NumCast> ToM for M<T> {
type Output = T;
/// to_m simply returns self.
///
/// # Examples
///
/// ```
/// use fiz_math::unit::{M, ToM};
///
/// assert_eq!(M(1.0).to_m(), M(1.0));
/// ```
fn to_m(self) -> M<T> {
self
}
}
impl<T: Num + NumCast> ToKM for M<T> {
type Output = T;
/// to_km returns these meters converted to kilometers.
///
/// # Examples
///
/// ```
/// use fiz_math::unit::{M, KM, ToKM};
///
/// assert_eq!(M(1000.0).to_km(), KM(1.0));
/// ```
fn to_km(self) -> KM<T> {
KM(self.0 / T::from(1000).unwrap())
}
}
| true |
abf8e84f6e322851825a7949a1e8b2e684f1900a
|
Rust
|
thomasrockhu/Toshi
|
/src/handlers/search.rs
|
UTF-8
| 7,722 | 2.78125 | 3 |
[
"MIT"
] |
permissive
|
use std::sync::{Arc, RwLock};
use futures::{future, Future};
use log::info;
use tower_web::*;
use crate::index::IndexCatalog;
use crate::query::Request;
use crate::results::ScoredDoc;
use crate::results::SearchResults;
use crate::Error;
#[derive(Clone)]
pub struct SearchHandler {
catalog: Arc<RwLock<IndexCatalog>>,
}
impl SearchHandler {
pub fn new(catalog: Arc<RwLock<IndexCatalog>>) -> Self {
SearchHandler { catalog }
}
fn fold_results(results: Vec<SearchResults>) -> SearchResults {
let mut docs: Vec<ScoredDoc> = Vec::new();
for result in results {
docs.extend(result.docs);
}
SearchResults::new(docs)
}
}
impl_web! {
impl SearchHandler {
#[post("/:index")]
#[content_type("application/json")]
pub fn doc_search(&self, body: Request, index: String) -> impl Future<Item = SearchResults, Error = Error> + Send {
info!("Query: {:?}", body);
let mut futs = Vec::new();
match self.catalog.read() {
Ok(cat) => {
if cat.exists(&index) {
futs.push(future::Either::A(cat.search_local_index(&index, body.clone())));
}
if cat.remote_exists(&index) {
futs.push(future::Either::B(cat.search_remote_index(&index, body.clone())));
}
return future::join_all(futs).map(|r| SearchHandler::fold_results(r.into_iter().flatten().collect()));
}
_ => panic!("asdf"),
}
}
#[get("/:index")]
#[content_type("application/json")]
pub fn get_all_docs(&self, index: String) -> impl Future<Item = SearchResults, Error = Error> + Send {
self.doc_search(Request::all_docs(), index)
}
}
}
#[cfg(test)]
pub mod tests {
use super::*;
use crate::index::tests::*;
use crate::query::*;
use std::collections::HashMap;
pub fn make_map<V>(field: &'static str, term: V) -> HashMap<String, V> {
let mut term_map = HashMap::<String, V>::new();
term_map.insert(field.into(), term);
term_map
}
pub fn run_query(req: Request, index: &str) -> impl Future<Item = SearchResults, Error = Error> + Send {
let cat = create_test_catalog(index.into());
let handler = SearchHandler::new(Arc::clone(&cat));
handler.doc_search(req, index.into())
}
#[test]
fn test_term_query() {
let term = make_map("test_text", String::from("document"));
let term_query = Query::Exact(ExactTerm { term });
let search = Request::new(Some(term_query), None, 10);
run_query(search, "test_index")
.map(|q| {
dbg!(&q);
assert_eq!(q.hits, 3);
})
.map_err(|_| ())
.wait()
.unwrap();
}
// Should I do this? with the tokio::run
#[test]
fn test_wrong_index_error() {
let cat = create_test_catalog("test_index");
let handler = SearchHandler::new(Arc::clone(&cat));
let body = r#"{ "query" : { "raw": "test_text:\"document\"" } }"#;
let req: Request = serde_json::from_str(body).unwrap();
handler
.doc_search(req, "asdf".into())
.map_err(|err| assert_eq!(err.to_string(), "asdf"))
.map(|_| ())
.wait()
.unwrap();
}
// Or this with the .wait() for the future?
#[test]
fn test_bad_raw_query_syntax() {
let cat = create_test_catalog("test_index");
let handler = SearchHandler::new(Arc::clone(&cat));
let body = r#"{ "query" : { "raw": "asd*(@sq__" } }"#;
let req: Request = serde_json::from_str(body).unwrap();
handler
.doc_search(req, "test_index".into())
.map_err(|err| {
dbg!(&err.to_string());
assert_eq!(err.to_string(), "Query Parse Error: invalid digit found in string");
})
.wait();
}
#[test]
fn test_unindexed_field() {
let cat = create_test_catalog("test_index");
let handler = SearchHandler::new(Arc::clone(&cat));
let body = r#"{ "query" : { "raw": "test_unindex:asdf" } }"#;
let req: Request = serde_json::from_str(body).unwrap();
let docs = handler
.doc_search(req, "test_index".into())
.map_err(|err| match err {
Error::QueryError(e) => assert_eq!(e.to_string(), "Query to unindexed field \'test_unindex\'"),
_ => assert_eq!(true, false),
})
.map(|_| ());
tokio::run(docs);
}
#[test]
fn test_bad_term_field_syntax() {
let cat = create_test_catalog("test_index");
let handler = SearchHandler::new(Arc::clone(&cat));
let body = r#"{ "query" : { "term": { "asdf": "Document" } } }"#;
let req: Request = serde_json::from_str(body).unwrap();
let docs = handler
.doc_search(req, "test_index".into())
.map_err(|err| match err {
Error::QueryError(e) => assert_eq!(e.to_string(), "Field: asdf does not exist"),
_ => assert_eq!(true, false),
})
.map(|_| ());
tokio::run(docs);
}
#[test]
fn test_raw_query() {
let body = r#"test_text:"Duckiment""#;
let req = Request::new(Some(Query::Raw { raw: body.into() }), None, 10);
let docs = run_query(req, "test_index")
.map(|result| {
assert_eq!(result.hits as usize, result.docs.len());
assert_eq!(result.docs[0].doc.get("test_text").unwrap()[0].text().unwrap(), "Test Duckiment 3")
})
.map_err(|_| ());
tokio::run(docs);
}
#[test]
fn test_fuzzy_term_query() {
let fuzzy = make_map("test_text", FuzzyTerm::new("document".into(), 0, false));
let term_query = Query::Fuzzy(FuzzyQuery { fuzzy });
let search = Request::new(Some(term_query), None, 10);
let query = run_query(search, "test_index")
.map(|result| {
assert_eq!(result.hits as usize, result.docs.len());
assert_eq!(result.hits, 3);
assert_eq!(result.docs.len(), 3);
})
.map_err(|_| ());
tokio::run(query);
}
#[test]
fn test_inclusive_range_query() {
let body = r#"{ "query" : { "range" : { "test_i64" : { "gte" : 2012, "lte" : 2015 } } } }"#;
let req: Request = serde_json::from_str(body).unwrap();
let docs = run_query(req, "test_index")
.map(|result| {
assert_eq!(result.hits as usize, result.docs.len());
assert_eq!(result.docs[0].score.unwrap(), 1.0);
})
.map_err(|_| ());
tokio::run(docs);
}
#[test]
fn test_exclusive_range_query() {
let body = r#"{ "query" : { "range" : { "test_i64" : { "gt" : 2012, "lt" : 2015 } } } }"#;
let req: Request = serde_json::from_str(&body).unwrap();
let docs = run_query(req, "test_index")
.map(|results| {
assert_eq!(results.hits as usize, results.docs.len());
assert_eq!(results.docs[0].score.unwrap(), 1.0);
})
.map_err(|_| ());
tokio::run(docs);
}
// This is ignored right now while we wait for https://github.com/tantivy-search/tantivy/pull/437
// to be released.
//#[test]
//#[ignore]
//fn test_aggregate_sum() {
// let _body = r#"{ "query": { "field": "test_u64" } }"#;
//}
}
| true |
233094a367021de0c19e949db94b99c4fa684bab
|
Rust
|
aDotInTheVoid/ltxmk
|
/src/strings.rs
|
UTF-8
| 570 | 2.640625 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"Apache-2.0"
] |
permissive
|
//! Important strings
/// Regexes for errors
const FILE_NOT_FOUND: &[&str] = &[
r"^No file\s*(.*)\.$",
r"^\! LaTeX Error: File `([^\']*)\' not found\.",
r"^\! I can\'t find file `([^\']*)\'\.",
r".*?:\d*: LaTeX Error: File `([^\']*)\' not found\.",
r"^LaTeX Warning: File `([^\']*)\' not found",
r"^Package .* [fF]ile `([^\']*)\' not found",
r"^Package .* No file `([^\']*)\'",
r"Error: pdflatex \(file ([^\)]*)\): cannot find image file",
r": File (.*) not found:\s*$",
r"! Unable to load picture or PDF file \'([^\']+)\'.",
];
| true |
afe6b4dd48ed31c4b8cddc9b009e8175369c2181
|
Rust
|
royvegard/aoc_2020
|
/src/day11.rs
|
UTF-8
| 5,975 | 3.375 | 3 |
[
"MIT"
] |
permissive
|
#[aoc(day11, part1)]
pub fn solve_part1(input: &str) -> usize {
game_of_seats(input)
}
#[aoc(day11, part2)]
pub fn solve_part2(input: &str) -> usize {
game_of_seats_los(input)
}
#[derive(Clone)]
struct Seat {
state: char,
next_state: char,
}
fn game_of_seats(input: &str) -> usize {
let mut layout: Vec<Vec<Seat>> = input
.lines()
.map(|x| {
x.chars()
.map(|x| Seat {
state: x,
next_state: ' ',
})
.collect()
})
.collect();
loop {
for row_no in 0..layout.len() {
for col_no in 0..layout.first().unwrap().len() {
let adjacent = get_adjacent(&layout, row_no, col_no);
if layout[row_no][col_no].state == 'L' && adjacent == 0 {
layout[row_no][col_no].next_state = '#';
} else if layout[row_no][col_no].state == '#' && adjacent >= 4 {
layout[row_no][col_no].next_state = 'L';
} else if layout[row_no][col_no].state == '.' {
layout[row_no][col_no].next_state = '.';
} else {
layout[row_no][col_no].next_state = layout[row_no][col_no].state;
}
}
}
if is_stable(&layout) {
break;
}
for row_no in 0..layout.len() {
for col_no in 0..layout.first().unwrap().len() {
layout[row_no][col_no].state = layout[row_no][col_no].next_state;
}
}
}
get_occupied(&layout)
}
fn game_of_seats_los(input: &str) -> usize {
let mut layout: Vec<Vec<Seat>> = input
.lines()
.map(|x| {
x.chars()
.map(|x| Seat {
state: x,
next_state: ' ',
})
.collect()
})
.collect();
loop {
for row_no in 0..layout.len() {
for col_no in 0..layout.first().unwrap().len() {
let adjacent = get_adjacent_los(&layout, row_no as isize, col_no as isize);
if layout[row_no][col_no].state == 'L' && adjacent == 0 {
layout[row_no][col_no].next_state = '#';
} else if layout[row_no][col_no].state == '#' && adjacent >= 5 {
layout[row_no][col_no].next_state = 'L';
} else if layout[row_no][col_no].state == '.' {
layout[row_no][col_no].next_state = '.';
} else {
layout[row_no][col_no].next_state = layout[row_no][col_no].state;
}
}
}
if is_stable(&layout) {
break;
}
for row_no in 0..layout.len() {
for col_no in 0..layout.first().unwrap().len() {
layout[row_no][col_no].state = layout[row_no][col_no].next_state;
}
}
}
get_occupied(&layout)
}
fn is_stable(layout: &Vec<Vec<Seat>>) -> bool {
let mut stable = true;
for row_no in 0..layout.len() {
for col_no in 0..layout.first().unwrap().len() {
if !(layout[row_no][col_no].state == layout[row_no][col_no].next_state) {
stable = false;
}
}
}
stable
}
fn get_occupied(layout: &Vec<Vec<Seat>>) -> usize {
let mut occupied = 0;
for row_no in 0..layout.len() {
for col_no in 0..layout.first().unwrap().len() {
if layout[row_no][col_no].state == '#' {
occupied += 1;
}
}
}
occupied
}
fn get_adjacent(layout: &Vec<Vec<Seat>>, row: usize, col: usize) -> usize {
let mut adj = 0;
let last_row = layout.len() - 1;
let last_col = layout.first().unwrap().len() - 1;
for r in &[row as isize - 1, row as isize, row as isize + 1] {
for c in &[col as isize - 1, col as isize, col as isize + 1] {
if r == &(row as isize) && c == &(col as isize) {
continue;
}
if r < &0 || c < &0 {
continue;
}
if r > &(last_row as isize) || c > &(last_col as isize) {
continue;
}
if layout[*r as usize][*c as usize].state == '#' {
adj += 1;
}
}
}
adj
}
fn get_adjacent_los(layout: &Vec<Vec<Seat>>, row: isize, col: isize) -> usize {
let mut adj = 0;
let last_row = (layout.len() - 1) as isize;
let last_col = (layout.first().unwrap().len() - 1) as isize;
let directions: Vec<(isize, isize)> = vec![
(-1, 0), // north
(-1, 1), // northeast
(0, 1), // east
(1, 1), // southeast
(1, 0), // south
(1, -1), // southwest
(0, -1), // west
(-1, -1), // nortwest
];
for dir in directions {
let mut r = row;
let mut c = col;
let mut step = 0;
while step < last_row {
r += dir.0;
c += dir.1;
if r == row && c == col {
break;
}
if r < 0 || c < 0 {
break;
}
if r > last_row || c > last_col {
break;
}
if layout[r as usize][c as usize].state == '#' {
adj += 1;
break;
} else if layout[r as usize][c as usize].state == 'L' {
break;
}
step += 1;
}
}
adj
}
#[cfg(test)]
mod tests {
use super::*;
const EXAMPLE_DATA_1: &str = "L.LL.LL.LL
LLLLLLL.LL
L.L.L..L..
LLLL.LL.LL
L.LL.LL.LL
L.LLLLL.LL
..L.L.....
LLLLLLLLLL
L.LLLLLL.L
L.LLLLL.LL";
#[test]
fn play_game_of_seats() {
assert!(game_of_seats(EXAMPLE_DATA_1) == 37);
}
#[test]
fn play_game_of_seats_los() {
assert!(game_of_seats_los(EXAMPLE_DATA_1) == 26);
}
}
| true |
6000291393620c887c11dae9a3c010d817217f93
|
Rust
|
arynh/cs419-ray-tracer
|
/src/hittable/sphere.rs
|
UTF-8
| 2,685 | 3.46875 | 3 |
[
"MIT"
] |
permissive
|
use crate::hit_record::HitRecord;
use crate::hittable::aabb::AABB;
use crate::hittable::Hittable;
use crate::material::MaterialType;
use crate::ray::Ray;
use glm::Vec3;
/// Represent a sphere in space
pub struct Sphere {
/// center point of the sphere
pub center: Vec3,
/// radius of the sphere
pub radius: f32,
/// material to use for the sphere
pub material: MaterialType,
}
/// Methods from the hittable trait
impl Hittable for Sphere {
/// If an object will be hit by a ray in a certain range, return a
/// hit record with the intersection information. Otherwise, return `None`.
///
/// # Arguments
/// - `ray` the ray to search for intersections along
/// - `min_distance` the minimum distance of intersections along the ray
/// - `max_distance` the maximum distance of intersections
///
/// # Returns
/// - Optional `HitRecord` if there was a hit, otherwise `None`.
fn hit(&self, ray: &Ray, min_distance: f32, max_distance: f32) -> Option<HitRecord> {
// calculate the discriminant
let oc = ray.origin - self.center;
let a = glm::dot(&ray.direction, &ray.direction);
let half_b = glm::dot(&oc, &ray.direction);
let c = glm::dot(&oc, &oc) - self.radius * self.radius;
let discriminant = half_b.powi(2) - a * c;
if discriminant > 0.0 {
let root = discriminant.sqrt();
let mut x = (-half_b - root) / a;
if x < max_distance && x > min_distance {
Some(HitRecord {
hit_point: ray.at(x),
ray: *ray,
distance: x,
outward_normal: (ray.at(x) - self.center) / self.radius,
material: Some(&self.material),
})
} else {
x = (-half_b + root) / a;
if x < max_distance && x > min_distance {
Some(HitRecord {
hit_point: ray.at(x),
ray: *ray,
distance: x,
outward_normal: (ray.at(x) - self.center) / self.radius,
material: Some(&self.material),
})
} else {
None
}
}
} else {
None
}
}
/// Calculate the bounding box for this sphere.
fn bounding_box(&self) -> Option<AABB> {
Some(AABB {
minimum_point: self.center - glm::vec3(self.radius, self.radius, self.radius),
maximum_point: self.center + glm::vec3(self.radius, self.radius, self.radius),
})
}
}
| true |
dba39f431b7319e1ce22790309ba8a7f41d10feb
|
Rust
|
bouzuya/rust-atcoder
|
/cargo-atcoder/contests/nomura2020/src/bin/c.rs
|
UTF-8
| 611 | 2.75 | 3 |
[] |
no_license
|
use std::cmp;
use proconio::input;
fn main() {
input! {
n: usize,
a: [usize; n + 1],
};
if a[0] > 1 {
println!("-1");
return;
}
let mut v = 1_usize - a[0];
let mut b = vec![(v, a[0])];
for &a_i in a.iter().skip(1) {
if a_i > v * 2 {
println!("-1");
return;
}
v = v * 2 - a_i;
b.push((v, a_i));
}
let mut c = a[n];
let mut v = a[n];
for &(m, l) in b.iter().rev().skip(1) {
v = cmp::min(m + l, v + l);
c += v;
}
let ans = c;
println!("{}", ans);
}
| true |
2f27fe9a511ebe1c6942b688a4752a8c090cdad8
|
Rust
|
coreos/fedora-coreos-cincinnati
|
/commons/src/web.rs
|
UTF-8
| 2,989 | 2.703125 | 3 |
[
"Apache-2.0"
] |
permissive
|
use crate::graph::GraphScope;
use actix_cors::CorsFactory;
use failure::{bail, ensure, err_msg};
use std::collections::HashSet;
/// Build a CORS middleware.
///
/// By default, this allows all CORS requests from all origins.
/// If an allowlist is provided, only those origins are allowed instead.
pub fn build_cors_middleware(origin_allowlist: &Option<Vec<String>>) -> CorsFactory {
let mut builder = actix_cors::Cors::new();
match origin_allowlist {
Some(allowed) => {
for origin in allowed {
builder = builder.allowed_origin(origin.as_ref());
}
}
None => {
builder = builder.send_wildcard();
}
};
builder.finish()
}
/// Validate input query parameters into a valid graph scope.
pub fn validate_scope(
basearch: Option<String>,
stream: Option<String>,
scope_allowlist: &Option<HashSet<GraphScope>>,
) -> Result<GraphScope, failure::Error> {
let basearch = basearch.ok_or_else(|| err_msg("missing basearch"))?;
ensure!(!basearch.is_empty(), "empty basearch");
let stream = stream.ok_or_else(|| err_msg("missing stream"))?;
ensure!(!stream.is_empty(), "empty stream");
let scope = GraphScope { basearch, stream };
// Optionally filter out scope according to given allowlist, if any.
if let Some(allowlist) = scope_allowlist {
if !allowlist.contains(&scope) {
bail!(
"scope not allowed: basearch='{}', stream='{}'",
scope.basearch,
scope.stream
);
}
}
Ok(scope)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_validate_scope() {
{
let r = validate_scope(None, None, &None);
assert!(r.is_err());
}
{
let basearch = Some("test_empty".to_string());
let stream = Some("".to_string());
let r = validate_scope(basearch, stream, &None);
assert!(r.is_err());
}
{
let basearch = Some("x86_64".to_string());
let stream = Some("stable".to_string());
let r = validate_scope(basearch, stream, &None);
assert!(r.is_ok());
}
{
let basearch = Some("x86_64".to_string());
let stream = Some("stable".to_string());
let filter_none_allowed = Some(HashSet::new());
let r = validate_scope(basearch, stream, &filter_none_allowed);
assert!(r.is_err());
}
{
let basearch = Some("x86_64".to_string());
let stream = Some("stable".to_string());
let allowed_scope = GraphScope {
basearch: "x86_64".to_string(),
stream: "stable".to_string(),
};
let filter = Some(maplit::hashset! {allowed_scope});
let r = validate_scope(basearch, stream, &filter);
assert!(r.is_ok());
}
}
}
| true |
32cf67a2e10acaab036d922b0e020704a169f992
|
Rust
|
zwhitchcox/leetcode_rs
|
/src/_0118_pascal_triangle.rs
|
UTF-8
| 815 | 3.46875 | 3 |
[
"MIT"
] |
permissive
|
struct Solution;
impl Solution {
fn generate(nums_rows: i32) -> Vec<Vec<i32>> {
let mut res: Vec<Vec<i32>> = vec![];
for i in 0..nums_rows {
let ui = i as usize;
res.push(vec![]);
for j in 0..=i {
let uj = j as usize;
if j == 0 || j == i {
res[ui].push(1);
} else {
let prev = &res[ui - 1];
let sum = prev[uj - 1] + prev[uj];
res[ui].push(sum);
}
}
}
res
}
}
#[test]
fn test() {
let triangle_5 = vec![
vec![1],
vec![1, 1],
vec![1, 2, 1],
vec![1, 3, 3, 1],
vec![1, 4, 6, 4, 1],
];
assert_eq!(Solution::generate(5), triangle_5);
}
| true |
b48f255e812ecbff84a496c69c4c654161c553de
|
Rust
|
markatk/serial-unit-testing
|
/src/parser/mod.rs
|
UTF-8
| 12,564 | 2.578125 | 3 |
[
"MIT"
] |
permissive
|
/*
* File: src/parser/mod.rs
* Date: 02.10.2018
* Author: MarkAtk
*
* MIT License
*
* Copyright (c) 2018 MarkAtk
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
use std::fs;
use std::io::{BufReader, Read};
use regex::Regex;
use crate::tests::{TestCase, TestSuite, TestCaseSettings, TestSuiteSettings};
use crate::utils::TextFormat;
mod error;
mod token;
mod string_util;
mod char_util;
mod lexer;
mod finite_state_machine;
mod options;
use self::lexer::Lexer;
use self::token::{Token, TokenType};
use self::error::Error;
use self::finite_state_machine::FiniteStateMachine;
use self::options::{set_test_option, set_group_option};
/// Parse the given file for tests and test suites.
///
/// A vector of test suites is returned on successful parsing, otherwise a parsing error is returned.
pub fn parse_file(file: &mut fs::File) -> Result<Vec<TestSuite>, Error> {
parse_file_with_default_settings(file, Default::default())
}
/// Parse the given file for tests and test suites with the given default settings.
///
/// A vector of test suites is returned on successful parsing, otherwise a parsing error is returned.
pub fn parse_file_with_default_settings(file: &mut fs::File, default_test_settings: TestCaseSettings) -> Result<Vec<TestSuite>, Error> {
let mut reader = BufReader::new(file);
let mut content = String::new();
if reader.read_to_string(&mut content).is_err() {
return Err(Error::ReadFile);
}
let mut lexer = Lexer::new(content);
let tokens = lexer.get_tokens();
analyse_tokens(tokens, default_test_settings)
}
fn analyse_tokens(tokens: Vec<Token>, default_test_settings: TestCaseSettings) -> Result<Vec<TestSuite>, Error> {
let mut lines: Vec<Vec<Token>> = Vec::new();
let mut line: Vec<Token> = Vec::new();
// split token stream into lines
for token in tokens {
if token.token_type == TokenType::Illegal {
return Err(Error::IllegalToken(token.value, token.line, token.column));
}
if token.token_type == TokenType::Newline {
// only add line if not empty
if !line.is_empty() {
lines.push(line);
line = Vec::new();
}
continue;
}
line.push(token);
}
// analyse each line
let mut test_suites: Vec<TestSuite> = Vec::new();
// <> mark optional tokens
// / mark alternative tokens
// * repeat tokens
// [ Identifier <, Identifier < = Value> >* ]
let group_state_machine = FiniteStateMachine::new(1, vec!(4), |state, token| -> u32 {
match state {
1 if token.token_type == TokenType::LeftGroupParenthesis => 2,
2 if token.token_type == TokenType::Identifier => 3,
2 if token.token_type == TokenType::ContentSeparator => 5,
3 if token.token_type == TokenType::RightGroupParenthesis => 4,
3 if token.token_type == TokenType::ContentSeparator => 5,
5 if token.token_type == TokenType::Identifier => 6,
6 if token.token_type == TokenType::OptionSeparator => 7,
7 if token.token_type == TokenType::Identifier => 3,
_ => 0
}
});
// <( Identifier <, Identifier < = Value> >* )> < <b/o/d/h>" Content ">* : < <b/o/d/h>" Content ">*
let test_state_machine = FiniteStateMachine::new(1, vec!(9), |state, token| -> u32 {
match state {
1 if token.token_type == TokenType::LeftTestParenthesis => 2,
1 if token.token_type == TokenType::FormatSpecifier => 5,
1 if token.token_type == TokenType::Content => 5,
2 if token.token_type == TokenType::Identifier => 3,
2 if token.token_type == TokenType::ContentSeparator => 10,
3 if token.token_type == TokenType::RightTestParenthesis => 4,
3 if token.token_type == TokenType::ContentSeparator => 10,
4 if token.token_type == TokenType::FormatSpecifier => 5,
4 if token.token_type == TokenType::Content => 6,
5 if token.token_type == TokenType::Content => 6,
6 if token.token_type == TokenType::DirectionSeparator => 7,
7 if token.token_type == TokenType::FormatSpecifier => 8,
7 if token.token_type == TokenType::Content => 9,
8 if token.token_type == TokenType::Content => 9,
10 if token.token_type == TokenType::Identifier => 11,
11 if token.token_type == TokenType::OptionSeparator => 12,
11 if token.token_type == TokenType::ContentSeparator => 10,
11 if token.token_type == TokenType::RightTestParenthesis => 4,
12 if token.token_type == TokenType::Identifier => 3,
_ => 0
}
});
for line in lines {
let first_token: &Token = line.first().unwrap();
if first_token.token_type == TokenType::LeftGroupParenthesis {
match analyse_test_group(&line, &group_state_machine, default_test_settings.clone()) {
Ok(test_suite) => test_suites.push(test_suite),
Err(err) => return Err(err)
};
continue;
}
if first_token.token_type == TokenType::LeftTestParenthesis || first_token.token_type == TokenType::FormatSpecifier || first_token.token_type == TokenType::Content {
match analyse_test(&line, &test_state_machine) {
Ok(test) => {
if test_suites.is_empty() {
test_suites.push(TestSuite::new(String::new()));
}
let test_suite: &mut TestSuite = test_suites.last_mut().unwrap();
test_suite.push(test);
}
Err(err) => return Err(err)
};
continue;
}
return Err(Error::InvalidLineStart(first_token.line, first_token.column));
}
Ok(test_suites)
}
fn analyse_test_group(tokens: &[Token], state_machine: &FiniteStateMachine, default_test_settings: TestCaseSettings) -> Result<TestSuite, Error> {
let result = state_machine.run(tokens);
if let Err((state, token)) = result {
return match state {
2 => Err(Error::MissingGroupIdentifier(token.line, token.column)),
3 => Err(Error::MissingClosingParenthesis("]".to_string(), token.line, token.column)),
5 => Err(Error::MissingOptionIdentifier(token.line, token.column)),
6 => Err(Error::MissingOptionSeparator(token.line, token.column)),
7 => Err(Error::MissingOptionValue(token.line, token.column)),
_ => Err(Error::Unknown(token.line, token.column))
};
}
let mut index = 1;
let name = if tokens[1].token_type == TokenType::Identifier {
index += 1;
tokens[1].value.clone()
} else {
String::new()
};
let mut settings = TestSuiteSettings::default();
let mut test_settings = default_test_settings;
analyse_group_options(&tokens[index..], &mut settings, &mut test_settings)?;
let test_suite = TestSuite::new_with_settings(name, settings, test_settings);
Ok(test_suite)
}
fn analyse_test(tokens: &[Token], state_machine: &FiniteStateMachine) -> Result<TestCase, Error> {
let result = state_machine.run(tokens);
if let Err((state, token)) = result {
return match state {
2 => Err(Error::MissingTestIdentifier(token.line, token.column)),
3 => Err(Error::MissingClosingParenthesis(")".to_string(), token.line, token.column)),
4 | 5 => Err(Error::MissingContent("input".to_string(), token.line, token.column)),
6 => Err(Error::MissingDirectionSeparator(token.line, token.column)),
7 | 8 => Err(Error::MissingContent("output".to_string(), token.line, token.column)),
10 => Err(Error::MissingOptionIdentifier(token.line, token.column)),
11 => Err(Error::MissingOptionSeparator(token.line, token.column)),
12 => Err(Error::MissingOptionValue(token.line, token.column)),
_ => Err(Error::Unknown(token.line, token.column))
};
}
// create test case
let mut name = String::new();
let mut settings = TestCaseSettings::default();
let mut input_format: Option<TextFormat> = None;
let mut output_format: Option<TextFormat> = None;
let mut index = 0;
if tokens[index].token_type == TokenType::LeftTestParenthesis {
if tokens[index + 1].token_type == TokenType::Identifier {
name = tokens[1].value.clone();
index += 1;
}
index += 1;
index += analyse_test_options(&tokens[index..], &mut settings)?;
}
if tokens[index].token_type == TokenType::FormatSpecifier {
input_format = Some(get_text_format(&tokens[index])?);
index += 1;
}
let input = tokens[index].value.clone();
// skip direction separator
index += 2;
if tokens[index].token_type == TokenType::FormatSpecifier {
output_format = Some(get_text_format(&tokens[index])?);
index += 1;
}
let output = tokens[index].value.clone();
if Regex::new(&output).is_err() {
return Err(Error::InvalidOutputContent(output, tokens[index].line, tokens[index].column));
}
let mut test = TestCase::new(name, input, output);
test.settings = settings;
if let Some(format) = input_format {
test.input_format = format;
}
if let Some(format) = output_format {
test.output_format = format;
}
Ok(test)
}
fn analyse_test_options(tokens: &[Token], settings: &mut TestCaseSettings) -> Result<usize, Error> {
let mut index = 0;
while tokens[index].token_type == TokenType::ContentSeparator {
// get length of option
let mut option_length = 1;
while tokens[index + option_length].token_type != TokenType::ContentSeparator && tokens[index + option_length].token_type != TokenType::RightTestParenthesis {
option_length += 1;
}
let offset = set_test_option(&tokens[index + 1 .. index + option_length], settings)?;
index += 2 + offset;
}
Ok(index + 1)
}
fn analyse_group_options(tokens: &[Token], settings: &mut TestSuiteSettings, test_settings: &mut TestCaseSettings) -> Result<usize, Error> {
let mut index = 0;
while tokens[index].token_type == TokenType::ContentSeparator {
// get length of option
let mut option_length = 1;
while tokens[index + option_length].token_type != TokenType::ContentSeparator && tokens[index + option_length].token_type != TokenType::RightGroupParenthesis {
option_length += 1;
}
// test for both group and test option
let offset = match set_test_option(&tokens[index + 1 .. index + option_length], test_settings) {
Ok(offset) => offset,
Err(err) => {
match err {
Error::UnknownTestOption(_, _, _) => set_group_option(&tokens[index + 1 .. index + option_length], settings)?,
_ => return Err(err)
}
},
};
index += 2 + offset;
}
Ok(index + 1)
}
fn get_text_format(token: &Token) -> Result<TextFormat, Error> {
match token.value.as_str() {
"b" => Ok(TextFormat::Binary),
"o" => Ok(TextFormat::Octal),
"d" => Ok(TextFormat::Decimal),
"h" => Ok(TextFormat::Hex),
_ => Err(Error::Unknown(token.line, token.column))
}
}
| true |
b0a2b15bb2efee1f3b8cca863d3b0009b1774762
|
Rust
|
fiberseq/fibertools-rs
|
/bamlift/src/lib.rs
|
UTF-8
| 11,509 | 3.03125 | 3 |
[] |
no_license
|
use itertools::multiunzip;
use rust_htslib::{bam, bam::ext::BamRecordExtensions};
use std::collections::HashMap;
use std::fmt::{Debug, Display};
/// Merge two lists into a sorted list
/// Normal sort is supposed to be very fast on two sorted lists
/// <https://doc.rust-lang.org/std/vec/struct.Vec.html#current-implementation-6>
pub fn merge_two_lists<T>(left: &[T], right: &[T]) -> Vec<T>
where
T: Ord,
T: Clone,
{
let mut x: Vec<T> = left.iter().chain(right.iter()).cloned().collect();
x.sort();
x
}
/// Merge two lists based on a key
/// Normal sort is supposed to be very fast on two sorted lists
/// <https://doc.rust-lang.org/std/vec/struct.Vec.html#current-implementation-6>
/// ```
/// use bamlift::*;
/// let x = vec![1,3];
/// let x_q = vec!["a","b"];
/// let y = vec![2,4];
/// let y_q = vec!["c", "d"];
/// let z = merge_two_lists_with_qual(&x, &x_q, &y, &y_q);
/// assert_eq!(z, vec![(1,"a"), (2,"c"), (3,"b"), (4, "d")]);
/// ```
pub fn merge_two_lists_with_qual<T, U>(
left: &[T],
left_q: &[U],
right: &[T],
right_q: &[U],
) -> Vec<(T, U)>
where
T: Ord,
T: Clone,
U: Clone,
{
let l = left
.iter()
.zip(left_q.iter())
.map(|(a, b)| (a.clone(), b.clone()));
let r = right
.iter()
.zip(right_q.iter())
.map(|(a, b)| (a.clone(), b.clone()));
let mut x: Vec<(T, U)> = l.chain(r).collect();
x.sort_by_key(|(a, _b)| a.clone());
x
}
/// get positions on the complimented sequence in the cigar record
pub fn positions_on_complimented_sequence(
record: &bam::Record,
input_positions: &[i64],
) -> Vec<i64> {
// reverse positions if needed
let positions: Vec<i64> = if record.is_reverse() {
let seq_len = i64::try_from(record.seq_len()).unwrap();
input_positions
.iter()
.rev()
.map(|p| seq_len - p - 1)
.collect()
} else {
input_positions.to_vec()
};
positions
}
/// get positions on the complimented sequence in the cigar record
pub fn positions_on_complimented_sequence_in_place(
record: &bam::Record,
input_positions: &mut Vec<i64>,
part_of_range: bool,
) {
if !record.is_reverse() {
return;
}
let seq_len = i64::try_from(record.seq_len()).unwrap();
// need to correct for going from [) to (] if we are part of a range
let offset = if part_of_range { 0 } else { 1 };
for p in input_positions.iter_mut() {
*p = seq_len - *p - offset;
}
input_positions.reverse();
}
#[inline(always)]
pub fn is_sorted<T>(v: &[T]) -> bool
where
T: Ord,
{
v.windows(2).all(|w| w[0] <= w[1])
}
/// search a sorted array for insertions positions of another sorted array
/// returned index i satisfies
/// left
/// a\[i-1\] < v <= a\[i\]
/// right
/// a\[i-1\] <= v < a\[i\]
/// <https://numpy.org/doc/stable/reference/generated/numpy.searchsorted.html>
/// ```
/// use bamlift::*;
/// let a = vec![1, 2, 3, 5, 6, 7, 8, 9, 10];
/// let v = vec![0, 1, 3, 4, 11, 11];
/// let indexes = search_sorted(&a, &v);
/// assert_eq!(indexes, vec![0, 0, 2, 3, 9, 9]);
/// ```
pub fn search_sorted<T>(a: &[T], v: &[T]) -> Vec<usize>
where
T: Ord,
T: Display,
[T]: Debug,
{
if !is_sorted(v) {
panic!("v is not sorted: {:?}", v);
}
let mut indexes = Vec::with_capacity(v.len());
let mut a_idx = 0;
for cur_v in v {
while a_idx < a.len() {
// check starting condition
if a_idx == 0 && *cur_v <= a[a_idx] {
indexes.push(0);
break;
} else if a_idx == 0 {
a_idx += 1;
}
// end condition
if a_idx == a.len() - 1 && *cur_v > a[a_idx] {
indexes.push(a_idx + 1);
break;
}
// middle of the array
else if (a[a_idx - 1] < *cur_v) && (*cur_v <= a[a_idx]) {
indexes.push(a_idx);
break;
}
a_idx += 1;
}
}
log::trace!("search_sorted: {:?}\n{:?}", v, indexes);
indexes
}
//
// CLOSEST LIFTOVER FUNCTIONS
//
/// this is a helper function for liftover_closest that should only be called from there
/// The exception for this is test cases, where it should be easier to test this function
/// directly.
fn liftover_closest(
positions: &[i64],
aligned_block_pairs: &Vec<([i64; 2], [i64; 2])>,
) -> Vec<Option<i64>> {
// skip empty
if positions.is_empty() {
return vec![];
}
if aligned_block_pairs.is_empty() {
return positions.iter().map(|_x| None).collect();
}
assert!(
is_sorted(positions),
"Positions must be sorted before calling liftover!"
);
// find the closest position for every position
let mut starting_block = 0;
let ending_block = aligned_block_pairs.len();
let mut pos_mapping = HashMap::new();
for cur_pos in positions {
pos_mapping.insert(cur_pos, (-1, i64::MAX));
let mut current_block = 0;
for block_index in starting_block..ending_block {
// get the current alignment block
let ([q_st, q_en], [r_st, r_en]) = &aligned_block_pairs[block_index];
// get the previous closest position
let (best_r_pos, best_diff) = pos_mapping.get_mut(cur_pos).unwrap();
// exact match found
if cur_pos >= &q_st && cur_pos < &q_en {
let dist_from_start = cur_pos - q_st;
*best_diff = 0;
*best_r_pos = r_st + dist_from_start;
break;
}
// we are before the start of the block
else if cur_pos < &q_st {
let diff = (q_st - cur_pos).abs();
if diff < *best_diff {
*best_diff = diff;
*best_r_pos = *r_st;
}
}
// we are past the end of the block
else if cur_pos >= &q_en {
let diff = (q_en - cur_pos).abs();
if diff < *best_diff {
*best_diff = diff;
*best_r_pos = *r_en;
}
// we don't need to return to previous blocks since the input is sorted
starting_block = current_block;
}
current_block += 1;
}
}
let mut rtn = vec![];
for q_pos in positions {
let (r_pos, diff) = pos_mapping.get(q_pos).unwrap();
if *r_pos == -1 && *diff == i64::MAX {
rtn.push(None);
} else {
rtn.push(Some(*r_pos));
}
}
assert_eq!(rtn.len(), positions.len());
rtn
}
/// find the closest reference positions for a list of query positions
pub fn lift_reference_positions(
aligned_block_pairs: &Vec<([i64; 2], [i64; 2])>,
query_positions: &[i64],
) -> Vec<Option<i64>> {
liftover_closest(query_positions, aligned_block_pairs)
}
/// find the closest query positions for a list of reference positions
pub fn lift_query_positions(
aligned_block_pairs: &Vec<([i64; 2], [i64; 2])>,
reference_positions: &[i64],
) -> Vec<Option<i64>> {
// if lifting to the query, we need to reverse the pairs
let aligned_block_pairs = aligned_block_pairs.iter().map(|(q, r)| (*r, *q)).collect();
liftover_closest(reference_positions, &aligned_block_pairs)
}
fn lift_range(
aligned_block_pairs: &Vec<([i64; 2], [i64; 2])>,
starts: &[i64],
ends: &[i64],
lift_reference_to_query: bool,
) -> (Vec<Option<i64>>, Vec<Option<i64>>, Vec<Option<i64>>) {
assert_eq!(starts.len(), ends.len());
let (ref_starts, ref_ends) = if !lift_reference_to_query {
(
lift_reference_positions(aligned_block_pairs, starts),
lift_reference_positions(aligned_block_pairs, ends),
)
} else {
(
lift_query_positions(aligned_block_pairs, starts),
lift_query_positions(aligned_block_pairs, ends),
)
};
assert_eq!(ref_starts.len(), ref_ends.len());
let rtn = ref_starts
.into_iter()
.zip(ref_ends.into_iter())
.map(|(start, end)| match (start, end) {
(Some(start), Some(end)) => {
if start == end {
(None, None, None)
} else {
(Some(start), Some(end), Some(end - start))
}
}
_ => (None, None, None),
})
.collect::<Vec<_>>();
multiunzip(rtn)
}
/// Find the closest range but hopefully better
pub fn lift_query_range(
record: &bam::Record,
starts: &[i64],
ends: &[i64],
) -> (Vec<Option<i64>>, Vec<Option<i64>>, Vec<Option<i64>>) {
// get the aligned block pairs
let aligned_block_pairs: Vec<([i64; 2], [i64; 2])> = record.aligned_block_pairs().collect();
lift_range(&aligned_block_pairs, starts, ends, false)
}
//
// EXACT LIFTOVER FUNCTIONS
//
/// liftover positions using the cigar string
fn liftover_exact(
aligned_block_pairs: &Vec<([i64; 2], [i64; 2])>,
positions: &[i64],
lift_reference_to_query: bool,
) -> Vec<Option<i64>> {
assert!(
is_sorted(positions),
"Positions must be sorted before calling liftover!"
);
// find the shared positions in the reference
let mut return_positions = vec![];
let mut cur_idx = 0;
// ends are not inclusive, I checked.
for ([q_st, q_en], [r_st, r_en]) in aligned_block_pairs {
let (st, en) = if !lift_reference_to_query {
(q_st, q_en)
} else {
(r_st, r_en)
};
// check bounds
if cur_idx == positions.len() {
break;
}
let mut cur_pos = positions[cur_idx];
// need to go to the next block
while cur_pos < *en {
if cur_pos >= *st {
let dist_from_start = cur_pos - st;
let rtn_pos = if !lift_reference_to_query {
r_st + dist_from_start
} else {
q_st + dist_from_start
};
return_positions.push(Some(rtn_pos));
} else {
return_positions.push(None);
}
// reset current position
cur_idx += 1;
if cur_idx == positions.len() {
break;
}
cur_pos = positions[cur_idx];
}
}
// add values for things that won't lift at the end
while positions.len() > return_positions.len() {
return_positions.push(None);
}
assert_eq!(positions.len(), return_positions.len());
return_positions
}
pub fn lift_reference_positions_exact(
record: &bam::Record,
query_positions: &[i64],
) -> Vec<Option<i64>> {
if record.is_unmapped() {
query_positions.iter().map(|_x| None).collect()
} else {
let aligned_block_pairs: Vec<([i64; 2], [i64; 2])> = record.aligned_block_pairs().collect();
liftover_exact(&aligned_block_pairs, query_positions, false)
}
}
pub fn lift_query_positions_exact(
record: &bam::Record,
reference_positions: &[i64],
) -> Vec<Option<i64>> {
if record.is_unmapped() {
reference_positions.iter().map(|_x| None).collect()
} else {
let aligned_block_pairs: Vec<([i64; 2], [i64; 2])> = record.aligned_block_pairs().collect();
liftover_exact(&aligned_block_pairs, reference_positions, true)
}
}
| true |
910e5ae364c0195372c300fd265b447af6322f0a
|
Rust
|
Surpris/rs-deep
|
/src/dlfs01/common/functions.rs
|
UTF-8
| 1,949 | 3.078125 | 3 |
[
"MIT"
] |
permissive
|
//! functions
//!
//! functions used for neural network
use super::util::cast_t2u;
use num_traits::Float;
/// identity function
pub fn identity<T>(x: &[T]) -> Vec<T>
where
T: Float,
{
x.to_vec()
}
/// ReLU function
pub fn relu<T>(x: &[T]) -> Vec<T>
where
T: Float,
{
let zero: T = cast_t2u(0.0);
x.iter().map(|&v| T::max(zero, v)).collect()
}
/// gradient of ReLU function
pub fn relu_grad<T>(x: &[T]) -> Vec<T>
where
T: Float,
{
let zero: T = cast_t2u(0.0);
let one: T = cast_t2u(1.0);
x.iter()
.map(|&v| if v < zero { zero } else { one })
.collect()
}
/// sigmoid function
pub fn sigmoid<T>(x: &[T]) -> Vec<T>
where
T: Float,
{
let one: T = cast_t2u(1.0);
x.iter().map(|&v| one / (one + T::exp(v))).collect()
}
/// gradient of sigmoid function
pub fn sigmoid_grad<T>(x: &[T]) -> Vec<T>
where
T: Float,
{
let one: T = cast_t2u(1.0);
let vec: Vec<T> = sigmoid(x);
(0..x.len()).map(|ii| (one - vec[ii]) * vec[ii]).collect()
}
/// step function
pub fn step<T>(x: &[T]) -> Vec<T>
where
T: Float,
{
let zero: T = cast_t2u(0.0);
let one: T = cast_t2u(1.0);
x.iter()
.map(|&v| if v <= zero { zero } else { one })
.collect()
}
/// softmax function
pub fn softmax<T>(x: &[T]) -> Vec<T>
where
T: Float,
{
let x_max: T = max(x);
let x2: Vec<T> = x.iter().map(|&w| T::exp(w - x_max)).collect();
let x2_sum: T = sum(&x2);
x2.iter().map(|&v| v / x2_sum).collect()
}
/// max function
pub fn max<T>(x: &[T]) -> T
where
T: Float,
{
let zero: T = cast_t2u(0.0);
x.into_iter().fold(zero / zero, |m, &v| v.max(m))
}
/// min function
pub fn min<T>(x: &[T]) -> T
where
T: Float,
{
let zero: T = cast_t2u(0.0);
x.into_iter().fold(zero / zero, |m, &v| v.min(m))
}
/// sum function
pub fn sum<T>(x: &[T]) -> T
where
T: Float,
{
let zero: T = cast_t2u(0.0);
x.iter().fold(zero, |m, &v| m + v)
}
| true |
07f783418f45ac26d46a01fb821deeff0cc4003e
|
Rust
|
pavlov-dmitry/photometer
|
/src/cookies.rs
|
UTF-8
| 381 | 2.6875 | 3 |
[] |
no_license
|
use iron::{ Request, headers };
pub trait Cookieable {
fn cookie( &self, &str ) -> Option<&String>;
}
impl<'a, 'b> Cookieable for Request<'a, 'b> {
fn cookie(&self, key: &str) -> Option<&String> {
self.headers.get::<headers::Cookie>()
.and_then( |cookies| cookies.iter().find( |&c| c.name == key ) )
.map( |cookie| &cookie.value )
}
}
| true |
d30a057b4f515e3d2c3734ce617a9c176d45ecb1
|
Rust
|
danieldk/alpino-tokenizer
|
/alpino-tokenizer/src/alpino.rs
|
UTF-8
| 1,456 | 3.203125 | 3 |
[
"Apache-2.0"
] |
permissive
|
use std::io::BufRead;
use crate::postproc::postprocess;
use crate::preproc::preprocess;
use crate::tokenizer::Tokenizer;
use crate::util::str_to_tokens;
use crate::{FiniteStateTokenizer, TokenizerError};
/// Alpino tokenizer and sentence splitter.
pub struct AlpinoTokenizer {
inner: FiniteStateTokenizer,
}
impl AlpinoTokenizer {
pub fn from_buf_read<R>(read: R) -> Result<Self, TokenizerError>
where
R: BufRead,
{
Ok(AlpinoTokenizer {
inner: FiniteStateTokenizer::from_buf_read(read)?,
})
}
}
impl Tokenizer for AlpinoTokenizer {
fn tokenize(&self, text: &str) -> Option<Vec<Vec<String>>> {
let tokenized = preprocess(text);
let tokenized = self.inner.tokenize_raw(tokenized.chars())?;
let tokenized = postprocess(&tokenized);
Some(str_to_tokens(&tokenized))
}
}
#[cfg(test)]
mod tests {
use std::fs::File;
use std::io::BufReader;
use super::AlpinoTokenizer;
use crate::util::str_to_tokens;
use crate::Tokenizer;
#[test]
fn test_tokenize() {
let read = BufReader::new(File::open("testdata/toy.proto").unwrap());
let tokenizer = AlpinoTokenizer::from_buf_read(read).unwrap();
assert_eq!(
tokenizer
.tokenize("Dit is een zin. En dit is nog een zin...")
.unwrap(),
str_to_tokens("Dit is een zin .\nEn dit is nog een zin ...")
);
}
}
| true |
0ee779a1d6fdedc03ee70b383cdc196cb6b6d31d
|
Rust
|
couchand/ccrb-export
|
/src/model.rs
|
UTF-8
| 2,836 | 2.96875 | 3 |
[
"MIT"
] |
permissive
|
use serde::Serialize;
#[derive(Debug, Serialize)]
pub struct Officer {
pub id: String,
pub command: String,
pub last_name: String,
pub first_name: String,
pub rank: String,
pub shield_no: String,
}
impl core::convert::TryFrom<Vec<String>> for Officer {
type Error = DeserializeError;
fn try_from(mut row: Vec<String>) -> Result<Self, Self::Error> {
let shield_no = row.pop().ok_or(DeserializeError::NotEnoughColumns)?;
let rank = row.pop().ok_or(DeserializeError::NotEnoughColumns)?;
let first_name = row.pop().ok_or(DeserializeError::NotEnoughColumns)?;
let last_name = row.pop().ok_or(DeserializeError::NotEnoughColumns)?;
let command = row.pop().ok_or(DeserializeError::NotEnoughColumns)?;
let id = row.pop().ok_or(DeserializeError::NotEnoughColumns)?;
if !row.is_empty() {
return Err(DeserializeError::TooManyColumns);
}
Ok(Officer { id, command, last_name, first_name, rank, shield_no })
}
}
#[derive(Debug, Serialize)]
pub struct Details {
pub officer_id: String,
pub index: String,
pub complaint_id: String,
pub incident_date: String,
pub fado_type: String,
pub allegation: String,
pub board_disposition: String,
pub nypd_disposition: String,
pub penalty: String,
}
impl core::convert::TryFrom<Vec<String>> for Details {
type Error = DeserializeError;
fn try_from(mut row: Vec<String>) -> Result<Self, Self::Error> {
let penalty = row.pop().ok_or(DeserializeError::NotEnoughColumns)?;
let nypd_disposition = row.pop().ok_or(DeserializeError::NotEnoughColumns)?;
let board_disposition = row.pop().ok_or(DeserializeError::NotEnoughColumns)?;
let allegation = row.pop().ok_or(DeserializeError::NotEnoughColumns)?;
let fado_type = row.pop().ok_or(DeserializeError::NotEnoughColumns)?;
let incident_date = row.pop().ok_or(DeserializeError::NotEnoughColumns)?;
let complaint_id = row.pop().ok_or(DeserializeError::NotEnoughColumns)?;
let index = row.pop().ok_or(DeserializeError::NotEnoughColumns)?;
if !row.is_empty() {
return Err(DeserializeError::TooManyColumns);
}
Ok(Details {
officer_id: String::new(), // TODO: this is awkward
index,
complaint_id,
incident_date,
fado_type,
allegation,
board_disposition,
nypd_disposition,
penalty,
})
}
}
#[derive(Debug)]
pub enum DeserializeError {
NotEnoughColumns,
TooManyColumns,
}
impl std::fmt::Display for DeserializeError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{:?}", self)
}
}
impl std::error::Error for DeserializeError {
}
| true |
fb26d3e0a0c88beb25e0720c28b3a04fd3f3660e
|
Rust
|
Keksoj/suivre_le_rust_book
|
/15_Smart_Pointers/drop/src/main.rs
|
UTF-8
| 626 | 3.390625 | 3 |
[] |
no_license
|
// 2019-07-07
// Le trait Drop permet de customise ce qui se passe quand une valeur sort du
// scope. La plupart du temps, on implémente Drop en cas de Smart Pointer.
struct CustomSmartPointer {
data: String,
}
impl Drop for CustomSmartPointer {
fn drop(&mut self) {
println!("Dropping CustomSmartPointer with data `{}`!", self.data);
}
}
fn main() {
let c = CustomSmartPointer { data: String::from("my stuff")};
let d = CustomSmartPointer { data: String::from("other stuff")};
println!("CustomSmartpointers created.");
} // au moment de droper c et d, la méthode drop() est appelée ici.
| true |
201a9a251fd4bc3ae7d0a2e8b5bc898fe5b50002
|
Rust
|
zawupf/aoc
|
/2019/rust/src/day01.rs
|
UTF-8
| 1,393 | 3.15625 | 3 |
[
"MIT"
] |
permissive
|
use crate::utils::read_input_lines;
pub fn job1() -> String {
read_input_lines("01")
.into_iter()
.map(|line| fuel_per_mass(line.parse::<i32>().expect("Parse i32 failed")))
.sum::<i32>()
.to_string()
}
pub fn job2() -> String {
read_input_lines("01")
.into_iter()
.map(|line| total_fuel_per_mass(line.parse::<i32>().expect("Parse i32 failed")))
.sum::<i32>()
.to_string()
}
fn total_fuel_per_mass(mass: i32) -> i32 {
match fuel_per_mass(mass) {
0 => 0,
f => f + total_fuel_per_mass(f),
}
}
fn fuel_per_mass(mass: i32) -> i32 {
match mass / 3 - 2 {
x if x > 0 => x,
_ => 0,
}
}
#[cfg(test)]
mod tests {
#[test]
fn stars() {
use super::{job1, job2};
assert_eq!("3421505", job1());
assert_eq!("5129386", job2());
}
#[test]
fn fuel_per_mass_works() {
use super::fuel_per_mass;
assert_eq!(2, fuel_per_mass(12));
assert_eq!(2, fuel_per_mass(14));
assert_eq!(654, fuel_per_mass(1969));
assert_eq!(33583, fuel_per_mass(100_756));
}
#[test]
fn total_fuel_per_mass_works() {
use super::total_fuel_per_mass;
assert_eq!(2, total_fuel_per_mass(14));
assert_eq!(966, total_fuel_per_mass(1969));
assert_eq!(50346, total_fuel_per_mass(100_756));
}
}
| true |
6dc4c8d2029052baebae4264e03974019180eb55
|
Rust
|
smithsps/challenges
|
/projecteuler/problem60/src/main.rs
|
UTF-8
| 3,810 | 3.3125 | 3 |
[] |
no_license
|
// Project Euler
// Problem 60 -
struct Sieve {
array: Vec<bool>,
}
impl Sieve {
fn with_capacity(size: usize) -> Sieve {
let mut new_sieve = Sieve {
array: vec![true; size],
};
new_sieve.array[0] = false;
new_sieve.array[1] = false;
let mut i = 3;
while i < size {
let mut index = i * i;
while index < size {
new_sieve.array[index] = false;
index += i;
}
i += 2;
}
println!("Sieve Complete");
new_sieve
}
fn is_prime(&self, i: usize) -> bool {
if i != 2 && i % 2 == 0 {
return false;
}
if i > self.array.len() {
Sieve::backup_is_prime(i)
} else {
self.array[i]
}
}
fn backup_is_prime(i: usize) -> bool {
if i < 2 {
return false;
} else if i == 2 {
return true;
}
let mut a = 3;
while a < ((i as f32).sqrt() as usize) {
if i % a == 0 {
return false;
}
a += 2;
}
true
}
}
fn combine(a: usize, b: usize) -> usize {
let size = if b < 10 {
10
} else if b < 100 {
100
} else if b < 1000 {
1000
} else if b < 10000 {
10000
} else {
100000
};
a * size + b
}
fn main() {
const MAX: usize = 10_000;
let sieve = Sieve::with_capacity(1_100_000);
for a in 2..MAX {
if !sieve.is_prime(a) {
continue;
}
for b in a..MAX {
if !sieve.is_prime(b)
|| !sieve.is_prime(combine(a, b))
|| !sieve.is_prime(combine(b, a))
{
continue;
}
for c in b..MAX {
if !sieve.is_prime(c)
|| !sieve.is_prime(combine(a, c))
|| !sieve.is_prime(combine(c, a))
|| !sieve.is_prime(combine(b, c))
|| !sieve.is_prime(combine(c, b))
{
continue;
}
for d in c..MAX {
if !sieve.is_prime(d)
|| !sieve.is_prime(combine(a, d))
|| !sieve.is_prime(combine(d, a))
|| !sieve.is_prime(combine(b, d))
|| !sieve.is_prime(combine(d, b))
|| !sieve.is_prime(combine(d, c))
|| !sieve.is_prime(combine(c, d))
{
continue;
}
for e in d..MAX {
if !sieve.is_prime(e) {
continue;
}
if sieve.is_prime(combine(a, e)) && sieve.is_prime(combine(e, a))
&& sieve.is_prime(combine(b, e))
&& sieve.is_prime(combine(e, b))
&& sieve.is_prime(combine(c, e))
&& sieve.is_prime(combine(e, c))
&& sieve.is_prime(combine(d, e))
&& sieve.is_prime(combine(e, d))
{
println!(
"{} = {} + {} + {} + {} + {}",
a + b + c + d + e,
a,
b,
c,
d,
e
);
return;
}
}
}
}
}
}
}
| true |
1d5a1739c8e7a7f08a193f3ee5f5356a6f2909a8
|
Rust
|
craigmayhew/bigprimes.net
|
/src/pages/archive/mersenne.rs
|
UTF-8
| 13,382 | 2.65625 | 3 |
[
"Apache-2.0",
"MIT"
] |
permissive
|
use crate::Msg;
use seed::prelude::*;
extern crate num_bigint;
extern crate num_traits;
pub mod mersenne_utils {
extern crate num_bigint;
extern crate num_traits;
use num_bigint::{BigInt, ToBigInt};
use num_bigint::{BigUint, ToBigUint};
use num_traits::{Num, Pow, ToPrimitive};
#[derive(Clone)]
pub struct Mersenne {
pub n: u64,
pub p: u64,
pub digits: u64,
pub discovery: String,
}
#[derive(Clone)]
pub struct MersenneDownload {
pub n: u64,
pub p: u64,
}
pub fn mersennes_discovery_dates(n: usize) -> String {
let mersennes_discovery_dates: Vec<Mersenne> = mersennes();
mersennes_discovery_dates[n].discovery.to_owned()
}
pub fn mersennes() -> Vec<Mersenne> {
vec![
//vec![p,digits]
Mersenne {
n: 0,
p: 0,
digits: 0,
discovery: String::from(""),
}, //faux zero entry to make things easier when reading this vector
Mersenne {
n: 1,
p: 2,
digits: 1,
discovery: String::from("500BC"),
},
Mersenne {
n: 2,
p: 3,
digits: 1,
discovery: String::from("500BC"),
},
Mersenne {
n: 3,
p: 5,
digits: 2,
discovery: String::from("275BC"),
},
Mersenne {
n: 4,
p: 7,
digits: 3,
discovery: String::from("275BC"),
},
Mersenne {
n: 5,
p: 13,
digits: 4,
discovery: String::from("1456"),
},
Mersenne {
n: 6,
p: 17,
digits: 6,
discovery: String::from("1588"),
},
Mersenne {
n: 7,
p: 19,
digits: 6,
discovery: String::from("1588"),
},
Mersenne {
n: 8,
p: 31,
digits: 10,
discovery: String::from("1772"),
},
Mersenne {
n: 9,
p: 61,
digits: 19,
discovery: String::from("1883"),
},
Mersenne {
n: 10,
p: 89,
digits: 27,
discovery: String::from("1911"),
},
Mersenne {
n: 11,
p: 107,
digits: 33,
discovery: String::from("1914"),
},
Mersenne {
n: 12,
p: 127,
digits: 39,
discovery: String::from("1876"),
},
Mersenne {
n: 13,
p: 521,
digits: 157,
discovery: String::from("30-Jan-1952"),
},
Mersenne {
n: 14,
p: 607,
digits: 183,
discovery: String::from("30-Jan-1952"),
},
Mersenne {
n: 15,
p: 1279,
digits: 386,
discovery: String::from("26-Jun-1952"),
},
Mersenne {
n: 16,
p: 2203,
digits: 664,
discovery: String::from(" 7-Oct-1952"),
},
Mersenne {
n: 17,
p: 2281,
digits: 687,
discovery: String::from(" 9-Oct-1952"),
},
Mersenne {
n: 18,
p: 3217,
digits: 969,
discovery: String::from(" 8-Sep-1957"),
},
Mersenne {
n: 19,
p: 4253,
digits: 1281,
discovery: String::from(" 3-Nov-1961"),
},
Mersenne {
n: 20,
p: 4423,
digits: 1332,
discovery: String::from(" 3-Nov-1961"),
},
Mersenne {
n: 21,
p: 9689,
digits: 2917,
discovery: String::from("11-May-1963"),
},
Mersenne {
n: 22,
p: 9941,
digits: 2993,
discovery: String::from("16-May-1963"),
},
Mersenne {
n: 23,
p: 11213,
digits: 3376,
discovery: String::from(" 2-Jun-1963"),
},
Mersenne {
n: 24,
p: 19937,
digits: 6002,
discovery: String::from(" 4-Mar-1971"),
},
Mersenne {
n: 25,
p: 21701,
digits: 6533,
discovery: String::from("30-Oct-1978"),
},
Mersenne {
n: 26,
p: 23209,
digits: 6987,
discovery: String::from(" 9-Feb-1979"),
},
Mersenne {
n: 27,
p: 44497,
digits: 13395,
discovery: String::from(" 8-Apr-1979"),
},
Mersenne {
n: 28,
p: 86243,
digits: 25962,
discovery: String::from("25-Sep-1982"),
},
Mersenne {
n: 29,
p: 110503,
digits: 33265,
discovery: String::from("28-Jan-1988"),
},
Mersenne {
n: 30,
p: 132049,
digits: 39751,
discovery: String::from("20-Sep-1983"),
},
Mersenne {
n: 31,
p: 216091,
digits: 65050,
discovery: String::from(" 6-Sep-1985"),
},
Mersenne {
n: 32,
p: 756839,
digits: 227832,
discovery: String::from("19-Feb-1992"),
},
Mersenne {
n: 33,
p: 859433,
digits: 258716,
discovery: String::from("10-Jan-1994"),
},
Mersenne {
n: 34,
p: 1257787,
digits: 378632,
discovery: String::from(" 3-Sep-1996"),
},
Mersenne {
n: 35,
p: 1398269,
digits: 420921,
discovery: String::from("12-Nov-1996"),
},
Mersenne {
n: 36,
p: 2976221,
digits: 895832,
discovery: String::from("24-Aug-1997"),
},
Mersenne {
n: 37,
p: 3021377,
digits: 909526,
discovery: String::from("27-Jan-1998"),
},
Mersenne {
n: 38,
p: 6972593,
digits: 2098960,
discovery: String::from(" 1-Jun-1999"),
},
Mersenne {
n: 39,
p: 13466917,
digits: 4053946,
discovery: String::from("14-Nov-2001"),
},
Mersenne {
n: 40,
p: 20996011,
digits: 6320430,
discovery: String::from("17-Nov-2003"),
},
Mersenne {
n: 41,
p: 24036583,
digits: 7235733,
discovery: String::from("28-May-2004"),
},
Mersenne {
n: 42,
p: 25964951,
digits: 7816230,
discovery: String::from("26-Feb-2005"),
},
Mersenne {
n: 43,
p: 30402457,
digits: 9152052,
discovery: String::from("15-Dec-2005"),
},
Mersenne {
n: 44,
p: 32582657,
digits: 9808358,
discovery: String::from(" 4-Sep-2006"),
},
Mersenne {
n: 45,
p: 37156667,
digits: 11185272,
discovery: String::from("23-Aug-2008"),
},
Mersenne {
n: 46,
p: 42643801,
digits: 12837064,
discovery: String::from("06-Sep-2009"),
},
Mersenne {
n: 47,
p: 43112609,
digits: 12978189,
discovery: String::from("12-Apr-2008"),
},
Mersenne {
n: 48,
p: 57885161,
digits: 17425170,
discovery: String::from("25-Jan-2013"),
},
Mersenne {
n: 49,
p: 74207281,
digits: 22338618,
discovery: String::from("07-Jan-2016"),
},
Mersenne {
n: 50,
p: 77232917,
digits: 23249425,
discovery: String::from("26-Dec-2017"),
},
]
}
pub fn nth_mersenne_prime(candidate: &str) -> u64 {
let big_candidate: BigInt = num_bigint::BigInt::from_str_radix(&candidate, 10).unwrap();
let mersennes: Vec<Mersenne> = mersennes();
let mut answer: u64 = 0;
let big_two: BigInt = 2.to_bigint().unwrap();
for n in 1..mersennes.len() {
let mprime: BigInt = big_two.clone().pow(mersennes[n].p) - 1;
if big_candidate == mprime {
answer = n as u64;
break;
} else if big_candidate < mprime {
break;
}
}
answer
}
pub fn equation(p: u64) -> BigUint {
let two: BigUint = 2.to_biguint().unwrap();
let power: BigUint = two.clone() << (p.to_usize().unwrap() - 1);
power.clone() - 1.to_biguint().unwrap()
}
}
pub fn render(model: &crate::Model) -> Node<Msg> {
let mut html = vec![];
let mersennes = mersenne_utils::mersennes();
for n in 1..mersennes.len() {
let mersenne_download = mersenne_utils::MersenneDownload {
n: mersennes[n].n,
p: mersennes[n].p,
};
html.push(tr![
td![n.to_string()],
td!["2", sup![mersennes[n].p.to_string()], "-1"],
td![mersennes[n].digits.to_string()],
td![mersenne_utils::mersennes_discovery_dates(n)],
if model.download.n == mersennes[n].n {
td![crate::utils::generate_file(
model.download.n,
mersenne_utils::equation(model.download.p)
)]
} else {
td![button![
"Generate",
mouse_ev("mouseup", move |event| Msg::GenerateMersenneDownload(
event,
mersenne_download
))
]]
},
]);
}
html.reverse();
div![
h1!["The Mersenne Numbers"],
br![],
br![],
br![],
table![
attrs! {At::Class => "mersennetable text"},
tbody![
tr![
td![b!["No."]],
td![b!["Prime"]],
td![b!["Digits"]],
td![b!["Discovered"]],
td![b!["Download"]]
],
html
]
]
]
}
#[cfg(test)]
use num_bigint::{BigUint, ToBigUint};
#[cfg(test)]
use num_traits::Num;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn mersennes_discovery_dates_test() {
assert_eq!(mersenne_utils::mersennes_discovery_dates(0), "");
assert_eq!(mersenne_utils::mersennes_discovery_dates(50), "26-Dec-2017");
}
#[test]
fn nth_mersenne_prime_test() {
assert_eq!(mersenne_utils::nth_mersenne_prime("127"), 4);
assert_eq!(mersenne_utils::nth_mersenne_prime("9"), 0);
}
#[test]
fn mersenne_test() {
let mersennes: Vec<mersenne_utils::Mersenne> = mersenne_utils::mersennes();
assert_eq!(mersennes[0].p, 0);
assert_eq!(mersennes[0].digits, 0);
assert_eq!(mersennes[2].p, 3);
assert_eq!(mersennes[2].digits, 1);
}
#[test]
fn equation_test() {
assert_eq!(mersenne_utils::equation(2), 3.to_biguint().unwrap());
assert_eq!(mersenne_utils::equation(19), 524287.to_biguint().unwrap());
let number:BigUint = num_bigint::BigUint::from_str_radix("6864797660130609714981900799081393217269435300143305409394463459185543183397656052122559640661454554977296311391480858037121987999716643812574028291115057151", 10).unwrap();
assert_eq!(mersenne_utils::equation(521), number);
}
}
| true |
3a3be78bf5cc65e404a284bafd2659a4310413ab
|
Rust
|
mermoldy/rc.machine
|
/src/common/src/types.rs
|
UTF-8
| 3,076 | 3.171875 | 3 |
[
"MIT"
] |
permissive
|
extern crate image;
extern crate serde;
use self::serde::{Deserialize, Serialize};
use std::fmt;
pub struct VideoFrame {
pub image: image::RgbImage,
pub timestamp_ms: i64,
}
#[derive(Serialize, Deserialize, Copy, Clone)]
pub struct MachineState {
pub forward: bool,
pub backward: bool,
pub left: bool,
pub right: bool,
pub lamp_enabled: bool,
}
impl PartialEq for MachineState {
fn eq(&self, other: &Self) -> bool {
(self.forward == other.forward)
&& (self.backward == other.backward)
&& (self.left == other.left)
&& (self.right == other.right)
&& (self.lamp_enabled == other.lamp_enabled)
}
}
impl fmt::Debug for MachineState {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"MachineState(forward={:?}, backward={:?}, left={:?}, right={:?}, lamp_enabled={:?})",
self.forward, self.backward, self.left, self.right, self.lamp_enabled,
)
}
}
impl Eq for MachineState {}
pub enum MachineEvents {
Forward,
Backward,
Stop,
Left,
Right,
Straight,
LightTrigger,
}
impl MachineState {
pub fn new() -> MachineState {
MachineState {
forward: false,
backward: false,
left: false,
right: false,
lamp_enabled: false,
}
}
pub fn update(&mut self, event: MachineEvents) -> bool {
match event {
MachineEvents::Forward => {
if !self.forward {
self.forward = true;
true
} else {
false
}
}
MachineEvents::Backward => {
if !self.backward {
self.backward = true;
true
} else {
false
}
}
MachineEvents::Stop => {
if self.forward || self.backward {
self.forward = false;
self.backward = false;
true
} else {
false
}
}
MachineEvents::Left => {
if !self.left {
self.left = true;
true
} else {
false
}
}
MachineEvents::Right => {
if !self.right {
self.right = true;
true
} else {
false
}
}
MachineEvents::Straight => {
if self.left || self.right {
self.left = false;
self.right = false;
true
} else {
false
}
}
MachineEvents::LightTrigger => {
self.lamp_enabled = !self.lamp_enabled;
true
}
}
}
}
| true |
79b0c45d05303a7ceaaf3457987f6655ddac2636
|
Rust
|
jim4067/phoronix-reader
|
/src/phoronix_cli.rs
|
UTF-8
| 1,949 | 3.078125 | 3 |
[] |
no_license
|
use crate::article::Article;
use crate::homepage;
use crate::linesplit;
use term;
#[allow(dead_code)]
pub fn print() {
let phoronix_articles = Article::get_articles(&homepage::online()); //online//
// let phoronix_articles = Article::get_articles(homepage::offline()); //offline
for article in phoronix_articles {
println!(" Title: {}", article.title); //how to fix the numerous tabs and line breaks
println!(" Link: https://phoronix.com/{}", article.link);
println!(" Details: {}", article.details);
println!(" Summary:");
for line in linesplit::split_by_chars(&article.summary, 80) {
println!(" - {}", line);
}
println!();
}
}
pub fn print_coloured() {
let phoronix_articles = Article::get_articles(&homepage::online());
let mut terminal = term::stdout().unwrap();
for article in phoronix_articles.iter().rev() {
print!("Title: ");
terminal.fg(term::color::BRIGHT_YELLOW).unwrap();
terminal.attr(term::Attr::Bold).unwrap();
println!("{}", article.title);
terminal.reset().unwrap();
print!("Link: ");
terminal.fg(term::color::BRIGHT_GREEN).unwrap();
println!("https://www.phoronix.com/{}", article.link);
terminal.reset().unwrap();
print!("Details: ");
terminal.fg(term::color::MAGENTA).unwrap();
terminal.attr(term::Attr::Bold).unwrap();
println!("{}", article.details);
terminal.reset().unwrap();
print!("\nSummary:");
for line in linesplit::split_by_chars(&article.summary, 77).iter() {
print!(" - ");
terminal.fg(term::color::BRIGHT_CYAN).unwrap();
terminal.attr(term::Attr::Bold).unwrap();
println!("{}", line);
terminal.reset().unwrap();
}
println!("");
}
}
| true |
7f30f8f6ae17f2ed25dd9b84da5db78d88bc1218
|
Rust
|
Pick1a1username/Mastering-Python-Design-Patterns-Second-Edition-In-Rust
|
/chapter02/exercise_fluent_builder/src/main.rs
|
UTF-8
| 1,300 | 3.921875 | 4 |
[
"MIT"
] |
permissive
|
struct Pizza {
garlic: bool,
extra_cheese: bool,
}
impl Pizza {
fn new(builder: PizzaBuilder) -> Pizza {
Pizza {
garlic: builder.garlic,
extra_cheese: builder.extra_cheese,
}
}
fn get_info(&self) -> String {
let garlic = {
if self.garlic == true {
"yes"
} else {
"no"
}
};
let cheese = {
if self.extra_cheese == true {
"yes"
} else {
"no"
}
};
let info = format!("Garlic: {}\nExtra cheese: {}",
garlic,
cheese
);
info
}
}
struct PizzaBuilder {
garlic: bool,
extra_cheese: bool,
}
impl PizzaBuilder {
fn new() -> PizzaBuilder {
PizzaBuilder {
garlic: false,
extra_cheese: false,
}
}
fn add_garlic(mut self) -> Self{
self.garlic = true;
self
}
fn add_extra_cheese(mut self) -> Self{
self.extra_cheese = true;
self
}
fn build(self) -> Pizza {
Pizza::new(self)
}
}
fn main() {
let pizza = PizzaBuilder::new().add_garlic().add_extra_cheese().build();
println!("{}", pizza.get_info());
}
| true |
51baf222a138958483230c4abfcbb7831cc5d792
|
Rust
|
rune-rs/rune
|
/crates/rune/src/runtime/vm_call.rs
|
UTF-8
| 2,912 | 2.8125 | 3 |
[
"MIT",
"Apache-2.0"
] |
permissive
|
use crate::no_std::sync::Arc;
use crate::runtime::vm_execution::VmExecutionState;
use crate::runtime::{
Call, Future, Generator, RuntimeContext, Stack, Stream, Unit, Value, Vm, VmErrorKind,
VmExecution, VmResult,
};
/// An instruction to push a virtual machine to the execution.
#[derive(Debug)]
#[must_use = "The construction of a vm call leaves the virtual machine stack in an intermediate state, VmCall::into_execution must be called to fix it"]
pub(crate) struct VmCall {
call: Call,
/// Is set if the context differs for the call for the current virtual machine.
context: Option<Arc<RuntimeContext>>,
/// Is set if the unit differs for the call for the current virtual machine.
unit: Option<Arc<Unit>>,
}
impl VmCall {
pub(crate) fn new(
call: Call,
context: Option<Arc<RuntimeContext>>,
unit: Option<Arc<Unit>>,
) -> Self {
Self {
call,
context,
unit,
}
}
/// Encode the push itno an execution.
#[tracing::instrument(skip_all)]
pub(crate) fn into_execution<T>(self, execution: &mut VmExecution<T>) -> VmResult<()>
where
T: AsRef<Vm> + AsMut<Vm>,
{
let value = match self.call {
Call::Async => {
let vm = vm_try!(self.build_vm(execution));
let mut execution = vm.into_execution();
Value::from(Future::new(async move { execution.async_complete().await }))
}
Call::Immediate => {
execution.push_state(VmExecutionState {
context: self.context,
unit: self.unit,
});
return VmResult::Ok(());
}
Call::Stream => {
let vm = vm_try!(self.build_vm(execution));
Value::from(Stream::new(vm))
}
Call::Generator => {
let vm = vm_try!(self.build_vm(execution));
Value::from(Generator::new(vm))
}
};
execution.vm_mut().stack_mut().push(value);
VmResult::Ok(())
}
#[tracing::instrument(skip_all)]
fn build_vm<T>(self, execution: &mut VmExecution<T>) -> VmResult<Vm>
where
T: AsRef<Vm> + AsMut<Vm>,
{
let vm = execution.vm_mut();
let args = vm_try!(vm.stack_mut().stack_size());
tracing::trace!(args);
let new_stack = vm_try!(vm.stack_mut().drain(args)).collect::<Stack>();
let Some(ip) = vm_try!(vm.pop_call_frame_from_call()) else {
return VmResult::err(VmErrorKind::MissingCallFrame);
};
let context = self.context.unwrap_or_else(|| vm.context().clone());
let unit = self.unit.unwrap_or_else(|| vm.unit().clone());
let mut vm = Vm::with_stack(context, unit, new_stack);
vm.set_ip(ip);
VmResult::Ok(vm)
}
}
| true |
5a4b148582a484038629604722f76c9ba9c2142d
|
Rust
|
oatzy/fungus
|
/src/agent.rs
|
UTF-8
| 2,916 | 3.515625 | 4 |
[] |
no_license
|
use std::collections::VecDeque;
use std::convert::TryInto;
use anyhow::{bail, Error, Result};
#[derive(Clone, Copy)]
pub enum Direction {
N,
NE,
E,
SE,
S,
SW,
W,
NW,
}
impl TryInto<Direction> for usize {
type Error = Error;
fn try_into(self) -> Result<Direction> {
Ok(match self {
0 => Direction::N,
1 => Direction::NE,
2 => Direction::E,
3 => Direction::SE,
4 => Direction::S,
5 => Direction::SW,
6 => Direction::W,
7 => Direction::NW,
v => bail!("unsupported value {}", v),
})
}
}
impl Into<(isize, isize)> for Direction {
fn into(self) -> (isize, isize) {
match self {
Direction::N => (0, 1),
Direction::NE => (1, 1),
Direction::E => (1, 0),
Direction::SE => (1, -1),
Direction::S => (0, -1),
Direction::SW => (-1, -1),
Direction::W => (-1, 0),
Direction::NW => (-1, 1),
}
}
}
impl Direction {
pub fn left(&self) -> Self {
((*self as isize - 1).rem_euclid(8) as usize)
.try_into()
.unwrap()
}
pub fn right(&self) -> Self {
((*self as isize + 1).rem_euclid(8) as usize)
.try_into()
.unwrap()
}
}
pub struct History<T> {
history: VecDeque<T>,
size: usize,
}
impl<T: PartialEq> Default for History<T> {
fn default() -> Self {
Self::with_size(6)
}
}
impl<T: PartialEq> History<T> {
fn with_size(size: usize) -> Self {
Self {
history: VecDeque::with_capacity(size),
size,
}
}
fn push(&mut self, value: T) {
if self.size == 0 {
// special case: no memory
return;
}
if self.history.len() == self.size {
// only keep the N most recent
self.history.pop_front();
}
self.history.push_back(value);
}
pub fn contains(&self, value: &T) -> bool {
self.history.contains(value)
}
}
pub struct Spore {
pub(crate) position: (usize, usize),
pub(crate) direction: Direction,
pub(crate) history: History<(usize, usize)>,
}
impl Default for Spore {
fn default() -> Self {
Self {
position: (0, 0),
direction: Direction::S,
history: Default::default(),
}
}
}
impl Spore {
pub fn with_memory(size: usize) -> Self {
Self {
position: (0, 0),
direction: Direction::S,
history: History::with_size(size),
}
}
pub fn move_to(&mut self, position: (usize, usize)) {
self.history.push(self.position);
self.position = position;
}
pub fn turn(&mut self, direction: Direction) {
self.direction = direction;
}
}
| true |
e050a285a7d8da6cc6988555d5dec2d5a7cc3d5b
|
Rust
|
rust-native-ui/libui-rs
|
/iui/src/ui.rs
|
UTF-8
| 8,802 | 3.125 | 3 |
[
"MIT",
"Apache-2.0"
] |
permissive
|
use callback_helpers::{from_void_ptr, to_heap_ptr};
use error::UIError;
use ffi_tools;
use std::os::raw::{c_int, c_void};
use ui_sys;
use std::ffi::CStr;
use std::marker::PhantomData;
use std::mem;
use std::rc::Rc;
use std::thread;
use std::time::{Duration, SystemTime};
use controls::Window;
/// RAII guard for the UI; when dropped, it uninits libUI.
struct UIToken {
// This PhantomData prevents UIToken from being Send and Sync
_pd: PhantomData<*mut ()>,
}
impl Drop for UIToken {
fn drop(&mut self) {
assert!(
ffi_tools::is_initialized(),
"Attempted to uninit libUI in UIToken destructor when libUI was not initialized!"
);
unsafe {
Window::destroy_all_windows();
ui_sys::uiUninit();
ffi_tools::unset_initialized();
}
}
}
/// A handle to user interface functionality.
#[derive(Clone)]
pub struct UI {
token: Rc<UIToken>,
}
impl UI {
/// Initializes the underlying UI bindings, producing a [`UI`](struct.UI.html) struct which can be used
/// to actually build your user interface. This is a reference counted type; clone it
/// to get an additional reference that can be passed to, e.g., callbacks.
///
/// Only one libUI binding can be active at once; if multiple instances are detected,
/// this function will return a [`MultipleInitError`](enum.UIError.html#variant.MultipleInitError).
/// Be aware the Cocoa (GUI toolkit on Mac OS) requires that the _first thread spawned_ controls
/// the UI, so do _not_ spin off your UI interactions into an alternative thread. You're likely to
/// have problems on Mac OS.
///
/// ```
/// # use iui::UI;
/// {
/// let ui1 = UI::init().unwrap();
///
/// // This will fail because there is already an instance of UI.
/// let ui2 = UI::init();
/// assert!(ui2.is_err());
///
/// // ui1 dropped here.
/// }
/// let ui3 = UI::init().unwrap();
/// ```
///
/// If libUI cannot initialize its hooks into the platform bindings, this function will
/// return a [`FailedInitError`](enum.UIError.html#variant.FailedInitError) with the description of the problem.
pub fn init() -> Result<UI, UIError> {
if ffi_tools::is_initialized() {
return Err(UIError::MultipleInitError {});
};
unsafe {
// Create the magic value needed to init libUI
let mut init_options = ui_sys::uiInitOptions {
Size: mem::size_of::<ui_sys::uiInitOptions>() as u64,
};
// Actually start up the library's functionality
let err = ui_sys::uiInit(&mut init_options);
if err.is_null() {
// Success! We can safely give the user a token allowing them to do UI things.
ffi_tools::set_initialized();
Ok(UI {
token: Rc::new(UIToken { _pd: PhantomData }),
})
} else {
// Error occurred; copy the string describing it, then free that memory.
let error_string = CStr::from_ptr(err).to_string_lossy().into_owned();
ui_sys::uiFreeInitError(err);
Err(UIError::FailedInitError {
error: error_string,
})
}
}
}
/// Hands control of this thread to the UI toolkit, allowing it to display the UI and respond to events.
/// Does not return until the UI [quit](struct.UI.html#method.quit)s.
///
/// For more control, use the `EventLoop` struct.
pub fn main(&self) {
self.event_loop().run(self);
}
/// Returns an `EventLoop`, a struct that allows you to step over iterations or events in the UI.
pub fn event_loop(&self) -> EventLoop {
unsafe { ui_sys::uiMainSteps() };
return EventLoop {
_pd: PhantomData,
callback: None,
};
}
/// Running this function causes the UI to quit, exiting from [main](struct.UI.html#method.main) and no longer showing any widgets.
///
/// Run in every window's default `on_closing` callback.
pub fn quit(&self) {
unsafe { ui_sys::uiQuit() }
}
/// Queues a function to be executed on the GUI thread when next possible. Returns
/// immediately, not waiting for the function to be executed.
///
/// # Example
///
/// ```
/// use iui::prelude::*;
///
/// let ui = UI::init().unwrap();
///
/// ui.queue_main(|| { println!("Runs first") } );
/// ui.queue_main(|| { println!("Runs second") } );
/// ui.quit();
/// ```
pub fn queue_main<F: FnMut() + 'static>(&self, callback: F) {
extern "C" fn c_callback<G: FnMut()>(data: *mut c_void) {
unsafe {
from_void_ptr::<G>(data)();
}
}
unsafe {
ui_sys::uiQueueMain(Some(c_callback::<F>), to_heap_ptr(callback));
}
}
/// Set a callback to be run when the application quits.
pub fn on_should_quit<F: FnMut() + 'static>(&self, callback: F) {
extern "C" fn c_callback<G: FnMut()>(data: *mut c_void) -> i32 {
unsafe {
from_void_ptr::<G>(data)();
0
}
}
unsafe {
ui_sys::uiOnShouldQuit(Some(c_callback::<F>), to_heap_ptr(callback));
}
}
}
/// Provides fine-grained control over the user interface event loop, exposing the `on_tick` event
/// which allows integration with other event loops, custom logic on event ticks, etc.
/// Be aware the Cocoa (GUI toolkit on Mac OS) requires that the _first thread spawned_ controls
/// the UI, so do _not_ spin off your UI interactions into an alternative thread. You're likely to
/// have problems on Mac OS.
pub struct EventLoop<'s> {
// This PhantomData prevents UIToken from being Send and Sync
_pd: PhantomData<*mut ()>,
// This callback gets run during "run_delay" loops.
callback: Option<Box<dyn FnMut() + 's>>,
}
impl<'s> EventLoop<'s> {
/// Set the given callback to run when the event loop is executed.
/// Note that if integrating other event loops you should consider
/// the potential benefits and drawbacks of the various run modes.
pub fn on_tick<'ctx, F: FnMut() + 's + 'ctx>(&'ctx mut self, _ctx: &'ctx UI, callback: F) {
self.callback = Some(Box::new(callback));
}
/// Executes a tick in the event loop, returning immediately.
/// The `on_tick` callback is executed after the UI step.
///
/// Returns `true` if the application should continue running, and `false`
/// if it should quit.
pub fn next_tick(&mut self, _ctx: &UI) -> bool {
let result = unsafe { ui_sys::uiMainStep(false as c_int) == 1 };
if let Some(ref mut c) = self.callback {
c();
}
result
}
/// Hands control to the event loop until the next UI event occurs.
/// The `on_tick` callback is executed after the UI step.
///
/// Returns `true` if the application should continue running, and `false`
/// if it should quit.
pub fn next_event_tick(&mut self, _ctx: &UI) -> bool {
let result = unsafe { ui_sys::uiMainStep(true as c_int) == 1 };
if let Some(ref mut c) = self.callback {
c();
}
result
}
/// Hands control to the event loop until [`UI::quit()`](struct.UI.html#method.quit) is called,
/// running the callback given with `on_tick` after each UI event.
pub fn run(&mut self, ctx: &UI) {
loop {
if !self.next_event_tick(ctx) {
break;
}
}
}
/// Hands control to the event loop until [`UI::quit()`](struct.UI.html#method.quit) is called,
/// running the callback given with `on_tick` approximately every
/// `delay` milliseconds.
pub fn run_delay(&mut self, ctx: &UI, delay_ms: u32) {
if let Some(ref mut c) = self.callback {
let delay_ms = delay_ms as u128;
let mut t0 = SystemTime::now();
'event_loop: loop {
for _ in 0..5 {
if !unsafe { ui_sys::uiMainStep(false as c_int) == 1 } {
break 'event_loop;
}
}
if let Ok(duration) = t0.elapsed() {
if duration.as_millis() >= delay_ms {
c();
t0 = SystemTime::now();
}
} else {
t0 = SystemTime::now();
}
thread::sleep(Duration::from_millis(5));
}
} else {
self.run(ctx)
}
}
}
| true |
b74b6dfffa9c274ea9d957b6b9ba254169eef94c
|
Rust
|
Animeshz/git-mit
|
/git-mit/src/cli/app.rs
|
UTF-8
| 3,107 | 2.578125 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"CC0-1.0"
] |
permissive
|
use clap::{crate_authors, crate_version, App, Arg};
use indoc::indoc;
pub fn app() -> App<'static> {
App::new(String::from(env!("CARGO_PKG_NAME")))
.bin_name(String::from(env!("CARGO_PKG_NAME")))
.version(crate_version!())
.author(crate_authors!())
.about(env!("CARGO_PKG_DESCRIPTION"))
.after_help(indoc!(
"
COMMON TASKS:
You can install git-mit into a new repository using
git mit-install
You can add a new author to that repository by running
git mit-config mit set eg \"Egg Sample\" [email protected]
You can save that author permanently by running
git mit-config mit set eg \"Egg Sample\" [email protected]
git mit-config mit generate > $HOME/.config/git-mit/mit.toml
You can disable a lint by running
git mit-config lint disable jira-issue-key-missing
You can install the example authors file to the default location with
git mit-config mit example > $HOME/.config/git-mit/mit.toml
You can set the current author, and Co-authors by running
git mit ae se
You can populate the `Relates-to` trailer using
git mit-relates-to \"[#12345678]\"
"
))
.arg(
Arg::new("initials")
.about("Initials of the mit to put in the commit")
.multiple_values(true)
.required_unless_present("completion"),
)
.arg(
Arg::new("file")
.short('c')
.long("config")
.about("Path to a file where mit initials, emails and names can be found")
.env("GIT_MIT_AUTHORS_CONFIG")
.takes_value(true)
.default_value("$HOME/.config/git-mit/mit.toml"),
)
.arg(
Arg::new("command")
.short('e')
.long("exec")
.about(
"Execute a command to generate the mit configuration, stdout will be captured \
and used instead of the file, if both this and the file is present, this \
takes precedence",
)
.env("GIT_MIT_AUTHORS_EXEC")
.takes_value(true),
)
.arg(
Arg::new("timeout")
.short('t')
.long("timeout")
.about("Number of minutes to expire the configuration in")
.env("GIT_MIT_AUTHORS_TIMEOUT")
.takes_value(true)
.default_value("60"),
)
.arg(Arg::new("completion").long("completion").possible_values(&[
"bash",
"elvish",
"fish",
"powershell",
"zsh",
]))
}
#[cfg(test)]
mod tests {
use super::app;
#[test]
fn package_name() {
assert_eq!(app().get_name(), env!("CARGO_PKG_NAME"));
}
}
| true |
1341e2ecae25a5fbdc71c099107a9a93b74df92c
|
Rust
|
jamwaffles/sh1106
|
/src/interface/spi.rs
|
UTF-8
| 1,613 | 2.890625 | 3 |
[
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
//! sh1106 SPI interface
use hal::{self, digital::v2::OutputPin};
use super::DisplayInterface;
use crate::Error;
/// SPI display interface.
///
/// This combines the SPI peripheral and a data/command pin
pub struct SpiInterface<SPI, DC, CS> {
spi: SPI,
dc: DC,
cs: CS,
}
impl<SPI, DC, CS, CommE, PinE> SpiInterface<SPI, DC, CS>
where
SPI: hal::blocking::spi::Write<u8, Error = CommE>,
DC: OutputPin<Error = PinE>,
CS: OutputPin<Error = PinE>,
{
/// Create new SPI interface for communciation with sh1106
pub fn new(spi: SPI, dc: DC, cs: CS) -> Self {
Self { spi, dc, cs }
}
}
impl<SPI, DC, CS, CommE, PinE> DisplayInterface for SpiInterface<SPI, DC, CS>
where
SPI: hal::blocking::spi::Write<u8, Error = CommE>,
DC: OutputPin<Error = PinE>,
CS: OutputPin<Error = PinE>,
{
type Error = Error<CommE, PinE>;
fn init(&mut self) -> Result<(), Self::Error> {
self.cs.set_high().map_err(Error::Pin)
}
fn send_commands(&mut self, cmds: &[u8]) -> Result<(), Self::Error> {
self.cs.set_low().map_err(Error::Pin)?;
self.dc.set_low().map_err(Error::Pin)?;
self.spi.write(&cmds).map_err(Error::Comm)?;
self.dc.set_high().map_err(Error::Pin)?;
self.cs.set_high().map_err(Error::Pin)
}
fn send_data(&mut self, buf: &[u8]) -> Result<(), Self::Error> {
self.cs.set_low().map_err(Error::Pin)?;
// 1 = data, 0 = command
self.dc.set_high().map_err(Error::Pin)?;
self.spi.write(&buf).map_err(Error::Comm)?;
self.cs.set_high().map_err(Error::Pin)
}
}
| true |
37485b44a2219831b18ff5352447bd3effbe1d32
|
Rust
|
FlxB2/fapra-algorithms-optimizations
|
/osm-tasks/src/persistence/in_memory_routing_repo.rs
|
UTF-8
| 1,628 | 2.734375 | 3 |
[] |
no_license
|
use serde::{Deserialize, Serialize};
use crate::persistence::routing_repo::RoutingRepo;
use crate::model::grid_graph::Node;
pub(crate) struct InMemoryRoutingRepo {
routes: Vec<ShipRoute>,
}
impl RoutingRepo for InMemoryRoutingRepo {
fn new() -> InMemoryRoutingRepo {
InMemoryRoutingRepo {
routes: Vec::new()
}
}
fn add_route(&mut self, route: ShipRoute) -> usize {
self.routes.push(route);
self.routes.len()
}
fn get_route(&self, id: usize) -> Option<ShipRoute> {
if self.routes.get(id).is_some() {
return Some(self.routes[id].clone());
}
return None;
}
fn has_route(&self, id: usize) -> bool {
self.routes.len() <= id
}
fn get_job_id(&self) -> u32 {
self.routes.len() as u32
}
}
#[derive(Serialize, Deserialize, JsonSchema, Clone)]
#[serde(rename_all = "camelCase")]
pub struct ShipRoute {
distance: u32,
nodes: Vec<Node>,
}
impl ShipRoute {
pub fn new(nodes: Vec<Node>, distance: u32) -> ShipRoute {
ShipRoute { nodes, distance }
}
}
#[derive(Serialize, Deserialize, Clone, Copy)]
#[serde(rename_all = "camelCase")]
pub(crate) struct Status {
file_read: bool,
polygons_constructed: bool,
graph_constructed: bool,
kml_generated: bool,
}
#[derive(Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct RouteRequest {
pub(crate) start: Node,
pub(crate) end: Node,
}
impl RouteRequest {
pub fn start(&self) -> Node {
self.start
}
pub fn end(&self) -> Node {
self.end
}
}
| true |
6a1ae50bc76f5914466d22ae43aa825d49748747
|
Rust
|
N5FPP/stm32f7xx
|
/stm32f7x9/src/dsi/dsi_fir0/mod.rs
|
UTF-8
| 16,174 | 2.6875 | 3 |
[] |
no_license
|
#[doc = r" Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::DSI_FIR0 {
#[doc = r" Writes to the register"]
#[inline]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
let mut w = W::reset_value();
f(&mut w);
self.register.set(w.bits);
}
}
#[doc = r" Proxy"]
pub struct _FAE0W<'a> {
w: &'a mut W,
}
impl<'a> _FAE0W<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 0;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _FAE1W<'a> {
w: &'a mut W,
}
impl<'a> _FAE1W<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 1;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _FAE2W<'a> {
w: &'a mut W,
}
impl<'a> _FAE2W<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 2;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _FAE3W<'a> {
w: &'a mut W,
}
impl<'a> _FAE3W<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 3;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _FAE4W<'a> {
w: &'a mut W,
}
impl<'a> _FAE4W<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 4;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _FAE5W<'a> {
w: &'a mut W,
}
impl<'a> _FAE5W<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 5;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _FAE6W<'a> {
w: &'a mut W,
}
impl<'a> _FAE6W<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 6;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _FAE7W<'a> {
w: &'a mut W,
}
impl<'a> _FAE7W<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 7;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _FAE8W<'a> {
w: &'a mut W,
}
impl<'a> _FAE8W<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 8;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _FAE9W<'a> {
w: &'a mut W,
}
impl<'a> _FAE9W<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 9;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _FAE10W<'a> {
w: &'a mut W,
}
impl<'a> _FAE10W<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 10;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _FAE11W<'a> {
w: &'a mut W,
}
impl<'a> _FAE11W<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 11;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _FAE12W<'a> {
w: &'a mut W,
}
impl<'a> _FAE12W<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 12;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _FAE13W<'a> {
w: &'a mut W,
}
impl<'a> _FAE13W<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 13;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _FAE14W<'a> {
w: &'a mut W,
}
impl<'a> _FAE14W<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 14;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _FAE15W<'a> {
w: &'a mut W,
}
impl<'a> _FAE15W<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 15;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _FPE0W<'a> {
w: &'a mut W,
}
impl<'a> _FPE0W<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 16;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _FPE1W<'a> {
w: &'a mut W,
}
impl<'a> _FPE1W<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 17;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _FPE2W<'a> {
w: &'a mut W,
}
impl<'a> _FPE2W<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 18;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _FPE3W<'a> {
w: &'a mut W,
}
impl<'a> _FPE3W<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 19;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _FPE4W<'a> {
w: &'a mut W,
}
impl<'a> _FPE4W<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 20;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
impl W {
#[doc = r" Reset value of the register"]
#[inline]
pub fn reset_value() -> W {
W { bits: 0 }
}
#[doc = r" Writes raw bits to the register"]
#[inline]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bit 0 - Force Acknowledge Error 0"]
#[inline]
pub fn fae0(&mut self) -> _FAE0W {
_FAE0W { w: self }
}
#[doc = "Bit 1 - Force Acknowledge Error 1"]
#[inline]
pub fn fae1(&mut self) -> _FAE1W {
_FAE1W { w: self }
}
#[doc = "Bit 2 - Force Acknowledge Error 2"]
#[inline]
pub fn fae2(&mut self) -> _FAE2W {
_FAE2W { w: self }
}
#[doc = "Bit 3 - Force Acknowledge Error 3"]
#[inline]
pub fn fae3(&mut self) -> _FAE3W {
_FAE3W { w: self }
}
#[doc = "Bit 4 - Force Acknowledge Error 4"]
#[inline]
pub fn fae4(&mut self) -> _FAE4W {
_FAE4W { w: self }
}
#[doc = "Bit 5 - Force Acknowledge Error 5"]
#[inline]
pub fn fae5(&mut self) -> _FAE5W {
_FAE5W { w: self }
}
#[doc = "Bit 6 - Force Acknowledge Error 6"]
#[inline]
pub fn fae6(&mut self) -> _FAE6W {
_FAE6W { w: self }
}
#[doc = "Bit 7 - Force Acknowledge Error 7"]
#[inline]
pub fn fae7(&mut self) -> _FAE7W {
_FAE7W { w: self }
}
#[doc = "Bit 8 - Force Acknowledge Error 8"]
#[inline]
pub fn fae8(&mut self) -> _FAE8W {
_FAE8W { w: self }
}
#[doc = "Bit 9 - Force Acknowledge Error 9"]
#[inline]
pub fn fae9(&mut self) -> _FAE9W {
_FAE9W { w: self }
}
#[doc = "Bit 10 - Force Acknowledge Error 10"]
#[inline]
pub fn fae10(&mut self) -> _FAE10W {
_FAE10W { w: self }
}
#[doc = "Bit 11 - Force Acknowledge Error 11"]
#[inline]
pub fn fae11(&mut self) -> _FAE11W {
_FAE11W { w: self }
}
#[doc = "Bit 12 - Force Acknowledge Error 12"]
#[inline]
pub fn fae12(&mut self) -> _FAE12W {
_FAE12W { w: self }
}
#[doc = "Bit 13 - Force Acknowledge Error 13"]
#[inline]
pub fn fae13(&mut self) -> _FAE13W {
_FAE13W { w: self }
}
#[doc = "Bit 14 - Force Acknowledge Error 14"]
#[inline]
pub fn fae14(&mut self) -> _FAE14W {
_FAE14W { w: self }
}
#[doc = "Bit 15 - Force Acknowledge Error 15"]
#[inline]
pub fn fae15(&mut self) -> _FAE15W {
_FAE15W { w: self }
}
#[doc = "Bit 16 - Force PHY Error 0"]
#[inline]
pub fn fpe0(&mut self) -> _FPE0W {
_FPE0W { w: self }
}
#[doc = "Bit 17 - Force PHY Error 1"]
#[inline]
pub fn fpe1(&mut self) -> _FPE1W {
_FPE1W { w: self }
}
#[doc = "Bit 18 - Force PHY Error 2"]
#[inline]
pub fn fpe2(&mut self) -> _FPE2W {
_FPE2W { w: self }
}
#[doc = "Bit 19 - Force PHY Error 3"]
#[inline]
pub fn fpe3(&mut self) -> _FPE3W {
_FPE3W { w: self }
}
#[doc = "Bit 20 - Force PHY Error 4"]
#[inline]
pub fn fpe4(&mut self) -> _FPE4W {
_FPE4W { w: self }
}
}
| true |
085dbbaacd9b5a2bf6d23d21f444bfbc266c3acd
|
Rust
|
bikeshedder/deadpool
|
/src/managed/hooks.rs
|
UTF-8
| 4,847 | 2.984375 | 3 |
[
"MIT",
"Apache-2.0"
] |
permissive
|
//! Hooks allowing to run code when creating and/or recycling objects.
use std::{fmt, future::Future, pin::Pin};
use super::{Manager, Metrics, ObjectInner};
/// The result returned by hooks
pub type HookResult<E> = Result<(), HookError<E>>;
/// The boxed future that should be returned by async hooks
pub type HookFuture<'a, E> = Pin<Box<dyn Future<Output = HookResult<E>> + Send + 'a>>;
/// Function signature for sync callbacks
type SyncFn<M> =
dyn Fn(&mut <M as Manager>::Type, &Metrics) -> HookResult<<M as Manager>::Error> + Sync + Send;
/// Function siganture for async callbacks
type AsyncFn<M> = dyn for<'a> Fn(&'a mut <M as Manager>::Type, &'a Metrics) -> HookFuture<'a, <M as Manager>::Error>
+ Sync
+ Send;
/// Wrapper for hook functions
pub enum Hook<M: Manager> {
/// Use a plain function (non-async) as a hook
Fn(Box<SyncFn<M>>),
/// Use an async function as a hook
AsyncFn(Box<AsyncFn<M>>),
}
impl<M: Manager> Hook<M> {
/// Create Hook from sync function
pub fn sync_fn(
f: impl Fn(&mut M::Type, &Metrics) -> HookResult<M::Error> + Sync + Send + 'static,
) -> Self {
Self::Fn(Box::new(f))
}
/// Create Hook from async function
pub fn async_fn(
f: impl for<'a> Fn(&'a mut M::Type, &'a Metrics) -> HookFuture<'a, M::Error>
+ Sync
+ Send
+ 'static,
) -> Self {
Self::AsyncFn(Box::new(f))
}
}
impl<M: Manager> fmt::Debug for Hook<M> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Fn(_) => f
.debug_tuple("Fn")
//.field(arg0)
.finish(),
Self::AsyncFn(_) => f
.debug_tuple("AsyncFn")
//.field(arg0)
.finish(),
}
}
}
/// Error which is returned by `pre_create`, `pre_recycle` and
/// `post_recycle` hooks.
#[derive(Debug)]
pub enum HookError<E> {
/// Hook failed for some other reason.
Message(String),
/// Hook failed for some other reason.
StaticMessage(&'static str),
/// Error caused by the backend.
Backend(E),
}
impl<E: fmt::Display> fmt::Display for HookError<E> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Message(msg) => write!(f, "{}", msg),
Self::StaticMessage(msg) => write!(f, "{}", msg),
Self::Backend(e) => write!(f, "{}", e),
}
}
}
impl<E: std::error::Error + 'static> std::error::Error for HookError<E> {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Message(_) => None,
Self::StaticMessage(_) => None,
Self::Backend(e) => Some(e),
}
}
}
pub(crate) struct HookVec<M: Manager> {
vec: Vec<Hook<M>>,
}
// Implemented manually to avoid unnecessary trait bound on `M` type parameter.
impl<M: Manager> fmt::Debug for HookVec<M> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("HookVec")
//.field("fns", &self.fns)
.finish_non_exhaustive()
}
}
// Implemented manually to avoid unnecessary trait bound on `M` type parameter.
impl<M: Manager> Default for HookVec<M> {
fn default() -> Self {
Self { vec: Vec::new() }
}
}
impl<M: Manager> HookVec<M> {
pub(crate) async fn apply(
&self,
inner: &mut ObjectInner<M>,
) -> Result<(), HookError<M::Error>> {
for hook in &self.vec {
match hook {
Hook::Fn(f) => f(&mut inner.obj, &inner.metrics)?,
Hook::AsyncFn(f) => f(&mut inner.obj, &inner.metrics).await?,
};
}
Ok(())
}
pub(crate) fn push(&mut self, hook: Hook<M>) {
self.vec.push(hook);
}
}
/// Collection of all the hooks that can be configured for a [`Pool`].
///
/// [`Pool`]: super::Pool
pub(crate) struct Hooks<M: Manager> {
pub(crate) post_create: HookVec<M>,
pub(crate) pre_recycle: HookVec<M>,
pub(crate) post_recycle: HookVec<M>,
}
// Implemented manually to avoid unnecessary trait bound on `M` type parameter.
impl<M: Manager> fmt::Debug for Hooks<M> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Hooks")
.field("post_create", &self.post_create)
.field("pre_recycle", &self.post_recycle)
.field("post_recycle", &self.post_recycle)
.finish()
}
}
// Implemented manually to avoid unnecessary trait bound on `M` type parameter.
impl<M: Manager> Default for Hooks<M> {
fn default() -> Self {
Self {
pre_recycle: HookVec::default(),
post_create: HookVec::default(),
post_recycle: HookVec::default(),
}
}
}
| true |
402ed30df4f81e238db2e3bdc93c80dce5a191e5
|
Rust
|
ThomasHauth/ros2_rust
|
/rclrs/src/publisher/loaned_message.rs
|
UTF-8
| 2,939 | 2.890625 | 3 |
[
"Apache-2.0"
] |
permissive
|
use std::ops::{Deref, DerefMut};
use rosidl_runtime_rs::RmwMessage;
use crate::rcl_bindings::*;
use crate::{Publisher, RclrsError, ToResult};
/// A message that is owned by the middleware, loaned for publishing.
///
/// It dereferences to a `&mut T`.
///
/// This type is returned by [`Publisher::borrow_loaned_message()`], see the documentation of
/// that function for more information.
///
/// The loan is returned by dropping the message or [publishing it][1].
///
/// [1]: LoanedMessage::publish
pub struct LoanedMessage<'a, T>
where
T: RmwMessage,
{
pub(super) msg_ptr: *mut T,
pub(super) publisher: &'a Publisher<T>,
}
impl<'a, T> Deref for LoanedMessage<'a, T>
where
T: RmwMessage,
{
type Target = T;
fn deref(&self) -> &Self::Target {
// SAFETY: msg_ptr is a valid pointer, obtained through rcl_borrow_loaned_message.
unsafe { &*self.msg_ptr }
}
}
impl<'a, T> DerefMut for LoanedMessage<'a, T>
where
T: RmwMessage,
{
fn deref_mut(&mut self) -> &mut Self::Target {
// SAFETY: msg_ptr is a valid pointer, obtained through rcl_borrow_loaned_message.
unsafe { &mut *self.msg_ptr }
}
}
impl<'a, T> Drop for LoanedMessage<'a, T>
where
T: RmwMessage,
{
fn drop(&mut self) {
// Check whether the loan was already returned with
// rcl_publish_loaned_message()
if !self.msg_ptr.is_null() {
unsafe {
// SAFETY: These two pointers are valid, and the msg_ptr is not used afterwards.
rcl_return_loaned_message_from_publisher(
&*self.publisher.rcl_publisher_mtx.lock().unwrap(),
self.msg_ptr as *mut _,
)
.ok()
.unwrap()
}
}
}
}
// SAFETY: The functions accessing this type, including drop(), shouldn't care about the thread
// they are running in. Therefore, this type can be safely sent to another thread.
unsafe impl<'a, T> Send for LoanedMessage<'a, T> where T: RmwMessage {}
// SAFETY: There is no interior mutability in this type. All mutation happens through &mut references.
unsafe impl<'a, T> Sync for LoanedMessage<'a, T> where T: RmwMessage {}
impl<'a, T> LoanedMessage<'a, T>
where
T: RmwMessage,
{
/// Publishes the loaned message, falling back to regular publishing if needed.
pub fn publish(mut self) -> Result<(), RclrsError> {
unsafe {
// SAFETY: These two pointers are valid, and the msg_ptr is not used afterwards.
rcl_publish_loaned_message(
&*self.publisher.rcl_publisher_mtx.lock().unwrap(),
self.msg_ptr as *mut _,
std::ptr::null_mut(),
)
.ok()?;
}
// Set the msg_ptr to null, as a signal to the drop impl that this
// loan was already returned.
self.msg_ptr = std::ptr::null_mut();
Ok(())
}
}
| true |
56bd2164bc8c2c7ddac12844c366132cf46d6393
|
Rust
|
HeartANDu/rust-snake
|
/src/lib.rs
|
UTF-8
| 9,350 | 3.1875 | 3 |
[] |
no_license
|
extern crate termion;
extern crate rand;
use rand::Rng;
use std::fmt;
const SCORE_PER_MICE: u32 = 100;
pub trait CanMove {
fn do_move(&mut self);
fn set_velocity(&mut self, velocity: Velocity);
}
#[derive(Copy, Clone)]
pub struct Velocity {
vel_x: i16,
vel_y: i16,
}
impl Velocity {
pub fn new(vel_x: i16, vel_y: i16) -> Velocity {
Velocity { vel_x, vel_y }
}
pub fn is_same(&self, other: &Velocity) -> bool {
self.vel_x == other.vel_x && self.vel_y == other.vel_y
}
}
#[derive(Copy, Clone)]
pub struct Coordinates {
x: u16,
y: u16,
}
impl Coordinates {
pub fn new(x: u16, y: u16) -> Coordinates {
Coordinates { x, y }
}
pub fn is_same(&self, other: &Coordinates) -> bool {
self.x == other.x && self.y == other.y
}
}
pub struct Block {
coordinates: Coordinates,
velocity: Velocity,
symbol: char,
}
impl Block {
pub fn new(x: u16, y: u16, symbol: char) -> Block {
Block {
coordinates: Coordinates::new(x, y),
velocity: Velocity::new(0, 0),
symbol,
}
}
pub fn new_random(min_x: u16, max_x: u16, min_y: u16, max_y: u16, symbol: char) -> Block {
let mut rng = rand::thread_rng();
Block::new(rng.gen_range(min_x, max_x), rng.gen_range(min_y, max_y), symbol)
}
}
impl CanMove for Block {
fn do_move(&mut self) {
if self.velocity.vel_x.abs() > 0 {
self.coordinates.x = self.coordinates.x.wrapping_add(self.velocity.vel_x as u16);
}
if self.velocity.vel_y.abs() > 0 {
self.coordinates.y = self.coordinates.y.wrapping_add(self.velocity.vel_y as u16);
}
}
fn set_velocity(&mut self, velocity: Velocity) {
self.velocity = velocity;
}
}
impl fmt::Display for Block {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{}{}",
termion::cursor::Goto(self.coordinates.x, self.coordinates.y),
self.symbol
)
}
}
pub struct Mice {
block: Block,
}
impl Mice {
pub fn new(min_x: u16, max_x: u16, min_y: u16, max_y: u16) -> Mice {
Mice { block: Block::new_random(min_x, max_x, min_y, max_y, 'O') }
}
pub fn new_in_screen(screen: &Screen) -> Mice {
Mice::new(screen.min_x, screen.max_x, screen.min_y, screen.max_y)
}
}
impl fmt::Display for Mice {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.block)
}
}
pub struct Snake {
head: Block,
tail: Vec<Block>,
}
impl Snake {
pub fn new(x: u16, y: u16) -> Snake {
let mut snake = Snake {
head: Block::new(x, y, 'O'),
tail: vec![],
};
for i in 1..4 {
snake.tail.push(Snake::new_tail_circle(x - i, y));
}
snake
}
pub fn new_in_screen(screen: &Screen) -> Snake {
Snake::new((screen.max_x - screen.min_x) / 2, (screen.max_y - screen.min_y) / 2)
}
pub fn grow(&mut self) {
let tail_coords = self.tail.iter().last().unwrap().coordinates;
self.tail.push(Snake::new_tail_circle(tail_coords.x, tail_coords.y));
}
pub fn is_stuck(&self) -> bool {
self.does_intersect_tail(&self.head.coordinates)
}
pub fn does_intersect_tail(&self, coordinates: &Coordinates) -> bool {
match self.tail.iter().position(|piece| piece.coordinates.is_same(coordinates)) {
Some(_) => true,
None => false,
}
}
fn new_tail_circle(x: u16, y: u16) -> Block {
Block::new(x, y, 'o')
}
}
impl CanMove for Snake {
fn do_move(&mut self) {
self.head.do_move();
let mut previous_velocity = self.head.velocity;
for piece in self.tail.iter_mut() {
piece.do_move();
if !previous_velocity.is_same(&piece.velocity) {
let temp_velocity = piece.velocity;
piece.set_velocity(previous_velocity);
previous_velocity = temp_velocity;
}
}
}
fn set_velocity(&mut self, velocity: Velocity) {
if self.head.velocity.vel_x == 0 && self.head.velocity.vel_y == 0 {
self.head.set_velocity(velocity);
self.tail.iter_mut().for_each(|piece| piece.set_velocity(velocity));
}
if self.head.velocity.vel_x != velocity.vel_x && self.head.velocity.vel_y != velocity.vel_y {
self.head.set_velocity(velocity);
}
}
}
impl fmt::Display for Snake {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut result = format!("{}", self.head);
for piece in self.tail.iter() {
result.push_str(format!("{}", piece).as_ref());
}
write!(f, "{}", result)
}
}
pub struct Score {
score: u32,
coordinates: Coordinates,
}
impl Score {
pub fn new(position_x: u16, position_y: u16) -> Score {
Score { score: 0 , coordinates: Coordinates::new(position_x, position_y) }
}
pub fn new_in_screen(screen: &Screen) -> Score {
Score::new(screen.limit_x / 2, screen.min_y - 1)
}
pub fn inc(&mut self) {
self.score += SCORE_PER_MICE;
}
}
impl fmt::Display for Score {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let score = format!("Score: {}", self.score);
write!(
f,
"{}{}",
termion::cursor::Goto(self.coordinates.x - score.len() as u16 / 2, self.coordinates.y),
score
)
}
}
pub struct Screen {
min_x: u16,
max_x: u16,
min_y: u16,
max_y: u16,
limit_x: u16,
limit_y: u16,
}
impl Screen {
pub fn new(size_x: u16, size_y: u16) -> Screen {
Screen {
min_x: 2,
min_y: 2,
max_x: size_x - 1,
max_y: size_y - 1,
limit_x: size_x,
limit_y: size_y,
}
}
pub fn is_inbound(&self, item: &Coordinates) -> bool {
self.is_x_inbound(item.x) && self.is_y_inbound(item.y)
}
pub fn is_x_inbound(&self, x: u16) -> bool {
self.min_x <= x && x <= self.max_x
}
pub fn is_y_inbound(&self, y: u16) -> bool {
self.min_y <= y && y <= self.max_y
}
}
impl fmt::Display for Screen {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let dash_line = "—".repeat((self.max_x - self.min_x + 1) as usize);
write!(f, "{}{}", termion::cursor::Goto(self.min_x, self.min_y - 1), dash_line)?;
write!(f, "{}{}", termion::cursor::Goto(self.min_x, self.max_y + 1), dash_line)?;
for i in self.min_y..(self.max_y + 1) {
write!(
f,
"{}{}{}{}",
termion::cursor::Goto(self.min_x - 1, i),
'|',
termion::cursor::Goto(self.max_x + 1, i),
'|'
)?;
}
Ok(())
}
}
pub struct Game {
screen: Screen,
mice: Mice,
snake: Snake,
score: Score,
is_paused: bool,
}
impl Game {
pub fn new(size_x: u16, size_y: u16) -> Game {
let screen = Screen::new(size_x, size_y);
let mice = Mice::new_in_screen(&screen);
let snake = Snake::new_in_screen(&screen);
let score = Score::new_in_screen(&screen);
Game {
screen,
mice,
snake,
score,
is_paused: false,
}
}
fn make_mice(&mut self) {
self.mice = Mice::new_in_screen(&self.screen);
}
pub fn calc_new_frame(&mut self) {
if self.is_paused {
return;
}
self.snake.do_move();
while self.snake.head.coordinates.is_same(&self.mice.block.coordinates) {
self.score.inc();
self.snake.grow();
self.make_mice();
while self.snake.does_intersect_tail(&self.mice.block.coordinates) {
self.make_mice()
}
}
}
pub fn set_snake_velocity(&mut self, velocity: Velocity) {
if self.is_paused {
return;
}
self.snake.set_velocity(velocity);
}
pub fn switch_pause(&mut self) {
self.is_paused = !self.is_paused;
}
pub fn is_game_over(&self) -> bool {
!self.screen.is_inbound(&self.snake.head.coordinates) || self.snake.is_stuck()
}
pub fn get_game_over_message(&self) -> String {
self.format_message(format!("Game Over! Your score is {}", self.score.score))
}
pub fn get_pause_message(&self) -> String {
self.format_message("Paused".to_string())
}
fn format_message(&self, message: String) -> String {
format!(
"{}{}",
termion::cursor::Goto(
(self.screen.max_x - message.len() as u16) / 2,
self.screen.max_y / 2
),
message
)
}
}
impl fmt::Display for Game {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{}{}{}{}",
self.mice,
self.snake,
self.screen,
self.score
)?;
if self.is_paused {
write!(f, "{}", self.get_pause_message())?;
}
Ok(())
}
}
| true |
34a00bc05fed7f2b7be2097372e80355e0648300
|
Rust
|
colin-daniels/typing
|
/src/paren/ops/any_all.rs
|
UTF-8
| 836 | 2.640625 | 3 |
[] |
no_license
|
use crate::boolean::{AndFn, False, OrFn, True};
use crate::paren::ops::{Fold, FoldOut, Map, MapOut};
pub trait All<F> {
type Output;
fn all(self) -> Self::Output;
}
impl<F, T> All<F> for T
where
Self: Map<F>,
MapOut<F, Self>: Fold<AndFn, True>,
{
type Output = FoldOut<AndFn, MapOut<F, Self>, True>;
#[inline]
fn all(self) -> Self::Output {
self.map().fold(True::default())
}
}
pub type AllOut<F, T> = <T as All<F>>::Output;
pub trait Any<F> {
type Output;
fn any(self) -> Self::Output;
}
impl<F, T> Any<F> for T
where
Self: Map<F>,
MapOut<F, Self>: Fold<OrFn, False>,
{
type Output = FoldOut<OrFn, MapOut<F, Self>, False>;
#[inline]
fn any(self) -> Self::Output {
self.map().fold(False::default())
}
}
pub type AnyOut<F, T> = <T as Any<F>>::Output;
| true |
37e2e9c2968c8b6376fd81fefec78c2f602a3b7b
|
Rust
|
mich2000/smartapp
|
/backend/jwt-gang/src/claim_config.rs
|
UTF-8
| 4,102 | 3.28125 | 3 |
[] |
no_license
|
use crate::claim::Claim;
use crate::claim_error::JwtCustomError;
use jsonwebtoken::errors::ErrorKind;
use jsonwebtoken::{decode, encode, DecodingKey, EncodingKey, Header, TokenData, Validation};
/**
* This configuration will be used to make claims and to validate these claims. The maximum expiration that can be given is 2^16 expiration.
*/
#[derive(Clone)]
pub struct ClaimConfiguration<'a> {
claim_decoder: DecodingKey<'a>,
claim_encoder: EncodingKey,
validation: Validation,
}
impl<'a> ClaimConfiguration<'a> {
pub fn new(issuer: &str, secret: &'a str, expiration: u64) -> Result<Self, JwtCustomError> {
if issuer.is_empty() {
return Err(JwtCustomError::IssuerIsEmpty);
}
if secret.is_empty() {
return Err(JwtCustomError::SecretIsEmpty);
}
if expiration >= i64::MAX as u64 {
return Err(JwtCustomError::ExpirationIsTooBig);
}
Ok(Self {
claim_decoder: DecodingKey::from_secret(secret.as_ref()),
claim_encoder: EncodingKey::from_secret(secret.as_ref()),
validation: Validation {
iss: Some(issuer.to_string()),
leeway: expiration,
..Default::default()
},
})
}
pub fn get_expiration(&self) -> u64 {
self.validation.leeway
}
pub fn create_claim(&self, user_id: &str) -> Result<Claim, JwtCustomError> {
if user_id.is_empty() {
return Err(JwtCustomError::UserIdIsEmpty);
}
let issuer = match &self.validation.iss {
Some(iss) => iss,
None => return Err(JwtCustomError::IssuerIsEmpty),
};
Claim::new(user_id, issuer, self.get_expiration())
}
pub fn token_from_claim(&self, claim: &Claim) -> Result<String, JwtCustomError> {
match encode(&Header::default(), &claim, &self.claim_encoder) {
Ok(token) => {
info!("A token has been made from a claim");
Ok(token)
}
Err(e) => {
warn!("A token couldn't be made out of a claim. Reason: {}", e);
Err(JwtCustomError::TokenCannotBeMadeFromClaim)
}
}
}
/**
* Function that decodes a token string returning a claim.
*
* An error can be thrown when:
* * a token is empty
* * Whenever the issuer of the decoded token is not equal to the issuer in the .env file
* * token is invalid
*/
pub fn decode_token(&self, token: &str) -> Result<TokenData<Claim>, JwtCustomError> {
if token.is_empty() {
warn!("{}", JwtCustomError::TokenIsEmpty);
return Err(JwtCustomError::TokenIsEmpty);
}
match decode::<Claim>(&token, &self.claim_decoder, &self.validation) {
Ok(c) => Ok(c),
Err(err) => match &*err.kind() {
ErrorKind::InvalidToken => {
warn!("{}", JwtCustomError::TokenIsInvalid);
Err(JwtCustomError::TokenIsInvalid)
}
ErrorKind::InvalidIssuer => {
warn!("{}", JwtCustomError::IssuerIsInvalid);
Err(JwtCustomError::IssuerIsInvalid)
}
ErrorKind::ExpiredSignature => {
warn!("{}", JwtCustomError::SignatureHasExpired);
Err(JwtCustomError::SignatureHasExpired)
}
e => {
warn!("{}", format!("Some other JWT error. Error: {:#?}", &e));
Err(JwtCustomError::CustomError(format!(
"Some other JWT error. Error: {:#?}",
&e
)))
}
},
}
}
}
#[test]
fn test_sizes() {
pub fn show_size<T>() {
println!("{}", std::mem::size_of::<T>());
}
show_size::<Validation>();
show_size::<DecodingKey>();
show_size::<EncodingKey>();
show_size::<ClaimConfiguration>();
show_size::<usize>();
show_size::<u16>();
}
| true |
a034d6184443454bbf2036b6df5ec17965d5ba73
|
Rust
|
thekuom/serde_json_tracing_bunyan_formatter_bug_report
|
/src/lib.rs
|
UTF-8
| 363 | 3 | 3 |
[] |
no_license
|
use serde::Deserialize;
#[derive(Debug, Deserialize)]
pub struct Bar {
pub baz: i32,
}
#[derive(Debug, Deserialize)]
pub struct Foo {
#[serde(flatten)]
pub bar: Bar,
}
#[test]
fn deserialize() {
let result: Foo = serde_json::from_str(
r#"{
"baz": 1
}"#,
)
.expect("deserialize failed");
dbg!(result);
}
| true |
f94dae51c7b2a645c4ccf33be060e123d629443f
|
Rust
|
bch29/battlebots
|
/support/src/math.rs
|
UTF-8
| 4,493 | 3.8125 | 4 |
[
"MIT"
] |
permissive
|
/// Serialisable 2D vectors.
pub mod vector {
use cgmath;
use std::ops::{Add, AddAssign, Sub, SubAssign, Mul, MulAssign};
/// A two dimensional vector with `f64` components.
#[derive(PartialEq, PartialOrd, Debug, Clone, Copy, Default, Serialize, Deserialize)]
pub struct Vector2 {
pub x: f64,
pub y: f64,
}
impl Vector2 {
/// Creates a new vector with the given `x` and `y` components.
#[inline]
pub fn new(x: f64, y: f64) -> Self {
Vector2 { x: x, y: y }
}
/// Returns the zero vector.
#[inline]
pub fn zero() -> Self {
Vector2::new(0.0, 0.0)
}
/// Converts a `Vector2` from `cgmath` into a serialisable vector.
#[inline]
pub fn from_cgmath(v: cgmath::Vector2<f64>) -> Self {
Vector2::new(v.x, v.y)
}
/// Converts the vector into `cgmath`'s representation.
#[inline]
pub fn into_cgmath(self) -> cgmath::Vector2<f64> {
cgmath::Vector2::new(self.x, self.y)
}
}
impl<'a, 'b> Add<&'a Vector2> for &'b Vector2 {
type Output = Vector2;
#[inline]
fn add(self, other: &Vector2) -> Vector2 {
Vector2::new(self.x + other.x, self.y + other.y)
}
}
impl Add<Vector2> for Vector2 {
type Output = Vector2;
#[inline]
fn add(self, other: Self) -> Self {
&self + &other
}
}
impl<'a> AddAssign<&'a Vector2> for Vector2 {
#[inline]
fn add_assign(&mut self, other: &Vector2) {
*self = (self as &Vector2) + other
}
}
impl AddAssign<Vector2> for Vector2 {
#[inline]
fn add_assign(&mut self, other: Vector2) {
*self = (self as &Vector2) + &other
}
}
impl<'a, 'b> Sub<&'a Vector2> for &'b Vector2 {
type Output = Vector2;
#[inline]
fn sub(self, other: &Vector2) -> Vector2 {
Vector2::new(self.x - other.x, self.y - other.y)
}
}
impl Sub<Vector2> for Vector2 {
type Output = Vector2;
#[inline]
fn sub(self, other: Self) -> Self {
&self - &other
}
}
impl<'a> SubAssign<&'a Vector2> for Vector2 {
#[inline]
fn sub_assign(&mut self, other: &Vector2) {
*self = (self as &Vector2) - other
}
}
impl SubAssign<Vector2> for Vector2 {
#[inline]
fn sub_assign(&mut self, other: Vector2) {
*self = (self as &Vector2) - &other
}
}
impl<'a> Mul<f64> for &'a Vector2 {
type Output = Vector2;
#[inline]
fn mul(self, scalar: f64) -> Vector2 {
Vector2::new(self.x * scalar, self.y * scalar)
}
}
impl Mul<f64> for Vector2 {
type Output = Vector2;
#[inline]
fn mul(self, scalar: f64) -> Vector2 {
&self * scalar
}
}
impl MulAssign<f64> for Vector2 {
#[inline]
fn mul_assign(&mut self, scalar: f64) {
*self = (self as &Vector2) * scalar
}
}
}
/// Serialisable clamped values.
pub mod clamped {
/// Specifies a range of allowed values which can be clamped to or checked
/// against.
#[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)]
pub struct Clamped<T> {
pub min: T,
pub max: T,
}
impl<T: PartialOrd + Clone> Clamped<T> {
/// Creates a new clamped value with the given min and max.
#[inline]
pub fn new(min: T, max: T) -> Self {
Clamped {
min: min,
max: max
}
}
/// Clamps the given value to between the `min` and `max` values.
#[inline]
pub fn clamp(&self, val: T) -> T {
if val < self.min {
self.min.clone()
} else if val > self.max {
self.max.clone()
} else {
val
}
}
/// Checks if `val` is within `min` and `max` (inclusive). If so,
/// returns `Ok(val)`, otherwise returns `Err(val)`.
#[inline]
pub fn check(&self, val: T) -> Result<T, T> {
if self.min <= val && val <= self.max {
Ok(val)
} else {
Err(val)
}
}
}
}
pub use self::vector::*;
pub use self::clamped::*;
| true |
95e1ac9239bc546edf24a4ff2fed2a7880a2ce67
|
Rust
|
rsfyi/rust-basics
|
/src/enums/enumvalues.rs
|
UTF-8
| 569 | 3.109375 | 3 |
[] |
no_license
|
/*
* - Enums as a types for the field of struct
* - Predefined values
* - using different types inside enums
*/
#[derive(Debug)]
enum IpAddrKind {
V4,
V6,
}
#[derive(Debug)]
struct IpAddr {
kind: IpAddrKind,
address: String,
}
pub fn run() {
let ip_addr_v4 = IpAddr {
kind: IpAddrKind::V4,
address: String::from("127.0.0.1"),
};
let ip_addr_v6 = IpAddr {
kind: IpAddrKind::V6,
address: String::from("::1"),
};
println!(" ipV4 - {:?}", ip_addr_v4);
println!(" ipV4 - {:?}", ip_addr_v6);
}
| true |
e82972a49be19ef7fae31aaf9cafeb93877e7b17
|
Rust
|
notmandatory/gun
|
/src/amount_ext.rs
|
UTF-8
| 944 | 3.265625 | 3 |
[
"0BSD"
] |
permissive
|
use std::str::FromStr;
use anyhow::anyhow;
use bdk::bitcoin::{Amount, Denomination};
pub trait FromCliStr: Sized {
fn from_cli_str(string: &str) -> anyhow::Result<Self>;
}
impl FromCliStr for Amount {
fn from_cli_str(string: &str) -> anyhow::Result<Self> {
match string.rfind(char::is_numeric) {
Some(i) => {
let denom = Denomination::from_str(&string[(i + 1)..])?;
let value: String = string[..=i]
.chars()
.filter(|c| !c.is_whitespace())
.collect();
Ok(Amount::from_str_in(&value, denom)?)
}
None => Err(anyhow!("{} is not a Bitcoin amount")),
}
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_parse_value() {
assert_eq!(
Amount::from_cli_str("0.01BTC").unwrap(),
Amount::from_sat(1_000_000)
);
}
}
| true |
a2293c5b4a72b5441b18a88dc4afd20c17f49ed6
|
Rust
|
HerrFrutti/tanoshi
|
/src/proxy.rs
|
UTF-8
| 3,323 | 3.046875 | 3 |
[
"MIT"
] |
permissive
|
use bytes::Bytes;
use serde::Deserialize;
use std::convert::Infallible;
use warp::{filters::BoxedFilter, hyper::Response, Filter, Reply};
#[derive(Deserialize)]
pub struct Image {
pub url: String,
}
pub fn proxy() -> BoxedFilter<(impl Reply,)> {
warp::path!("image")
.and(warp::get())
.and(warp::query::<Image>())
.and_then(get_image)
.boxed()
}
pub async fn get_image(image: Image) -> Result<impl warp::Reply, Infallible> {
match image.url {
url if url.starts_with("http") => Ok(get_image_from_url(url).await?),
url if !url.is_empty() => Ok(get_image_from_file(url).await?),
_ => Ok(warp::http::Response::builder()
.status(400)
.body(Bytes::new())
.unwrap()),
}
}
pub async fn get_image_from_file(file: String) -> Result<Response<Bytes>, Infallible> {
let file = std::path::PathBuf::from(file);
// if file is already a file, serve it
if file.is_file() {
match std::fs::read(file) {
Ok(buf) => Ok(warp::http::Response::builder()
.status(200)
.body(Bytes::from(buf))
.unwrap()),
Err(_) => Ok(warp::http::Response::builder()
.status(400)
.body(Bytes::new())
.unwrap()),
}
} else {
// else if its combination of archive files and path inside the archive
// extract the file from archive
let filename = file.parent().unwrap().to_str().unwrap();
let path = file.file_name().unwrap().to_str().unwrap();
match libarchive_rs::extract_archive_file(filename, path) {
Ok(buf) => Ok(warp::http::Response::builder()
.status(200)
.body(Bytes::from(buf))
.unwrap()),
Err(_) => Ok(warp::http::Response::builder()
.status(400)
.body(Bytes::new())
.unwrap()),
}
}
}
pub async fn get_image_from_url(url: String) -> Result<Response<Bytes>, Infallible> {
debug!("get image from {}", url);
if url.is_empty() {
return Ok(warp::http::Response::builder()
.status(400)
.body(bytes::Bytes::new())
.unwrap_or_default());
}
let res = match reqwest::get(&url).await.unwrap().bytes().await {
Ok(res) => res,
Err(e) => {
error!("error fetch image, reason: {}", e);
return Ok(warp::http::Response::builder()
.status(500)
.body(bytes::Bytes::new())
.unwrap_or_default());
}
};
let content_type = match url.split('.').rev().take(1).next() {
Some(ext) => ["image", ext].join("/"),
None => "application/octet-stream".to_string(),
};
match warp::http::Response::builder()
.header("Content-Type", content_type)
.header("Content-Length", res.len())
.header("Cache-Control", "max-age=315360000")
.body(res)
{
Ok(res) => Ok(res),
Err(e) => {
error!("error create response, reason: {}", e);
return Ok(warp::http::Response::builder()
.status(500)
.body(bytes::Bytes::new())
.unwrap_or_default());
}
}
}
| true |
abc056b6a6e4071a285d6fba97997c199a3b410d
|
Rust
|
aspires/lucet
|
/lucet-runtime/lucet-runtime-internals/src/instance.rs
|
UTF-8
| 29,913 | 2.71875 | 3 |
[
"LLVM-exception",
"Apache-2.0"
] |
permissive
|
mod siginfo_ext;
pub mod signals;
pub use crate::instance::signals::{signal_handler_none, SignalBehavior, SignalHandler};
use crate::alloc::Alloc;
use crate::context::Context;
use crate::embed_ctx::CtxMap;
use crate::error::Error;
use crate::instance::siginfo_ext::SiginfoExt;
use crate::module::{self, Global, Module};
use crate::trapcode::{TrapCode, TrapCodeType};
use crate::val::{UntypedRetVal, Val};
use crate::WASM_PAGE_SIZE;
use libc::{c_void, siginfo_t, uintptr_t, SIGBUS, SIGSEGV};
use std::any::Any;
use std::cell::{RefCell, UnsafeCell};
use std::ffi::{CStr, CString};
use std::mem;
use std::ops::{Deref, DerefMut};
use std::ptr::{self, NonNull};
use std::sync::Arc;
pub const LUCET_INSTANCE_MAGIC: u64 = 746932922;
pub const INSTANCE_PADDING: usize = 2328;
thread_local! {
/// The host context.
///
/// Control returns here implicitly due to the setup in `Context::init()` when guest functions
/// return normally. Control can return here explicitly from signal handlers when the guest
/// program needs to be terminated.
///
/// This is an `UnsafeCell` due to nested borrows. The context must be borrowed mutably when
/// swapping to the guest context, which means that borrow exists for the entire time the guest
/// function runs even though the mutation to the host context is done only at the beginning of
/// the swap. Meanwhile, the signal handler can run at any point during the guest function, and
/// so it also must be able to immutably borrow the host context if it needs to swap back. The
/// runtime borrowing constraints for a `RefCell` are therefore too strict for this variable.
pub(crate) static HOST_CTX: UnsafeCell<Context> = UnsafeCell::new(Context::new());
/// The currently-running `Instance`, if one exists.
pub(crate) static CURRENT_INSTANCE: RefCell<Option<NonNull<Instance>>> = RefCell::new(None);
}
/// A smart pointer to an [`Instance`](struct.Instance.html) that properly manages cleanup when dropped.
///
/// Instances are always stored in memory backed by a `Region`; we never want to create one directly
/// with the Rust allocator. This type allows us to abide by that rule while also having an owned
/// type that cleans up the instance when we are done with it.
///
/// Since this type implements `Deref` and `DerefMut` to `Instance`, it can usually be treated as
/// though it were a `&mut Instance`.
pub struct InstanceHandle {
inst: NonNull<Instance>,
}
/// Create a new `InstanceHandle`.
///
/// This is not meant for public consumption, but rather is used to make implementations of
/// `Region`.
///
/// # Safety
///
/// This function runs the guest code for the WebAssembly `start` section, and running any guest
/// code is potentially unsafe; see [`Instance::run()`](struct.Instance.html#method.run).
pub fn new_instance_handle(
instance: *mut Instance,
module: Arc<dyn Module>,
alloc: Alloc,
embed_ctx: CtxMap,
) -> Result<InstanceHandle, Error> {
let inst = NonNull::new(instance)
.ok_or(lucet_format_err!("instance pointer is null; this is a bug"))?;
// do this check first so we don't run `InstanceHandle::drop()` for a failure
lucet_ensure!(
unsafe { inst.as_ref().magic } != LUCET_INSTANCE_MAGIC,
"created a new instance handle in memory with existing instance magic; this is a bug"
);
let mut handle = InstanceHandle { inst };
let inst = Instance::new(alloc, module, embed_ctx);
unsafe {
// this is wildly unsafe! you must be very careful to not let the drop impls run on the
// uninitialized fields; see
// <https://doc.rust-lang.org/std/mem/fn.forget.html#use-case-1>
// write the whole struct into place over the uninitialized page
ptr::write(&mut *handle, inst);
};
handle.reset()?;
Ok(handle)
}
pub fn instance_handle_to_raw(inst: InstanceHandle) -> *mut Instance {
let ptr = inst.inst.as_ptr();
std::mem::forget(inst);
ptr
}
pub unsafe fn instance_handle_from_raw(ptr: *mut Instance) -> InstanceHandle {
InstanceHandle {
inst: NonNull::new_unchecked(ptr),
}
}
// Safety argument for these deref impls: the instance's `Alloc` field contains an `Arc` to the
// region that backs this memory, keeping the page containing the `Instance` alive as long as the
// region exists
impl Deref for InstanceHandle {
type Target = Instance;
fn deref(&self) -> &Self::Target {
unsafe { self.inst.as_ref() }
}
}
impl DerefMut for InstanceHandle {
fn deref_mut(&mut self) -> &mut Self::Target {
unsafe { self.inst.as_mut() }
}
}
impl Drop for InstanceHandle {
fn drop(&mut self) {
// eprintln!("InstanceHandle::drop()");
// zero out magic, then run the destructor by taking and dropping the inner `Instance`
self.magic = 0;
unsafe {
mem::replace(self.inst.as_mut(), mem::uninitialized());
}
}
}
/// A Lucet program, together with its dedicated memory and signal handlers.
///
/// This is the primary interface for running programs, examining return values, and accessing the
/// WebAssembly heap.
///
/// `Instance`s are never created by runtime users directly, but rather are acquired from
/// [`Region`](trait.Region.html)s and often accessed through
/// [`InstanceHandle`](struct.InstanceHandle.html) smart pointers. This guarantees that instances
/// and their fields are never moved in memory, otherwise raw pointers in the metadata could be
/// unsafely invalidated.
#[repr(C)]
pub struct Instance {
/// Used to catch bugs in pointer math used to find the address of the instance
magic: u64,
/// The embedding context is a map containing embedder-specific values that are used to
/// implement hostcalls
pub(crate) embed_ctx: CtxMap,
/// The program (WebAssembly module) that is the entrypoint for the instance.
module: Arc<dyn Module>,
/// The `Context` in which the guest program runs
ctx: Context,
/// Instance state and error information
pub(crate) state: State,
/// The memory allocated for this instance
alloc: Alloc,
/// Handler run for signals that do not arise from a known WebAssembly trap, or that involve
/// memory outside of the current instance.
fatal_handler: fn(&Instance) -> !,
/// A fatal handler set from C
c_fatal_handler: Option<unsafe extern "C" fn(*mut Instance)>,
/// Handler run when `SIGBUS`, `SIGFPE`, `SIGILL`, or `SIGSEGV` are caught by the instance thread.
signal_handler: Box<
dyn Fn(
&Instance,
&TrapCode,
libc::c_int,
*const siginfo_t,
*const c_void,
) -> SignalBehavior,
>,
/// Pointer to the function used as the entrypoint (for use in backtraces)
entrypoint: *const extern "C" fn(),
/// Padding to ensure the pointer to globals at the end of the page occupied by the `Instance`
_reserved: [u8; INSTANCE_PADDING],
/// Pointer to the globals
///
/// This is accessed through the `vmctx` pointer, which points to the heap that begins
/// immediately after this struct, so it has to come at the very end.
globals_ptr: *const i64,
}
/// APIs that are internal, but useful to implementors of extension modules; you probably don't want
/// this trait!
///
/// This is a trait rather than inherent `impl`s in order to keep the `lucet-runtime` API clean and
/// safe.
pub trait InstanceInternal {
fn alloc(&self) -> &Alloc;
fn alloc_mut(&mut self) -> &mut Alloc;
fn module(&self) -> &dyn Module;
fn state(&self) -> &State;
fn valid_magic(&self) -> bool;
}
impl InstanceInternal for Instance {
/// Get a reference to the instance's `Alloc`.
fn alloc(&self) -> &Alloc {
&self.alloc
}
/// Get a mutable reference to the instance's `Alloc`.
fn alloc_mut(&mut self) -> &mut Alloc {
&mut self.alloc
}
/// Get a reference to the instance's `Module`.
fn module(&self) -> &dyn Module {
self.module.deref()
}
/// Get a reference to the instance's `State`.
fn state(&self) -> &State {
&self.state
}
/// Check whether the instance magic is valid.
fn valid_magic(&self) -> bool {
self.magic == LUCET_INSTANCE_MAGIC
}
}
// Public API
impl Instance {
/// Run a function with arguments in the guest context at the given entrypoint.
///
/// ```no_run
/// # use lucet_runtime_internals::instance::InstanceHandle;
/// # let instance: InstanceHandle = unimplemented!();
/// // regular execution yields `Ok(UntypedRetVal)`
/// let retval = instance.run(b"factorial", &[5u64.into()]).unwrap();
/// assert_eq!(u64::from(retval), 120u64);
///
/// // runtime faults yield `Err(Error)`
/// let result = instance.run(b"faulting_function", &[]);
/// assert!(result.is_err());
/// ```
///
/// # Safety
///
/// This is unsafe in two ways:
///
/// - The type of the entrypoint might not be correct. It might take a different number or
/// different types of arguments than are provided to `args`. It might not even point to a
/// function! We will likely add type information to `lucetc` output so we can dynamically check
/// the type in the future.
///
/// - The entrypoint is foreign code. While we may be convinced that WebAssembly compiled to
/// native code by `lucetc` is safe, we do not have the same guarantee for the hostcalls that a
/// guest may invoke. They might be implemented in an unsafe language, so we must treat this
/// call as unsafe, just like any other FFI call.
///
/// For the moment, we do not mark this as `unsafe` in the Rust type system, but that may change
/// in the future.
pub fn run(&mut self, entrypoint: &[u8], args: &[Val]) -> Result<UntypedRetVal, Error> {
let func = self.module.get_export_func(entrypoint)?;
self.run_func(func, &args)
}
/// Run a function with arguments in the guest context from the [WebAssembly function
/// table](https://webassembly.github.io/spec/core/syntax/modules.html#tables).
///
/// The same safety caveats of [`Instance::run()`](struct.Instance.html#method.run) apply.
pub fn run_func_idx(
&mut self,
table_idx: u32,
func_idx: u32,
args: &[Val],
) -> Result<UntypedRetVal, Error> {
let func = self.module.get_func_from_idx(table_idx, func_idx)?;
self.run_func(func, &args)
}
/// Reset the instance's heap and global variables to their initial state.
///
/// The WebAssembly `start` section will also be run, if one exists.
///
/// The embedder contexts present at instance creation or added with
/// [`Instance::insert_embed_ctx()`](struct.Instance.html#method.insert_embed_ctx) are not
/// modified by this call; it is the embedder's responsibility to clear or reset their state if
/// necessary.
///
/// # Safety
///
/// This function runs the guest code for the WebAssembly `start` section, and running any guest
/// code is potentially unsafe; see [`Instance::run()`](struct.Instance.html#method.run).
pub fn reset(&mut self) -> Result<(), Error> {
self.alloc.reset_heap(self.module.as_ref())?;
let globals = unsafe { self.alloc.globals_mut() };
let mod_globals = self.module.globals();
for (i, v) in mod_globals.iter().enumerate() {
globals[i] = match v.global() {
Global::Import { .. } => {
return Err(Error::Unsupported(format!(
"global imports are unsupported; found: {:?}",
i
)));
}
Global::Def { def } => def.init_val(),
};
}
self.state = State::Ready {
retval: UntypedRetVal::default(),
};
self.run_start()?;
Ok(())
}
/// Grow the guest memory by the given number of WebAssembly pages.
///
/// On success, returns the number of pages that existed before the call.
pub fn grow_memory(&mut self, additional_pages: u32) -> Result<u32, Error> {
let orig_len = self
.alloc
.expand_heap(additional_pages * WASM_PAGE_SIZE, self.module.as_ref())?;
Ok(orig_len / WASM_PAGE_SIZE)
}
/// Return the WebAssembly heap as a slice of bytes.
pub fn heap(&self) -> &[u8] {
unsafe { self.alloc.heap() }
}
/// Return the WebAssembly heap as a mutable slice of bytes.
pub fn heap_mut(&mut self) -> &mut [u8] {
unsafe { self.alloc.heap_mut() }
}
/// Return the WebAssembly heap as a slice of `u32`s.
pub fn heap_u32(&self) -> &[u32] {
unsafe { self.alloc.heap_u32() }
}
/// Return the WebAssembly heap as a mutable slice of `u32`s.
pub fn heap_u32_mut(&mut self) -> &mut [u32] {
unsafe { self.alloc.heap_u32_mut() }
}
/// Return the WebAssembly globals as a slice of `i64`s.
pub fn globals(&self) -> &[i64] {
unsafe { self.alloc.globals() }
}
/// Return the WebAssembly globals as a mutable slice of `i64`s.
pub fn globals_mut(&mut self) -> &mut [i64] {
unsafe { self.alloc.globals_mut() }
}
/// Check whether a given range in the host address space overlaps with the memory that backs
/// the instance heap.
pub fn check_heap<T>(&self, ptr: *const T, len: usize) -> bool {
self.alloc.mem_in_heap(ptr, len)
}
/// Check whether a context value of a particular type exists.
pub fn contains_embed_ctx<T: Any>(&self) -> bool {
self.embed_ctx.contains::<T>()
}
/// Get a reference to a context value of a particular type, if it exists.
pub fn get_embed_ctx<T: Any>(&self) -> Option<&T> {
self.embed_ctx.get::<T>()
}
/// Get a mutable reference to a context value of a particular type, if it exists.
pub fn get_embed_ctx_mut<T: Any>(&mut self) -> Option<&mut T> {
self.embed_ctx.get_mut::<T>()
}
/// Insert a context value.
///
/// If a context value of the same type already existed, it is returned.
///
/// **Note**: this method is intended for embedder contexts that need to be added _after_ an
/// instance is created and initialized. To add a context for an instance's entire lifetime,
/// including the execution of its `start` section, see
/// [`Region::new_instance_builder()`](trait.Region.html#method.new_instance_builder).
pub fn insert_embed_ctx<T: Any>(&mut self, x: T) -> Option<T> {
self.embed_ctx.insert(x)
}
/// Remove a context value of a particular type, returning it if it exists.
pub fn remove_embed_ctx<T: Any>(&mut self) -> Option<T> {
self.embed_ctx.remove::<T>()
}
/// Set the handler run when `SIGBUS`, `SIGFPE`, `SIGILL`, or `SIGSEGV` are caught by the
/// instance thread.
///
/// In most cases, these signals are unrecoverable for the instance that raised them, but do not
/// affect the rest of the process.
///
/// The default signal handler returns
/// [`SignalBehavior::Default`](enum.SignalBehavior.html#variant.Default), which yields a
/// runtime fault error.
///
/// The signal handler must be
/// [signal-safe](http://man7.org/linux/man-pages/man7/signal-safety.7.html).
pub fn set_signal_handler<H>(&mut self, handler: H)
where
H: 'static
+ Fn(&Instance, &TrapCode, libc::c_int, *const siginfo_t, *const c_void) -> SignalBehavior,
{
self.signal_handler = Box::new(handler) as Box<SignalHandler>;
}
/// Set the handler run for signals that do not arise from a known WebAssembly trap, or that
/// involve memory outside of the current instance.
///
/// Fatal signals are not only unrecoverable for the instance that raised them, but may
/// compromise the correctness of the rest of the process if unhandled.
///
/// The default fatal handler calls `panic!()`.
pub fn set_fatal_handler(&mut self, handler: fn(&Instance) -> !) {
self.fatal_handler = handler;
}
/// Set the fatal handler to a C-compatible function.
///
/// This is a separate interface, because C functions can't return the `!` type. Like the
/// regular `fatal_handler`, it is not expected to return, but we cannot enforce that through
/// types.
///
/// When a fatal error occurs, this handler is run first, and then the regular `fatal_handler`
/// runs in case it returns.
pub fn set_c_fatal_handler(&mut self, handler: unsafe extern "C" fn(*mut Instance)) {
self.c_fatal_handler = Some(handler);
}
}
// Private API
impl Instance {
fn new(alloc: Alloc, module: Arc<dyn Module>, embed_ctx: CtxMap) -> Self {
let globals_ptr = alloc.slot().globals as *mut i64;
Instance {
magic: LUCET_INSTANCE_MAGIC,
embed_ctx: embed_ctx,
module,
ctx: Context::new(),
state: State::Ready {
retval: UntypedRetVal::default(),
},
alloc,
fatal_handler: default_fatal_handler,
c_fatal_handler: None,
signal_handler: Box::new(signal_handler_none) as Box<SignalHandler>,
entrypoint: ptr::null(),
_reserved: [0; INSTANCE_PADDING],
globals_ptr,
}
}
/// Run a function in guest context at the given entrypoint.
fn run_func(
&mut self,
func: *const extern "C" fn(),
args: &[Val],
) -> Result<UntypedRetVal, Error> {
lucet_ensure!(
self.state.is_ready(),
"instance must be ready; this is a bug"
);
if func.is_null() {
return Err(Error::InvalidArgument(
"entrypoint function cannot be null; this is probably a malformed module",
));
}
self.entrypoint = func;
let mut args_with_vmctx = vec![Val::from(self.alloc.slot().heap)];
args_with_vmctx.extend_from_slice(args);
HOST_CTX.with(|host_ctx| {
Context::init(
unsafe { self.alloc.stack_u64_mut() },
unsafe { &mut *host_ctx.get() },
&mut self.ctx,
func,
&args_with_vmctx,
)
})?;
self.state = State::Running;
// there should never be another instance running on this thread when we enter this function
CURRENT_INSTANCE.with(|current_instance| {
let mut current_instance = current_instance.borrow_mut();
assert!(
current_instance.is_none(),
"no other instance is running on this thread"
);
// safety: `self` is not null if we are in this function
*current_instance = Some(unsafe { NonNull::new_unchecked(self) });
});
self.with_signals_on(|i| {
HOST_CTX.with(|host_ctx| {
// Save the current context into `host_ctx`, and jump to the guest context. The
// lucet context is linked to host_ctx, so it will return here after it finishes,
// successfully or otherwise.
unsafe { Context::swap(&mut *host_ctx.get(), &mut i.ctx) };
Ok(())
})
})?;
CURRENT_INSTANCE.with(|current_instance| {
*current_instance.borrow_mut() = None;
});
// Sandbox has jumped back to the host process, indicating it has either:
//
// * trapped, or called hostcall_error: state tag changed to something other than `Running`
// * function body returned: set state back to `Ready` with return value
match &self.state {
State::Running => {
let retval = self.ctx.get_untyped_retval();
self.state = State::Ready { retval };
Ok(retval)
}
State::Terminated { details, .. } => Err(Error::RuntimeTerminated(details.clone())),
State::Fault { .. } => {
// Sandbox is no longer runnable. It's unsafe to determine all error details in the signal
// handler, so we fill in extra details here.
self.populate_fault_detail()?;
if let State::Fault { ref details, .. } = self.state {
if details.fatal {
// Some errors indicate that the guest is not functioning correctly or that
// the loaded code violated some assumption, so bail out via the fatal
// handler.
// Run the C-style fatal handler, if it exists.
self.c_fatal_handler
.map(|h| unsafe { h(self as *mut Instance) });
// If there is no C-style fatal handler, or if it (erroneously) returns,
// call the Rust handler that we know will not return
(self.fatal_handler)(self)
} else {
// leave the full fault details in the instance state, and return the
// higher-level info to the user
Err(Error::RuntimeFault(details.clone()))
}
} else {
panic!("state remains Fault after populate_fault_detail()")
}
}
State::Ready { .. } => {
panic!("instance in Ready state after returning from guest context")
}
}
}
fn run_start(&mut self) -> Result<(), Error> {
if let Some(start) = self.module.get_start_func()? {
self.run_func(start, &[])?;
}
Ok(())
}
fn populate_fault_detail(&mut self) -> Result<(), Error> {
if let State::Fault {
details:
FaultDetails {
rip_addr,
trapcode,
ref mut fatal,
ref mut rip_addr_details,
..
},
siginfo,
..
} = self.state
{
// We do this after returning from the signal handler because it requires `dladdr`
// calls, which are not signal safe
*rip_addr_details = self.module.addr_details(rip_addr as *const c_void)?.clone();
// If the trap table lookup returned unknown, it is a fatal error
let unknown_fault = trapcode.ty == TrapCodeType::Unknown;
// If the trap was a segv or bus fault and the addressed memory was outside the
// guard pages, it is also a fatal error
let outside_guard = (siginfo.si_signo == SIGSEGV || siginfo.si_signo == SIGBUS)
&& !self.alloc.addr_in_heap_guard(siginfo.si_addr());
*fatal = unknown_fault || outside_guard;
}
Ok(())
}
}
pub enum State {
Ready {
retval: UntypedRetVal,
},
Running,
Fault {
details: FaultDetails,
siginfo: libc::siginfo_t,
context: libc::ucontext_t,
},
Terminated {
details: TerminationDetails,
},
}
/// Information about a runtime fault.
///
/// Runtime faults are raised implictly by signal handlers that return `SignalBehavior::Default` in
/// response to signals arising while a guest is running.
#[derive(Clone, Debug)]
pub struct FaultDetails {
/// If true, the instance's `fatal_handler` will be called.
pub fatal: bool,
/// Information about the type of fault that occurred.
pub trapcode: TrapCode,
/// The instruction pointer where the fault occurred.
pub rip_addr: uintptr_t,
/// Extra information about the instruction pointer's location, if available.
pub rip_addr_details: Option<module::AddrDetails>,
}
impl std::fmt::Display for FaultDetails {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
if self.fatal {
write!(f, "fault FATAL ")?;
} else {
write!(f, "fault ")?;
}
self.trapcode.fmt(f)?;
write!(f, "code at address {:p}", self.rip_addr as *const c_void)?;
if let Some(ref addr_details) = self.rip_addr_details {
if let Some(ref fname) = addr_details.file_name {
let sname = addr_details
.sym_name
.as_ref()
.map(String::as_str)
.unwrap_or("<unknown>");
write!(f, " (symbol {}:{})", fname, sname)?;
}
if addr_details.in_module_code {
write!(f, " (inside module code)")
} else {
write!(f, " (not inside module code)")
}
} else {
write!(f, " (unknown whether in module)")
}
}
}
/// Information about a terminated guest.
///
/// Guests are terminated either explicitly by `Vmctx::terminate()`, or implicitly by signal
/// handlers that return `SignalBehavior::Terminate`. It usually indicates that an unrecoverable
/// error has occurred in a hostcall, rather than in WebAssembly code.
#[derive(Clone)]
pub enum TerminationDetails {
Signal,
GetEmbedCtx,
/// Calls to `Vmctx::terminate()` may attach an arbitrary pointer for extra debugging
/// information.
Provided(Arc<dyn Any>),
}
impl TerminationDetails {
pub fn provide<A: Any>(details: A) -> Self {
TerminationDetails::Provided(Arc::new(details))
}
pub fn provided_details(&self) -> Option<&dyn Any> {
match self {
TerminationDetails::Provided(a) => Some(a.as_ref()),
_ => None,
}
}
}
// Because of deref coercions, the code above was tricky to get right-
// test that a string makes it through
#[test]
fn termination_details_any_typing() {
let hello = "hello, world".to_owned();
let details = TerminationDetails::provide(hello.clone());
let provided = details.provided_details().expect("got Provided");
assert_eq!(
provided.downcast_ref::<String>().expect("right type"),
&hello
);
}
impl std::fmt::Debug for TerminationDetails {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(
f,
"TerminationDetails::{}",
match self {
TerminationDetails::Signal => "Signal",
TerminationDetails::GetEmbedCtx => "GetEmbedCtx",
TerminationDetails::Provided(_) => "Provided(Any)",
}
)
}
}
unsafe impl Send for TerminationDetails {}
unsafe impl Sync for TerminationDetails {}
impl std::fmt::Display for State {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
State::Ready { .. } => write!(f, "ready"),
State::Running => write!(f, "running"),
State::Fault {
details, siginfo, ..
} => {
write!(f, "{}", details)?;
write!(
f,
" triggered by {}: ",
strsignal_wrapper(siginfo.si_signo)
.into_string()
.expect("strsignal returns valid UTF-8")
)?;
if siginfo.si_signo == SIGSEGV || siginfo.si_signo == SIGBUS {
// We know this is inside the heap guard, because by the time we get here,
// `lucet_error_verify_trap_safety` will have run and validated it.
write!(
f,
" accessed memory at {:p} (inside heap guard)",
siginfo.si_addr()
)?;
}
Ok(())
}
State::Terminated { .. } => write!(f, "terminated"),
}
}
}
impl State {
pub fn is_ready(&self) -> bool {
if let State::Ready { .. } = self {
true
} else {
false
}
}
pub fn is_running(&self) -> bool {
if let State::Running = self {
true
} else {
false
}
}
pub fn is_fault(&self) -> bool {
if let State::Fault { .. } = self {
true
} else {
false
}
}
pub fn is_fatal(&self) -> bool {
if let State::Fault {
details: FaultDetails { fatal, .. },
..
} = self
{
*fatal
} else {
false
}
}
pub fn is_terminated(&self) -> bool {
if let State::Terminated { .. } = self {
true
} else {
false
}
}
}
fn default_fatal_handler(inst: &Instance) -> ! {
panic!("> instance {:p} had fatal error: {}", inst, inst.state);
}
// TODO: PR into `libc`
extern "C" {
#[no_mangle]
fn strsignal(sig: libc::c_int) -> *mut libc::c_char;
}
// TODO: PR into `nix`
fn strsignal_wrapper(sig: libc::c_int) -> CString {
unsafe { CStr::from_ptr(strsignal(sig)).to_owned() }
}
#[cfg(test)]
mod tests {
use super::*;
use memoffset::offset_of;
#[test]
fn instance_size_correct() {
assert_eq!(mem::size_of::<Instance>(), 4096);
}
#[test]
fn instance_globals_offset_correct() {
let offset = offset_of!(Instance, globals_ptr) as isize;
if offset != 4096 - 8 {
let diff = 4096 - 8 - offset;
let new_padding = INSTANCE_PADDING as isize + diff;
panic!("new padding should be: {:?}", new_padding);
}
assert_eq!(offset_of!(Instance, globals_ptr), 4096 - 8);
}
}
| true |
bd59fec92eefee725c06e41f46fc1809f41d76b5
|
Rust
|
drahnr/yubihsm-rs
|
/src/serial_number.rs
|
UTF-8
| 2,310 | 3.15625 | 3 |
[
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
use serde::{de::Error as DeError, Deserialize, Deserializer, Serialize, Serializer};
use std::{
fmt::{self, Debug, Display},
str::{self, FromStr},
};
use connector::{ConnectionError, ConnectionErrorKind::AddrInvalid};
/// Length of a YubiHSM2 serial number
pub const SERIAL_SIZE: usize = 10;
/// YubiHSM serial numbers
#[derive(Copy, Clone, Eq, Hash, PartialEq, PartialOrd, Ord)]
pub struct SerialNumber([u8; SERIAL_SIZE]);
impl SerialNumber {
/// Borrow this serial as a string
pub fn as_str(&self) -> &str {
str::from_utf8(self.0.as_ref()).unwrap()
}
}
impl AsRef<str> for SerialNumber {
fn as_ref(&self) -> &str {
self.as_str()
}
}
impl Debug for SerialNumber {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "SerialNumber(\"{}\")", self.as_str())
}
}
impl Display for SerialNumber {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.as_str())
}
}
impl FromStr for SerialNumber {
type Err = ConnectionError;
fn from_str(s: &str) -> Result<SerialNumber, ConnectionError> {
if s.len() != SERIAL_SIZE {
return Err(err!(
AddrInvalid,
"invalid serial number length ({}): {}",
s.len(),
s
));
}
for char in s.chars() {
match char {
'0'...'9' => (),
_ => {
return Err(err!(
AddrInvalid,
"invalid character in serial number: {}",
s
))
}
}
}
// We need to use a byte array in order for this to be a `Copy` type
let mut bytes = [0u8; SERIAL_SIZE];
bytes.copy_from_slice(s.as_bytes());
Ok(SerialNumber(bytes))
}
}
impl Serialize for SerialNumber {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
self.0.serialize(serializer)
}
}
impl<'de> Deserialize<'de> for SerialNumber {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
Self::from_str(&String::deserialize(deserializer)?)
.map_err(|e| D::Error::custom(format!("{}", e)))
}
}
| true |
905991a96c0984bc28dfef8700457355ceca6fc5
|
Rust
|
dantengsky/curve25519-dalek
|
/src/utils.rs
|
UTF-8
| 1,103 | 2.65625 | 3 |
[
"LicenseRef-scancode-warranty-disclaimer",
"BSD-3-Clause"
] |
permissive
|
// -*- mode: rust; -*-
//
// This file is part of curve25519-dalek.
// Copyright (c) 2016-2017 Isis Lovecruft, Henry de Valence
// See LICENSE for licensing information.
//
// Authors:
// - Isis Agora Lovecruft <[email protected]>
// - Henry de Valence <[email protected]>
//! Miscellaneous common utility functions.
/// Convert an array of (at least) three bytes into an i64.
#[inline]
//#[allow(dead_code)]
pub fn load3(input: &[u8]) -> i64 {
(input[0] as i64)
| ((input[1] as i64) << 8)
| ((input[2] as i64) << 16)
}
/// Convert an array of (at least) four bytes into an i64.
#[inline]
//#[allow(dead_code)]
pub fn load4(input: &[u8]) -> i64 {
(input[0] as i64)
| ((input[1] as i64) << 8)
| ((input[2] as i64) << 16)
| ((input[3] as i64) << 24)
}
/// Convert an array of (at least) eight bytes into a u64.
#[inline]
//#[allow(dead_code)]
pub fn load8(input: &[u8]) -> u64 {
(input[0] as u64)
| ((input[1] as u64) << 8)
| ((input[2] as u64) << 16)
| ((input[3] as u64) << 24)
| ((input[4] as u64) << 32)
| ((input[5] as u64) << 40)
| ((input[6] as u64) << 48)
| ((input[7] as u64) << 56)
}
| true |
0f76900244ea99dbfa217cc04ad33c8977371a67
|
Rust
|
atoav/bender-worker
|
/src/work/ratelimit.rs
|
UTF-8
| 2,968 | 3.328125 | 3 |
[
"MIT"
] |
permissive
|
use ::*;
use chrono::prelude::DateTime;
use chrono::Utc;
/// The RateLimiter allows to exponentially backoff failing tasks
#[derive(Debug, Default, Clone, Copy)]
pub struct RateLimiter{
last: Option<DateTime<Utc>>,
last_failed: Option<DateTime<Utc>>,
n_failed: usize,
n_max: usize,
min_rate_s: usize,
max_rate_s: usize
}
impl RateLimiter{
/// Create a new RateLimiter using the default configuration
pub fn new() -> Self{
Self::default()
}
/// Implements the Default trait for RateLimiter
pub fn default() -> Self{
RateLimiter{
last: None,
last_failed: None,
n_failed: 0,
n_max: 10,
min_rate_s: 1,
max_rate_s: 120
}
}
/// Set the last successful run and thus resetting the count in `n_failed`
pub fn set_last(&mut self){
self.last = Some(Utc::now());
self.last_failed = None;
self.n_failed = 0
}
/// Set the last errored run, increasing the backoff count and thus making \
/// the next backoff period longer
pub fn set_last_failed(&mut self){
self.last_failed = Some(Utc::now());
self.last = None;
self.n_failed += 1;
}
/// Return true if the last duration is over a certain threshold. For a \
/// sucessful last run we always use the `min_rate_s` as a basis for this \
/// threshold. For a failed last run, this threshold is dynamically \
/// calculated for each increment in the `n_failed` counter by the \
/// method in `Self::calculate_backoff()`
pub fn should_run(&self) -> bool{
match (self.last, self.last_failed){
(None, None) => true,
(Some(last), None) => {
let delta = self.calculate_minimum_rate();
Utc::now() > last + delta
},
(None, Some(last_failed)) => {
let delta = self.calculate_backoff();
Utc::now() > last_failed + delta
},
_ => false
}
}
/// Return a exponential backoff period duration depending on the number of\
/// times `set_last_failed()` has been called, exponentially blending \
/// between `min_rate_s` and `max_rate_s`, with the `max_rate_s` beeing \
/// reached after `n_max` tries.
fn calculate_backoff(&self) -> chrono::Duration{
let factor = self.n_failed as f64 / self.n_max as f64;
// Exponential Backoff
let factor = factor * factor;
// Blend between the min_rate_s and the max_rate_s exponentially
let d = (self.min_rate_s + (self.max_rate_s-self.min_rate_s)) as f64 * factor;
// Return a chrono::Duration
chrono::Duration::seconds(d.round() as i64)
}
fn calculate_minimum_rate(&self) -> chrono::Duration{
chrono::Duration::seconds(self.min_rate_s as i64)
}
}
| true |
34fd9d1ef1383bad261ee6cec0df7fc69365c13a
|
Rust
|
bouzuya/rust-atcoder
|
/cargo-atcoder/contests/dwango2015-prelims/src/bin/b.rs
|
UTF-8
| 666 | 2.875 | 3 |
[] |
no_license
|
use proconio::input;
use proconio::marker::Chars;
fn main() {
input! {
s: Chars,
};
if s.len() == 1 {
println!("{}", 0);
return;
}
let mut v = vec![];
let mut i = 0;
while i < s.len() {
if s[i] == '2' && i + 1 < s.len() && s[i + 1] == '5' {
v.push(true);
i += 2;
} else {
v.push(false);
i += 1;
}
}
let mut c = 0_i64;
let mut sum = 0_i64;
for &v_i in v.iter() {
if v_i {
c += 1;
sum += c;
} else {
c = 0_i64;
}
}
let ans = sum;
println!("{}", ans);
}
| true |
5497d6e97bbf8e6aa4af1bba6d871a47266363bc
|
Rust
|
n8henrie/exercism-exercises
|
/rust/bob/src/lib.rs
|
UTF-8
| 790 | 3.171875 | 3 |
[
"MIT"
] |
permissive
|
const QUESTION_RESPONSE: &str = "Sure.";
const YELLING_RESPONSE: &str = "Whoa, chill out!";
const YELLING_QUESTION_RESPONSE: &str = "Calm down, I know what I'm doing!";
const SILENCE_RESPONSE: &str = "Fine. Be that way!";
const DEFAULT_RESPONSE: &str = "Whatever.";
pub fn is_yelling(m: &str) -> bool {
m.contains(char::is_alphabetic) && m.chars().all(|c| c.is_uppercase() || !c.is_alphabetic())
}
pub fn reply(message: &str) -> &str {
match message.trim() {
m if m.is_empty() => SILENCE_RESPONSE,
m if m.ends_with('?') => {
if is_yelling(m) {
YELLING_QUESTION_RESPONSE
} else {
QUESTION_RESPONSE
}
}
m if is_yelling(m) => YELLING_RESPONSE,
_ => DEFAULT_RESPONSE,
}
}
| true |
b95d86a16eb8be25fbd01ae6558b4b3c8b7e02cb
|
Rust
|
S-YOU/rapidus
|
/src/vm/error.rs
|
UTF-8
| 269 | 2.5625 | 3 |
[
"MIT"
] |
permissive
|
use ansi_term::Colour;
#[derive(Debug, Clone, PartialEq)]
pub enum RuntimeError {
Unknown,
Type(String),
Reference(String),
Unimplemented,
}
pub fn runtime_error(msg: &str) {
eprintln!("{}: {}", Colour::Red.bold().paint("runtime error"), msg,);
}
| true |
df51cc9bcb57cab9a8d2a7f15934c2b1c2a9e202
|
Rust
|
pnkfelix/euca
|
/examples/todomvc/src/lib.rs
|
UTF-8
| 23,235 | 2.671875 | 3 |
[
"MIT",
"Apache-2.0"
] |
permissive
|
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use cfg_if::cfg_if;
use log::{debug,info,error};
use euca::app::*;
use euca::route::Route;
use euca::dom;
use serde::{Serialize,Deserialize};
use serde_json;
cfg_if! {
if #[cfg(feature = "console_error_panic_hook")] {
#[inline]
fn set_panic_hook() {
console_error_panic_hook::set_once();
debug!("panic hook set");
}
}
else {
fn set_panic_hook() {}
}
}
cfg_if! {
if #[cfg(feature = "console_log")] {
#[inline]
fn init_log() {
console_log::init_with_level(log::Level::Trace)
.expect("error initializing log");
debug!("log initialized");
}
}
else {
fn init_log() {}
}
}
const TITLE: &str = "Euca • TodoMVC";
#[derive(PartialEq)]
enum Filter {
All,
Active,
Completed,
}
impl Default for Filter {
fn default() -> Self {
Filter::All
}
}
#[derive(Default)]
struct Todo {
pending_item: String,
items: Vec<Item>,
pending_edit: Option<(usize, String)>,
filter: Filter,
}
impl Todo {
fn with_items(items: Vec<Item>) -> Self {
Todo {
items: items,
.. Todo::default()
}
}
}
#[derive(Default,Serialize,Deserialize)]
struct Item {
#[serde(rename = "title")]
text: String,
#[serde(rename = "completed")]
is_complete: bool,
}
#[derive(PartialEq,Clone,Debug)]
enum Message {
UpdatePending(String),
AddTodo,
RemoveTodo(usize),
ToggleTodo(usize),
EditTodo(usize),
UpdateEdit(String),
SaveEdit,
AbortEdit,
ClearCompleted,
ToggleAll,
ShowAll(bool),
ShowActive(bool),
ShowCompleted(bool),
ItemsChanged,
}
#[derive(Clone,Debug)]
enum Command {
FocusPending,
FocusEdit,
PushHistory(String),
UpdateStorage(String),
}
impl Update<Message, Command> for Todo {
fn update(&mut self, msg: Message, cmds: &mut Commands<Command>) {
use Message::*;
match msg {
UpdatePending(text) => {
self.pending_item = text
}
AddTodo => {
self.items.push(Item {
text: self.pending_item.trim().to_owned(),
.. Item::default()
});
self.pending_item.clear();
self.update(ItemsChanged, cmds);
}
RemoveTodo(i) => {
self.items.remove(i);
self.update(ItemsChanged, cmds);
}
ToggleTodo(i) => {
self.items[i].is_complete = !self.items[i].is_complete;
self.update(ItemsChanged, cmds);
}
EditTodo(i) => {
self.pending_edit = Some((i, self.items[i].text.clone()));
cmds.post_render.push(Command::FocusEdit);
}
UpdateEdit(text) => {
match self.pending_edit {
Some((_, ref mut pending_text)) => {
*pending_text = text;
}
_ => panic!("UpdateEdit called with no pending edit"),
}
}
SaveEdit => {
match self.pending_edit {
Some((i, ref text)) => {
if text.trim().is_empty() {
self.update(RemoveTodo(i), cmds);
}
else {
self.items[i].text = text.trim().to_owned();
}
self.pending_edit = None;
}
_ => panic!("SaveEdit called with no pending edit"),
}
self.update(ItemsChanged, cmds);
}
AbortEdit => {
self.pending_edit = None;
}
ClearCompleted => {
self.items.retain(|item| !item.is_complete);
self.update(ItemsChanged, cmds);
}
ToggleAll => {
let all_complete = self.items.iter().all(|item| item.is_complete);
for item in self.items.iter_mut() {
item.is_complete = !all_complete;
}
self.update(ItemsChanged, cmds);
}
ShowAll(push_history) => {
self.filter = Filter::All;
if push_history {
cmds.push(Command::PushHistory("#/".to_owned()));
}
}
ShowActive(push_history) => {
self.filter = Filter::Active;
if push_history {
cmds.push(Command::PushHistory("#/active".to_owned()));
}
}
ShowCompleted(push_history) => {
self.filter = Filter::Completed;
if push_history {
cmds.push(Command::PushHistory("#/completed".to_owned()));
}
}
ItemsChanged => {
cmds.push(Command::UpdateStorage(serde_json::to_string(&self.items).unwrap()));
}
}
}
}
impl SideEffect<Message> for Command {
fn process(self, _: &Dispatcher<Message, Command>) {
use Command::*;
match self {
FocusPending => {
let pending_input = web_sys::window()
.expect("couldn't get window handle")
.document()
.expect("couldn't get document handle")
.query_selector("section.todoapp header.header input.new-todo")
.expect("error querying for element")
.expect("expected to find an input element")
.dyn_into::<web_sys::HtmlInputElement>()
.expect_throw("expected web_sys::HtmlInputElement");
pending_input.focus().expect_throw("error focusing input");
}
FocusEdit => {
let edit_input = web_sys::window()
.expect_throw("couldn't get window handle")
.document()
.expect_throw("couldn't get document handle")
.query_selector("section.todoapp section.main input.edit")
.expect_throw("error querying for element")
.expect_throw("expected to find an input element")
.dyn_into::<web_sys::HtmlInputElement>()
.expect_throw("expected web_sys::HtmlInputElement");
edit_input.focus().expect_throw("error focusing input");
}
PushHistory(url) => {
let history = web_sys::window()
.expect("couldn't get window handle")
.history()
.expect_throw("couldn't get history handle");
history.push_state_with_url(&JsValue::NULL, TITLE, Some(&url)).expect_throw("error updating history");
}
UpdateStorage(data) => {
let local_storage = web_sys::window()
.expect("couldn't get window handle")
.local_storage()
.expect("couldn't get local storage handle")
.expect_throw("local storage not supported?");
local_storage.set_item("todo-euca", &data).unwrap_throw();
}
}
}
}
fn read_items_from_storage() -> Vec<Item> {
let local_storage = web_sys::window()
.expect("couldn't get window handle")
.local_storage()
.expect("couldn't get local storage handle")
.expect_throw("local storage not supported?");
local_storage.get_item("todo-euca")
.expect_throw("error reading from storage")
.map_or(vec![], |items|
match serde_json::from_str(&items) {
Ok(items) => items,
Err(e) => {
error!("error reading items from storage: {}", e);
vec![]
}
}
)
}
impl Render<dom::DomVec<Message, Command>> for Todo {
fn render(&self) -> dom::DomVec<Message, Command> {
use dom::Dom;
use dom::Handler::Event;
let mut vec = vec![];
vec.push(Dom::elem("header")
.attr("class", "header")
.push(Dom::elem("h1").push("todos"))
.push(Dom::elem("input")
.attr("class", "new-todo")
.attr("placeholder", "What needs to be done?")
.attr("autofocus", "true")
.attr("value", self.pending_item.to_owned())
.on("input", dom::Handler::InputValue(|s| {
Some(Message::UpdatePending(s))
}))
.on("keyup", Event(|e| {
let e = e.dyn_into::<web_sys::KeyboardEvent>().expect_throw("expected web_sys::KeyboardEvent");
match e.key().as_ref() {
"Enter" => Some(Message::AddTodo),
_ => None,
}
}))
)
);
// render todo list if necessary
if !self.items.is_empty() {
// main section
vec.push(Dom::elem("section")
.attr("class", "main")
.push(Dom::elem("input")
.attr("id", "toggle-all")
.attr("class", "toggle-all")
.attr("type", "checkbox")
.attr("checked", self.items.iter().all(|item| item.is_complete).to_string())
.event("change", Message::ToggleAll)
)
.push(Dom::elem("label")
.attr("for", "toggle-all")
.push("Mark all as complete")
)
.push(Dom::elem("ul")
.attr("class", "todo-list")
.extend(self.items.iter()
.enumerate()
.filter(|(_, item)| {
match self.filter {
Filter::All => true,
Filter::Active => !item.is_complete,
Filter::Completed => item.is_complete,
}
})
.map(|(i, item)| {
match self.pending_edit {
Some((pending_i, ref pending_edit)) if pending_i == i => {
item.render(i, Some(pending_edit))
}
Some(_) | None => {
item.render(i, None)
}
}
})
)
)
);
// todo footer
vec.push({
let remaining = self.items.iter()
.filter(|item| !item.is_complete)
.count();
let footer = Dom::elem("footer")
.attr("class", "footer")
.push(Dom::elem("span")
.attr("class", "todo-count")
.push(Dom::elem("strong")
.push(remaining.to_string())
)
.push(
if remaining == 1 { " item left" }
else { " items left" }
)
)
.push(Dom::elem("ul")
.attr("class", "filters")
.push(Dom::elem("li")
.push(Dom::elem("a")
.attr("href", "#/")
.attr("class",
if self.filter == Filter::All { "selected" }
else { "" }
)
.push("All")
.on("click", Event(|e| {
e.prevent_default();
Some(Message::ShowAll(true))
}))
)
)
.push(Dom::elem("li")
.push(Dom::elem("a")
.attr("href", "#/active")
.attr("class",
if self.filter == Filter::Active { "selected" }
else { "" }
)
.push("Active")
.on("click", Event(|e| {
e.prevent_default();
Some(Message::ShowActive(true))
}))
)
)
.push(Dom::elem("li")
.push(Dom::elem("a")
.attr("href", "#/completed")
.attr("class",
if self.filter == Filter::Completed { "selected" }
else { "" }
)
.push("Completed")
.on("click", Event(|e| {
e.prevent_default();
Some(Message::ShowCompleted(true))
}))
)
)
)
;
if self.items.iter().any(|item| item.is_complete) {
footer.push(Dom::elem("button")
.attr("class", "clear-completed")
.push("Clear completed")
.event("click", Message::ClearCompleted)
)
}
else {
footer
}
});
}
vec.into()
}
}
impl Item {
fn render(&self, i: usize, pending_edit: Option<&str>) -> dom::Dom<Message, Command> {
use dom::Dom;
use dom::Handler::{Event,InputValue};
let e = Dom::elem("li");
if let Some(pending_edit) = pending_edit {
e.attr("class", "editing")
.push(Dom::elem("input")
.attr("class", "edit")
.attr("value", pending_edit)
.on("input", InputValue(|s| {
Some(Message::UpdateEdit(s))
}))
.event("blur", Message::SaveEdit)
.on("keyup", Event(|e| {
let e = e.dyn_into::<web_sys::KeyboardEvent>().expect_throw("expected web_sys::KeyboardEvent");
match e.key().as_ref() {
"Enter" => Some(Message::SaveEdit),
"Escape" => Some(Message::AbortEdit),
_ => None,
}
}))
)
}
else {
let e = e.push(
Dom::elem("div")
.attr("class", "view")
.push(Dom::elem("input")
.attr("class", "toggle")
.attr("type", "checkbox")
.attr("checked", self.is_complete.to_string())
.event("change", Message::ToggleTodo(i))
)
.push(Dom::elem("label")
.push(self.text.to_owned())
.event("dblclick", Message::EditTodo(i))
)
.push(Dom::elem("button")
.attr("class", "destroy")
.event("click", Message::RemoveTodo(i))
)
);
if self.is_complete {
e.attr("class", "completed")
}
else {
e
}
}
}
}
#[derive(Default)]
struct Router {}
impl Route<Message> for Router {
fn route(&self, url: &str) -> Option<Message> {
if url.ends_with("#/active") {
Some(Message::ShowActive(false))
}
else if url.ends_with("#/completed") {
Some(Message::ShowCompleted(false))
}
else {
Some(Message::ShowAll(false))
}
}
}
#[wasm_bindgen(start)]
pub fn start() -> Result<(), JsValue> {
init_log();
set_panic_hook();
let parent = web_sys::window()
.expect("couldn't get window handle")
.document()
.expect("couldn't get document handle")
.query_selector("section.todoapp")
.expect("error querying for element")
.expect("expected <section class=\"todoapp\"></section>");
let items = read_items_from_storage();
let app = AppBuilder::default()
.router(Router::default())
.attach(parent, Todo::with_items(items));
Command::FocusPending.process(&app.into());
info!("{} initialized", TITLE);
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use euca::app::Commands;
#[test]
fn add_todo() {
let mut todomvc = Todo::default();
todomvc.update(Message::UpdatePending("item".to_owned()), &mut Commands::default());
todomvc.update(Message::AddTodo, &mut Commands::default());
assert_eq!(todomvc.items.len(), 1);
assert_eq!(todomvc.items[0].text, "item");
assert_eq!(todomvc.items[0].is_complete, false);
}
#[test]
fn remove_todo() {
let mut todomvc = Todo::default();
todomvc.items.push(Item::default());
todomvc.update(Message::RemoveTodo(0), &mut Commands::default());
assert_eq!(todomvc.items.len(), 0);
}
#[test]
fn toggle_todo() {
let mut todomvc = Todo::default();
todomvc.items.push(Item::default());
todomvc.update(Message::ToggleTodo(0), &mut Commands::default());
assert_eq!(todomvc.items[0].is_complete, true);
}
#[test]
fn save_edit_removes_empty() {
let mut todomvc = Todo::default();
todomvc.items.push(Item {
text: "text".to_owned(),
.. Item::default()
});
todomvc.update(Message::EditTodo(0), &mut Commands::default());
todomvc.update(Message::UpdateEdit("".to_owned()), &mut Commands::default());
todomvc.update(Message::SaveEdit, &mut Commands::default());
assert_eq!(todomvc.items.len(), 0);
}
#[test]
fn save_edit_trims_whitespace() {
let mut todomvc = Todo::default();
todomvc.items.push(Item {
text: "text".to_owned(),
.. Item::default()
});
todomvc.update(Message::EditTodo(0), &mut Commands::default());
todomvc.update(Message::UpdateEdit(" edited text ".to_owned()), &mut Commands::default());
todomvc.update(Message::SaveEdit, &mut Commands::default());
assert_eq!(todomvc.items.len(), 1);
assert_eq!(todomvc.items[0].text, "edited text");
}
#[test]
fn abort_edit_does_not_modify() {
let mut todomvc = Todo::default();
todomvc.items.push(Item {
text: "text".to_owned(),
.. Item::default()
});
todomvc.update(Message::EditTodo(0), &mut Commands::default());
todomvc.update(Message::UpdateEdit(" edited text ".to_owned()), &mut Commands::default());
todomvc.update(Message::AbortEdit, &mut Commands::default());
assert_eq!(todomvc.items.len(), 1);
assert_eq!(todomvc.items[0].text, "text");
}
#[test]
fn clear_completed() {
let mut todomvc = Todo::default();
todomvc.items.push(Item {
text: "text1".to_owned(),
.. Item::default()
});
todomvc.items.push(Item {
text: "text2".to_owned(),
is_complete: true,
.. Item::default()
});
todomvc.items.push(Item {
text: "text3".to_owned(),
.. Item::default()
});
todomvc.update(Message::ClearCompleted, &mut Commands::default());
assert_eq!(todomvc.items.len(), 2);
assert_eq!(todomvc.items[0].text, "text1");
assert_eq!(todomvc.items[1].text, "text3");
}
#[test]
fn toggle_all() {
let mut todomvc = Todo::default();
todomvc.items.push(Item {
text: "text1".to_owned(),
.. Item::default()
});
todomvc.items.push(Item {
text: "text2".to_owned(),
is_complete: true,
.. Item::default()
});
todomvc.items.push(Item {
text: "text3".to_owned(),
.. Item::default()
});
todomvc.update(Message::ToggleAll, &mut Commands::default());
assert!(todomvc.items.iter().all(|item| item.is_complete));
todomvc.update(Message::ToggleAll, &mut Commands::default());
assert!(todomvc.items.iter().all(|item| !item.is_complete));
}
#[test]
fn test_routes() {
use Message::*;
let router = Router::default();
assert_eq!(router.route("http://localhost:8080"), Some(ShowAll(false)));
assert_eq!(router.route("http://localhost:8080/"), Some(ShowAll(false)));
assert_eq!(router.route("http://localhost:8080/#/"), Some(ShowAll(false)));
assert_eq!(router.route("http://localhost:8080/#/"), Some(ShowAll(false)));
assert_eq!(router.route("http://localhost:8080/#/active"), Some(ShowActive(false)));
assert_eq!(router.route("http://localhost:8080/#/completed"), Some(ShowCompleted(false)));
}
#[test]
fn storage_triggers() {
use Message::*;
use Command::*;
let mut todomvc = Todo::default();
todomvc.items.push(Item::default());
todomvc.items.push(Item::default());
todomvc.items.push(Item::default());
// ensure the following message types generate UpdateStorage commands
for msg in &[
AddTodo,
RemoveTodo(0),
ToggleTodo(0),
SaveEdit,
ClearCompleted,
ToggleAll,
ItemsChanged,
] {
// do necessary prep work
match msg {
SaveEdit => todomvc.update(EditTodo(0), &mut Commands::default()),
_ => {}
}
let mut cmds = Commands::default();
todomvc.update(msg.clone(), &mut cmds);
// verify the proper commands were generated
assert!(
cmds.immediate.iter().any(|cmd| match cmd {
UpdateStorage(_) => true,
_ => false,
}),
"didn't find UpdateStorage for {:?}", msg
);
}
}
}
| true |
4180a72850f942dfa9c7ad0c00e630c86c135031
|
Rust
|
cih-y2k/RustyTarantool
|
/src/tarantool/packets.rs
|
UTF-8
| 6,456 | 2.671875 | 3 |
[
"Apache-2.0"
] |
permissive
|
#![allow(non_camel_case_types)]
use std::io;
use std::str;
use rmpv::{Value};
use serde::{Serialize, Deserialize};
use tarantool::tools;
use bytes::{Bytes ,IntoBuf};
/// tarantool auth packet
#[derive(Debug)]
pub struct AuthPacket {
pub login: String,
pub password: String,
}
/// tarantool packet intended for serialize and cross thread send
#[derive(Debug,Clone)]
pub struct CommandPacket {
pub code: Code,
pub internal_fields: Vec<(Key, Value)>,
pub command_field: Vec<(Key, Vec<u8>)>,
}
/// Tarantool request enum (auth or ordinary packet)
#[derive(Debug)]
pub enum TarantoolRequest {
Auth(AuthPacket),
Command(CommandPacket),
}
/// Tarantool response struct
///
/// use any decode method to decode tarantool response to custom struct by serde
/// please look examples
/// https://github.com/zheludkovm/RustyTarantool/tree/master/examples
///
#[derive(Debug)]
pub struct TarantoolResponse {
code: u64,
data: Bytes,
}
#[derive(Debug,Clone)]
pub enum Code {
SELECT = 0x01,
INSERT = 0x02,
REPLACE = 0x03,
UPDATE = 0x04,
DELETE = 0x05,
OLD_CALL = 0x06,
AUTH = 0x07,
EVAL = 0x08,
UPSERT = 0x09,
CALL = 0x010,
PING = 0x064,
SUBSCRIBE = 0x066,
}
#[derive(Debug, Copy, Clone)]
pub enum Key {
//header
CODE = 0x00,
SYNC = 0x01,
SCHEMA_ID = 0x05,
//body
SPACE = 0x10,
INDEX = 0x11,
LIMIT = 0x12,
OFFSET = 0x13,
ITERATOR = 0x14,
KEY = 0x20,
TUPLE = 0x21,
FUNCTION = 0x22,
USER_NAME = 0x23,
EXPRESSION = 0x27,
UPSERT_OPS = 0x28,
DATA = 0x30,
ERROR = 0x31,
}
impl TarantoolResponse {
pub fn new (code:u64, data: Bytes) -> TarantoolResponse {
TarantoolResponse{code, data}
}
/// decode tarantool response to any serder deserializable struct
pub fn decode<'de, T>(self) -> io::Result<T>
where T: Deserialize<'de>
{
tools::decode_serde(self.data.into_buf())
}
/// decode tarantool response to tuple wih one element and return this element
pub fn decode_single<'de, T>(self) -> io::Result<T>
where T: Deserialize<'de>
{
let (res,) = tools::decode_serde(self.data.into_buf())?;
Ok(res)
}
/// decode tarantool response to tuple of two elements
pub fn decode_pair<'de, T1, T2>(self) -> io::Result<(T1,T2)>
where T1: Deserialize<'de>,T2: Deserialize<'de>
{
Ok(tools::decode_serde(self.data.into_buf())?)
}
///decode tarantool response to three elements
pub fn decode_trio<'de, T1, T2, T3>(self) -> io::Result<(T1,T2,T3)>
where T1: Deserialize<'de>,T2: Deserialize<'de>,T3: Deserialize<'de>
{
let (r1,r2,r3) = tools::decode_serde(self.data.into_buf())?;
Ok((r1,r2,r3))
}
}
impl CommandPacket {
pub fn call<T>(function: &str, params: &T) -> io::Result<CommandPacket>
where T:Serialize
{
Ok(
CommandPacket {
code: Code::OLD_CALL,
internal_fields: vec![(Key::FUNCTION,Value::from(function))],
command_field: vec![(Key::TUPLE, tools::serialize_to_vec_u8(params)? )]
}
)
}
pub fn select<T>(space:i32, index:i32, key:&T, offset:i32, limit:i32, iterator:i32) -> io::Result<CommandPacket>
where T:Serialize
{
Ok(
CommandPacket {
code: Code::SELECT,
internal_fields: vec![
(Key::SPACE,Value::from(space)),
(Key::INDEX,Value::from(index)),
(Key::ITERATOR,Value::from(iterator)),
(Key::LIMIT,Value::from(limit)),
(Key::OFFSET,Value::from(offset)),
],
command_field: vec![(Key::KEY, tools::serialize_to_vec_u8(key)? )]
}
)
}
pub fn insert<T>(space:i32, tuple: &T) -> io::Result<CommandPacket>
where T:Serialize
{
Ok(
CommandPacket {
code: Code::INSERT,
internal_fields: vec![(Key::SPACE,Value::from(space))],
command_field: vec![(Key::TUPLE, tools::serialize_to_vec_u8(tuple)? )]
}
)
}
pub fn replace<T>(space:i32, tuple: &T) -> io::Result<CommandPacket>
where T:Serialize
{
Ok(
CommandPacket {
code: Code::REPLACE,
internal_fields: vec![(Key::SPACE,Value::from(space))],
command_field: vec![(Key::TUPLE, tools::serialize_to_vec_u8(tuple)? )]
}
)
}
pub fn update<T,T2>(space:i32, key:&T2, args: &T) -> io::Result<CommandPacket>
where T:Serialize, T2:Serialize
{
Ok(
CommandPacket {
code: Code::UPDATE,
internal_fields: vec![(Key::SPACE,Value::from(space))],
command_field: vec![
(Key::KEY, tools::serialize_to_vec_u8(key)? ),
(Key::TUPLE, tools::serialize_to_vec_u8(args)? ),
]
}
)
}
pub fn upsert<T,T2,T3>(space:i32, key:&T2, def:&T3, args: &T) -> io::Result<CommandPacket>
where T:Serialize, T2:Serialize, T3:Serialize
{
Ok(
CommandPacket {
code: Code::UPSERT,
internal_fields: vec![(Key::SPACE,Value::from(space))],
command_field: vec![
(Key::KEY, tools::serialize_to_vec_u8(key)? ),
(Key::TUPLE, tools::serialize_to_vec_u8(def)? ),
(Key::UPSERT_OPS, tools::serialize_to_vec_u8(args)? ),
]
}
)
}
pub fn delete<T>(space:i32, key: &T) -> io::Result<CommandPacket>
where T:Serialize
{
Ok(
CommandPacket {
code: Code::DELETE,
internal_fields: vec![(Key::SPACE,Value::from(space))],
command_field: vec![(Key::KEY, tools::serialize_to_vec_u8(key)? )]
}
)
}
pub fn eval<T>(expression:String, args: &T) -> io::Result<CommandPacket>
where T:Serialize
{
Ok(
CommandPacket {
code: Code::EVAL,
internal_fields: vec![(Key::EXPRESSION,Value::from(expression))],
command_field: vec![(Key::TUPLE, tools::serialize_to_vec_u8(args)? )]
}
)
}
}
| true |
781fdeb1243bd028f811be05361cfa2bd885ece5
|
Rust
|
jvff/dkr
|
/src/dockerfile/run_commands.rs
|
UTF-8
| 912 | 2.96875 | 3 |
[] |
no_license
|
use super::single_or_multiple_items_visitor::SingleOrMultipleItemsVisitor;
use serde::{Deserialize, Deserializer};
use std::fmt::{self, Display, Formatter};
#[derive(Debug)]
pub struct RunCommands {
commands: Vec<String>,
}
impl<'de> Deserialize<'de> for RunCommands {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
Ok(RunCommands {
commands: deserializer.deserialize_any(SingleOrMultipleItemsVisitor)?,
})
}
}
impl Display for RunCommands {
fn fmt(&self, formatter: &mut Formatter) -> fmt::Result {
let mut commands = self.commands.iter();
if let Some(command) = commands.next() {
write!(formatter, "RUN {}", command)?;
for command in commands {
write!(formatter, " && {}", command)?;
}
}
writeln!(formatter)
}
}
| true |
4e016d9bd0ffb1582bb23ec896e783cec641830f
|
Rust
|
tgolsson/kludgine
|
/core/src/shape/stroke.rs
|
UTF-8
| 1,042 | 2.875 | 3 |
[
"MIT",
"Apache-2.0"
] |
permissive
|
use easygpu_lyon::lyon_tessellation::StrokeOptions;
use figures::Figure;
use crate::{color::Color, math::Scaled};
/// A shape stroke (outline) options.
#[derive(Default, Clone, Debug)]
pub struct Stroke {
/// The color to stroke the shape's with.
pub color: Color,
/// The options for drawing the stroke.
pub options: StrokeOptions,
}
impl Stroke {
/// Creates a new instance using `color` with default options.
#[must_use]
pub fn new(color: Color) -> Self {
Self {
color,
options: StrokeOptions::default(),
}
}
/// Builder-style function. Sets `options` and return self.
#[must_use]
pub const fn with_options(mut self, options: StrokeOptions) -> Self {
self.options = options;
self
}
/// Builder-style function. Sets `options.line_width` and return self.
#[must_use]
pub fn line_width<F: Into<Figure<f32, Scaled>>>(mut self, width: F) -> Self {
self.options.line_width = width.into().get();
self
}
}
| true |
8fe1fac422f31134708af4caac62cbc396ce8cb1
|
Rust
|
bonifaido/rust-sophia
|
/examples/example.rs
|
UTF-8
| 3,071 | 2.75 | 3 |
[] |
no_license
|
extern crate sophia;
use sophia::Native;
fn main() {
println!("## Setup ##");
let env = sophia::Sophia::new().unwrap();
println!("env type {}", env.get_type().unwrap());
let ctl = env.ctl();
let res = ctl.set("sophia.path", "./target/test.db");
println!("ctl.set {:?}", res.unwrap());
let res = ctl.set("db", "test");
println!("ctl.set {:?}", res.unwrap());
let res = env.open();
println!("env.open {:?}", res.unwrap());
let db = ctl.get_db("db.test").unwrap();
println!("## Set ##");
{
let object = db.object().unwrap();
println!("object type {}", object.get_type().unwrap());
let res = object.set("key", "hello".as_bytes());
println!("object.set.key {:?}", res.unwrap());
let res = object.set("value", "world".as_bytes());
println!("object.set.value {:?}", res.unwrap());
let res = db.set(&object);
println!("db.set.object {:?}", res.unwrap());
}
println!("## Get ##");
{
let object = db.object().unwrap();
let res = object.set("key", "hello".as_bytes());
println!("object.set.key {:?}", res.unwrap());
let object = db.get(&object).unwrap();
println!("db.get.object Ok");
let field = "value";
let value = object.get(field).ok().expect("value can't be read");
println!("object.get.{} {:?}", field, std::str::from_utf8(value).unwrap());
}
println!("## Transaction ##");
{
let object = db.object().unwrap();
let res = object.set("key", "inside".as_bytes());
println!("object.set.key {:?}", res.unwrap());
let res = object.set("value", "transaction".as_bytes());
println!("object.set.value {:?}", res.unwrap());
let transaction = env.transaction().unwrap();
let res = transaction.set(&object);
println!("transaction.set.object {:?}", res.unwrap());
let res = transaction.commit();
println!("transaction.commit {:?}", res.unwrap());
}
println!("## Cursor ## Bogus atm -> thread '<main>' has overflowed its stack");
{
let options = db.object().unwrap();
let cursor = db.cursor(&options).unwrap();
println!("db.cursor Ok");
loop {
let object = cursor.get(); // TODO
match object {
Err(_) => break,
Ok(object) => {
let key = object.get("key").unwrap();
let value = object.get("value").unwrap();
println!("cursor.object.key = {:?}", std::str::from_utf8(key).unwrap());
println!("cursor.object.value = {:?}", std::str::from_utf8(value).unwrap());
}
}
}
}
println!("## Delete ##");
{
let object = db.object().unwrap();
let res = object.set("key", "hello".as_bytes());
println!("object.set.key {:?}", res.unwrap());
let res = db.delete(&object).unwrap();
println!("db.delete.object {:?}", res);
}
}
| true |
1761e09522a13368946271fb4e7a0b49dbbd8a2a
|
Rust
|
Volland/steel
|
/steel/src/steel_vm/engine.rs
|
UTF-8
| 20,880 | 2.75 | 3 |
[
"Apache-2.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
use super::{
options::{ApplyContract, DoNotApplyContracts, DoNotUseCallback, UseCallback},
primitives::{embed_primitives, embed_primitives_without_io, CONSTANTS},
vm::VirtualMachineCore,
};
use crate::{
compiler::{compiler::Compiler, constants::ConstantMap, program::Program},
core::instructions::DenseInstruction,
parser::ast::ExprKind,
parser::parser::{ParseError, Parser},
rerrs::{ErrorKind, SteelErr},
rvals::{FromSteelVal, IntoSteelVal, Result, SteelVal},
stop, throw,
};
use std::{
collections::HashMap,
io::Read,
path::{Path, PathBuf},
rc::Rc,
};
use im_rc::HashMap as ImmutableHashMap;
use itertools::Itertools;
pub struct Engine {
virtual_machine: VirtualMachineCore,
compiler: Compiler,
constants: Option<ImmutableHashMap<String, SteelVal>>,
}
impl Engine {
/// Instantiates a raw engine instance. Includes no primitives or prelude.
///
/// # Examples
///
/// ```
/// # extern crate steel;
/// # use steel::steel_vm::engine::Engine;
/// let mut vm = Engine::new_raw();
/// assert!(vm.run("(+ 1 2 3").is_err()); // + is a free identifier
/// ```
pub fn new_raw() -> Self {
Engine {
virtual_machine: VirtualMachineCore::new(),
compiler: Compiler::default(),
constants: None,
}
}
/// Instantiates a new engine instance with all primitive functions enabled.
/// This excludes the prelude and contract files.
///
/// # Examples
///
/// ```
/// # extern crate steel;
/// # use steel::steel_vm::engine::Engine;
/// let mut vm = Engine::new_base();
/// // map is found in the prelude, so this will fail
/// assert!(vm.run(r#"(map (lambda (x) 10) (list 1 2 3 4 5))"#).is_err());
/// ```
#[inline]
pub fn new_base() -> Self {
let mut vm = Engine::new_raw();
// Embed any primitives that we want to use
embed_primitives(&mut vm);
vm
}
#[inline]
pub fn new_sandboxed() -> Self {
let mut vm = Engine::new_raw();
embed_primitives_without_io(&mut vm);
let core_libraries = [crate::stdlib::PRELUDE, crate::stdlib::CONTRACTS];
for core in std::array::IntoIter::new(core_libraries) {
vm.parse_and_execute_without_optimizations(core).unwrap();
}
vm
}
/// Instantiates a new engine instance with all the primitive functions enabled.
/// This is the most general engine entry point, and includes both the contract and
/// prelude files in the root.
///
/// # Examples
///
/// ```
/// # extern crate steel;
/// # use steel::steel_vm::engine::Engine;
/// let mut vm = Engine::new();
/// vm.run(r#"(+ 1 2 3)"#).unwrap();
/// ```
pub fn new() -> Self {
let mut vm = Engine::new_base();
let core_libraries = [
crate::stdlib::PRELUDE,
crate::stdlib::DISPLAY,
crate::stdlib::CONTRACTS,
];
for core in std::array::IntoIter::new(core_libraries) {
vm.parse_and_execute_without_optimizations(core).unwrap();
}
vm
}
/// Consumes the current `Engine` and emits a new `Engine` with the prelude added
/// to the environment. The prelude won't work unless the primitives are also enabled.
///
/// # Examples
///
/// ```
/// # extern crate steel;
/// # use steel::steel_vm::engine::Engine;
/// let mut vm = Engine::new_base().with_prelude().unwrap();
/// vm.run("(+ 1 2 3)").unwrap();
/// ```
pub fn with_prelude(mut self) -> Result<Self> {
let core_libraries = &[
crate::stdlib::PRELUDE,
crate::stdlib::DISPLAY,
crate::stdlib::CONTRACTS,
];
for core in core_libraries {
self.parse_and_execute_without_optimizations(core)?;
}
Ok(self)
}
/// Registers the prelude to the environment of the given Engine.
/// The prelude won't work unless the primitives are also enabled.
///
/// # Examples
///
/// ```
/// # extern crate steel;
/// # use steel::steel_vm::engine::Engine;
/// let mut vm = Engine::new_base();
/// vm.register_prelude().unwrap();
/// vm.run("(+ 1 2 3)").unwrap();
/// ```
pub fn register_prelude(&mut self) -> Result<&mut Self> {
let core_libraries = &[
crate::stdlib::PRELUDE,
crate::stdlib::DISPLAY,
crate::stdlib::CONTRACTS,
];
for core in core_libraries {
self.parse_and_execute_without_optimizations(core)?;
}
Ok(self)
}
/// Emits a program with path information embedded for error messaging.
pub fn emit_program_with_path(&mut self, expr: &str, path: PathBuf) -> Result<Program> {
let constants = self.constants();
self.compiler.compile_program(expr, Some(path), constants)
}
/// Emits a program for a given `expr` directly without providing any error messaging for the path.
pub fn emit_program(&mut self, expr: &str) -> Result<Program> {
let constants = self.constants();
self.compiler.compile_program(expr, None, constants)
}
// Attempts to disassemble the given expression into a series of bytecode dumps
pub fn disassemble(&mut self, expr: &str) -> Result<String> {
let constants = self.constants();
self.compiler
.emit_debug_instructions(expr, constants)
.map(|x| {
x.into_iter()
.map(|i| crate::core::instructions::disassemble(&i))
.join("\n\n")
})
}
/// Execute bytecode with a constant map directly.
pub fn execute(
&mut self,
bytecode: Rc<[DenseInstruction]>,
constant_map: &ConstantMap,
) -> Result<SteelVal> {
self.virtual_machine
.execute(bytecode, constant_map, UseCallback, ApplyContract)
}
/// Emit the bytecode directly, with a path provided.
pub fn emit_instructions_with_path(
&mut self,
exprs: &str,
path: PathBuf,
) -> Result<Vec<Vec<DenseInstruction>>> {
let constants = self.constants();
self.compiler
.emit_instructions(exprs, Some(path), constants)
}
/// Emit instructions directly, without a path for error messaging.
pub fn emit_instructions(&mut self, exprs: &str) -> Result<Vec<Vec<DenseInstruction>>> {
let constants = self.constants();
self.compiler.emit_instructions(exprs, None, constants)
}
/// Execute a program directly, returns a vector of `SteelVal`s corresponding to each expr in the `Program`.
pub fn execute_program(&mut self, program: Program) -> Result<Vec<SteelVal>> {
self.virtual_machine
.execute_program(program, UseCallback, ApplyContract)
}
/// Emit the unexpanded AST
pub fn emit_ast_to_string(expr: &str) -> Result<String> {
let mut intern = HashMap::new();
let parsed: std::result::Result<Vec<ExprKind>, ParseError> =
Parser::new(expr, &mut intern).collect();
let parsed = parsed?;
Ok(parsed.into_iter().map(|x| x.to_pretty(60)).join("\n\n"))
}
/// Emit the fully expanded AST
pub fn emit_fully_expanded_ast_to_string(&mut self, expr: &str) -> Result<String> {
let constants = self.constants();
Ok(self
.compiler
.emit_expanded_ast(expr, constants)?
.into_iter()
.map(|x| x.to_pretty(60))
.join("\n\n"))
}
/// Registers an external value of any type as long as it implements [`FromSteelVal`](crate::rvals::FromSteelVal) and
/// [`IntoSteelVal`](crate::rvals::IntoSteelVal). This method does the coercion to embed the type into the `Engine`'s
/// environment with the name `name`. This function can fail only if the conversion from `T` to [`SteelVal`](crate::rvals::SteelVal) fails.
///
/// # Examples
///
/// ```
/// # extern crate steel;
/// # use steel::steel_vm::engine::Engine;
/// let mut vm = Engine::new();
/// let external_value = "hello-world".to_string();
/// vm.register_external_value("hello-world", external_value).unwrap();
/// vm.run("hello-world").unwrap(); // Will return the string
/// ```
pub fn register_external_value<T: FromSteelVal + IntoSteelVal>(
&mut self,
name: &str,
value: T,
) -> Result<&mut Self> {
let converted = value.into_steelval()?;
Ok(self.register_value(name, converted))
}
/// Registers a [`SteelVal`](crate::rvals::SteelVal) under the name `name` in the `Engine`'s internal environment.
///
/// # Examples
/// ```
/// # extern crate steel;
/// # use steel::steel_vm::engine::Engine;
/// use steel::rvals::SteelVal;
///
/// let mut vm = Engine::new();
/// let external_value = SteelVal::StringV("hello-world".to_string().into());
/// vm.register_value("hello-world", external_value);
/// vm.run("hello-world").unwrap(); // Will return the string
/// ```
pub fn register_value(&mut self, name: &str, value: SteelVal) -> &mut Self {
let idx = self.compiler.register(name);
self.virtual_machine.insert_binding(idx, value);
self
}
/// Registers multiple values at once
pub fn register_values(
&mut self,
values: impl Iterator<Item = (String, SteelVal)>,
) -> &mut Self {
for (name, value) in values {
self.register_value(name.as_str(), value);
}
self
}
/// Registers a predicate for a given type. When embedding external values, it is convenient
/// to be able to have a predicate to test if the given value is the specified type.
/// In order to be registered, a type must implement [`FromSteelVal`](crate::rvals::FromSteelVal)
/// and [`IntoSteelVal`](crate::rvals::IntoSteelVal)
///
/// # Examples
///
/// ```
/// # extern crate steel;
/// # use steel::steel_vm::engine::Engine;
/// use steel::steel_vm::register_fn::RegisterFn;
/// fn foo() -> usize {
/// 10
/// }
///
/// let mut vm = Engine::new();
/// vm.register_fn("foo", foo);
///
/// vm.run(r#"(foo)"#).unwrap(); // Returns vec![10]
/// ```
pub fn register_type<T: FromSteelVal + IntoSteelVal>(
&mut self,
predicate_name: &'static str,
) -> &mut Self {
let f = move |args: &[SteelVal]| -> Result<SteelVal> {
if args.len() != 1 {
stop!(ArityMismatch => format!("{} expected 1 argument, got {}", predicate_name, args.len()));
}
Ok(SteelVal::BoolV(T::from_steelval(args[0].clone()).is_ok()))
};
self.register_value(predicate_name, SteelVal::BoxedFunction(Rc::new(f)))
}
/// Registers a callback function. If registered, this callback will be called on every instruction
/// Allows for the introspection of the currently running process. The callback here takes as an argument the current instruction number.
///
/// # Examples
///
/// ```
/// # extern crate steel;
/// # use steel::steel_vm::engine::Engine;
/// let mut vm = Engine::new();
/// vm.on_progress(|count| {
/// // parameter is 'usize' - number of instructions performed up to this point
/// if count % 1000 == 0 {
/// // print out a progress log every 1000 operations
/// println!("Number of instructions up to this point: {}", count);
/// // Returning false here would quit the evaluation of the function
/// return true;
/// }
/// true
/// });
/// // This should end with "Number of instructions up to this point: 12000"
/// vm.run(
/// r#"
/// (define (loop x)
/// (if (equal? x 1000)
/// x
/// (loop (+ x 1))))
/// (loop 0)
/// "#,
/// )
/// .unwrap();
/// ```
pub fn on_progress<FN: Fn(usize) -> bool + 'static>(&mut self, callback: FN) -> &mut Self {
self.virtual_machine.on_progress(callback);
self
}
/// Extracts a value with the given identifier `name` from the internal environment.
/// If a script calculated some series of bound values, then it can be extracted this way.
/// This will return the [`SteelVal`](crate::rvals::SteelVal), not the underlying data.
/// To unwrap the value, use the [`extract`](crate::steel_vm::engine::Engine::extract) method and pass the type parameter.
///
/// The function will return an error if the `name` is not currently bound in the `Engine`'s internal environment.
///
/// # Examples
///
/// ```
/// # extern crate steel;
/// # use steel::steel_vm::engine::Engine;
/// use steel::rvals::SteelVal;
/// let mut vm = Engine::new();
/// vm.run("(define a 10)").unwrap();
/// assert_eq!(vm.extract_value("a").unwrap(), SteelVal::IntV(10));
/// ```
pub fn extract_value(&self, name: &str) -> Result<SteelVal> {
let idx = self.compiler.get_idx(name).ok_or_else(throw!(
Generic => format!("free identifier: {} - identifier given cannot be found in the global environment", name)
))?;
self.virtual_machine.extract_value(idx)
.ok_or_else(throw!(
Generic => format!("free identifier: {} - identifier given cannot be found in the global environment", name)
))
}
/// Extracts a value with the given identifier `name` from the internal environment, and attempts to coerce it to the
/// given type. This will return an error if the `name` is not currently bound in the `Engine`'s internal environment, or
/// if the type passed in does not match the value (and thus the coercion using [`FromSteelVal`](crate::rvals::FromSteelVal) fails)
///
/// # Examples
///
/// ```
/// # extern crate steel;
/// # use steel::steel_vm::engine::Engine;
/// let mut vm = Engine::new();
/// vm.run("(define a 10)").unwrap();
/// assert_eq!(vm.extract::<usize>("a").unwrap(), 10);
/// ```
pub fn extract<T: FromSteelVal>(&self, name: &str) -> Result<T> {
T::from_steelval(self.extract_value(name)?)
}
/// Execute a program given as the `expr`, and computes a `Vec<SteelVal>` corresponding to the output of each expression given.
/// This method contains no path information used for error reporting, and simply runs the expression as is. Modules will be
/// imported with the root directory as wherever the executable was started.
/// Any parsing, compilation, or runtime error will be reflected here, ideally with span information as well. The error will not
/// be reported automatically.
///
/// # Examples
///
/// ```
/// # extern crate steel;
/// # use steel::steel_vm::engine::Engine;
/// use steel::rvals::SteelVal;
/// let mut vm = Engine::new();
/// let output = vm.run("(+ 1 2) (* 5 5) (- 10 5)").unwrap();
/// assert_eq!(output, vec![SteelVal::IntV(3), SteelVal::IntV(25), SteelVal::IntV(5)]);
/// ```
pub fn run(&mut self, expr: &str) -> Result<Vec<SteelVal>> {
let constants = self.constants();
let program = self.compiler.compile_program(expr, None, constants)?;
self.virtual_machine
.execute_program(program, UseCallback, ApplyContract)
}
/// Execute a program, however do not run any callbacks as registered with `on_progress`.
pub fn run_without_callbacks(&mut self, expr: &str) -> Result<Vec<SteelVal>> {
let constants = self.constants();
let program = self.compiler.compile_program(expr, None, constants)?;
self.virtual_machine
.execute_program(program, DoNotUseCallback, ApplyContract)
}
/// Execute a program (as per [`run`](crate::steel_vm::engine::Engine::run)), however do not enforce any contracts. Any contracts that are added are not
/// enforced.
///
/// # Examples
///
/// ```
/// # extern crate steel;
/// # use steel::steel_vm::engine::Engine;
/// use steel::rvals::SteelVal;
/// let mut vm = Engine::new();
/// let output = vm.run_without_contracts(r#"
/// (define/contract (foo x)
/// (->/c integer? any/c)
/// "hello world")
///
/// (foo "bad-input")
/// "#).unwrap();
/// ```
pub fn run_without_contracts(&mut self, expr: &str) -> Result<Vec<SteelVal>> {
let constants = self.constants();
let program = self.compiler.compile_program(expr, None, constants)?;
self.virtual_machine
.execute_program(program, UseCallback, DoNotApplyContracts)
}
/// Execute a program without invoking any callbacks, or enforcing any contract checking
pub fn run_without_callbacks_or_contracts(&mut self, expr: &str) -> Result<Vec<SteelVal>> {
let constants = self.constants();
let program = self.compiler.compile_program(expr, None, constants)?;
self.virtual_machine
.execute_program(program, DoNotUseCallback, DoNotApplyContracts)
}
/// Similar to [`run`](crate::steel_vm::engine::Engine::run), however it includes path information
/// for error reporting purposes.
pub fn run_with_path(&mut self, expr: &str, path: PathBuf) -> Result<Vec<SteelVal>> {
let constants = self.constants();
let program = self.compiler.compile_program(expr, Some(path), constants)?;
self.virtual_machine
.execute_program(program, UseCallback, ApplyContract)
}
pub fn parse_and_execute_without_optimizations(&mut self, expr: &str) -> Result<Vec<SteelVal>> {
let constants = self.constants();
let program = self.compiler.compile_program(expr, None, constants)?;
self.virtual_machine
.execute_program(program, UseCallback, ApplyContract)
}
pub fn parse_and_execute(&mut self, expr: &str) -> Result<Vec<SteelVal>> {
self.parse_and_execute_without_optimizations(expr)
}
// Read in the file from the given path and execute accordingly
// Loads all the functions in from the given env
// pub fn parse_and_execute_from_path<P: AsRef<Path>>(
// &mut self,
// path: P,
// ) -> Result<Vec<SteelVal>> {
// let mut file = std::fs::File::open(path)?;
// let mut exprs = String::new();
// file.read_to_string(&mut exprs)?;
// self.parse_and_execute(exprs.as_str(), )
// }
pub fn parse_and_execute_from_path<P: AsRef<Path>>(
&mut self,
path: P,
) -> Result<Vec<SteelVal>> {
let path_buf = PathBuf::from(path.as_ref());
let mut file = std::fs::File::open(path)?;
let mut exprs = String::new();
file.read_to_string(&mut exprs)?;
self.run_with_path(exprs.as_str(), path_buf)
}
// TODO this does not take into account the issues with
// people registering new functions that shadow the original one
fn constants(&mut self) -> ImmutableHashMap<String, SteelVal> {
if let Some(hm) = self.constants.clone() {
hm
} else {
let mut hm = ImmutableHashMap::new();
for constant in CONSTANTS {
if let Ok(v) = self.extract_value(constant) {
hm.insert(constant.to_string(), v);
}
}
self.constants = Some(hm.clone());
hm
}
}
}
#[cfg(test)]
mod on_progress_tests {
use super::*;
use std::cell::Cell;
use std::rc::Rc;
#[test]
fn count_every_thousand() {
let mut vm = Engine::new();
let external_count = Rc::new(Cell::new(0));
let embedded_count = Rc::clone(&external_count);
vm.on_progress(move |count| {
// parameter is 'usize' - number of instructions performed up to this point
if count % 1000 == 0 {
// print out a progress log every 1000 operations
println!("Number of instructions up to this point: {}", count);
embedded_count.set(embedded_count.get() + 1);
// Returning false here would quit the evaluation of the function
return true;
}
true
});
// This should end with "Number of instructions up to this point: 4000"
vm.run(
r#"
(define (loop x)
(if (equal? x 1000)
x
(loop (+ x 1))))
(displayln (loop 0))
"#,
)
.unwrap();
assert_eq!(external_count.get(), 4);
}
}
| true |
3d788e08b89a857d4e64b234e91d8255f6986b3f
|
Rust
|
gnoliyil/fuchsia
|
/src/fonts/manifest/src/v1_to_v2.rs
|
UTF-8
| 13,234 | 2.65625 | 3 |
[
"BSD-2-Clause"
] |
permissive
|
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//! Utilities for conversion from Font Manifest v1 to v2.
use {
crate::{v2, Family as FamilyV1, Font as FontV1, FontsManifest as FontsManifestV1},
anyhow::{format_err, Error},
itertools::Itertools,
std::{
convert::{From, TryFrom},
path::{Path, PathBuf},
},
};
impl TryFrom<FontsManifestV1> for v2::FontsManifest {
type Error = Error;
/// Converts a v1 [`manifest::FontsManifest`] to a v2 [`manifest::v2::Manifest`].
///
/// This is purely an in-memory conversion, and does not load character sets for local files.
fn try_from(old: FontsManifestV1) -> Result<v2::FontsManifest, Error> {
// In v2, whether a font is a `fallback` is specified not per font family, but in an
// explicit ordered list.
// We capture each v1 family's `fallback` property for later use.
let families_and_fallbacks: Result<Vec<(v2::Family, bool)>, _> = old
.families
.iter()
.map(|v1_family| {
v2::Family::try_from(v1_family).map(|v2_family| (v2_family, v1_family.fallback))
})
.collect();
let families_and_fallbacks = families_and_fallbacks?;
// For every v1 family that's `fallback: true`, for every asset, for every typeface, add the
// typeface to the v2 `fallback_chain`.
let fallback_chain: Vec<v2::TypefaceId> = families_and_fallbacks
.iter()
.filter(|(_, is_fallback)| *is_fallback)
.flat_map(|(family, _)| {
family.assets.iter().flat_map(|asset| {
asset.typefaces.iter().map(move |typeface| v2::TypefaceId {
file_name: asset.file_name.clone(),
index: typeface.index,
})
})
})
.collect();
let families = families_and_fallbacks.into_iter().map(|(family, _)| family).collect();
Ok(v2::FontsManifest { families, fallback_chain, settings: v2::Settings::default() })
}
}
impl TryFrom<&FamilyV1> for v2::Family {
type Error = Error;
/// Converts a v1 [`manifest::Family`] to a [`manifest::v2::Family`].
///
/// Assumes that all v1 fonts are local files.
fn try_from(old: &FamilyV1) -> Result<v2::Family, Error> {
let assets: Result<Vec<v2::Asset>, _> = old
.fonts
.iter()
.group_by(|font| &font.asset)
.into_iter()
.map(|(asset_path, font_group)| group_fonts_into_assets(asset_path, font_group))
.collect();
// v1 manifests only allow plain aliases, without any typeface property overrides.
let aliases = match &old.aliases {
None => vec![],
Some(aliases) => vec![v2::FontFamilyAliasSet::without_overrides(aliases)?],
};
Ok(v2::Family {
name: old.family.clone(),
aliases,
generic_family: old.generic_family.clone(),
assets: assets?,
})
}
}
/// Groups v1 [`manifest::Font`]s that share a single path into a v2 [`manifest::v2::Asset`] with
/// one or more [`manifest::v2::Typeface`]s.
///
/// Params:
/// - `asset_path`: The path to the font file
/// - `font_group`: Iterator for all the v1 `Font`s that share the same `asset_path`
fn group_fonts_into_assets<'a>(
asset_path: &PathBuf,
font_group: impl Iterator<Item = &'a FontV1>,
) -> Result<v2::Asset, Error> {
// We unwrap PathBuf to_str conversions because we should only be reading valid Unicode-encoded
// paths from JSON manifests.
let file_name: String = asset_path
.file_name()
.ok_or_else(|| format_err!("Invalid path: {:?}", asset_path))?
.to_str()
.ok_or_else(|| format_err!("Invalid path: {:?}", asset_path))?
.to_string();
// If the file is in the package root, then the parent directory will be blank.
let directory: PathBuf =
asset_path.parent().map_or_else(|| PathBuf::from(""), Path::to_path_buf);
// Assuming that all v1 fonts are local files.
Ok(v2::Asset {
file_name,
location: v2::AssetLocation::LocalFile(v2::LocalFileLocator { directory }),
typefaces: font_group.map(font_to_typeface).collect(),
})
}
/// Convert a v1 [`manifest::Font`] to a v2 [`v2::Typeface`].
fn font_to_typeface(font: &FontV1) -> v2::Typeface {
v2::Typeface {
index: font.index,
languages: font.languages.clone(),
style: v2::Style { slant: font.slant, weight: font.weight, width: font.width },
code_points: font.code_points.clone(),
postscript_name: None,
full_name: None,
}
}
#[cfg(test)]
mod tests {
use {
super::*,
char_set::CharSet,
fidl_fuchsia_fonts::{GenericFontFamily, Slant, Width},
};
#[test]
fn test_v1_to_v2() -> Result<(), Error> {
let old = FontsManifestV1 {
families: vec![
FamilyV1 {
family: "FamilyA".to_string(),
aliases: Some(vec!["Family A".to_string(), "A Family".to_string()]),
fonts: vec![
FontV1 {
asset: PathBuf::from("path/to/FamilyA-ExtraBold-Condensed.ttf"),
index: 0,
slant: Slant::Upright,
weight: 800,
width: Width::Condensed,
languages: vec!["en-US".to_string()],
package: None,
code_points: CharSet::new(vec![0x1, 0x2, 0x3, 0x7, 0x8, 0x9, 0x100]),
},
FontV1 {
asset: PathBuf::from("path/to/FamilyA-ExtraLight.ttf"),
index: 0,
slant: Slant::Upright,
weight: 200,
width: Width::Normal,
languages: vec!["en-US".to_string()],
package: None,
code_points: CharSet::new(vec![
0x11, 0x12, 0x13, 0x17, 0x18, 0x19, 0x100,
]),
},
],
fallback: true,
generic_family: Some(GenericFontFamily::SansSerif),
},
FamilyV1 {
family: "FamilyB".to_string(),
aliases: Some(vec!["Family B".to_string(), "B Family".to_string()]),
fonts: vec![
FontV1 {
asset: PathBuf::from("FamilyB.ttc"),
index: 0,
slant: Slant::Upright,
weight: 800,
width: Width::Condensed,
languages: vec!["en-US".to_string()],
package: None,
code_points: CharSet::new(vec![0x1, 0x2, 0x3, 0x7, 0x8, 0x9, 0x100]),
},
FontV1 {
asset: PathBuf::from("FamilyB.ttc"),
index: 1,
slant: Slant::Upright,
weight: 200,
width: Width::Normal,
languages: vec!["zh-Hant".to_string()],
package: None,
code_points: CharSet::new(vec![
0x11, 0x12, 0x13, 0x17, 0x18, 0x19, 0x100,
]),
},
],
fallback: false,
generic_family: None,
},
],
};
let expected = v2::FontsManifest {
families: vec![
v2::Family {
name: "FamilyA".to_string(),
aliases: vec![v2::FontFamilyAliasSet::without_overrides(vec![
"Family A", "A Family",
])?],
generic_family: Some(GenericFontFamily::SansSerif),
assets: vec![
v2::Asset {
file_name: "FamilyA-ExtraBold-Condensed.ttf".to_string(),
location: v2::AssetLocation::LocalFile(v2::LocalFileLocator {
directory: PathBuf::from("path/to"),
}),
typefaces: vec![v2::Typeface {
index: 0,
languages: vec!["en-US".to_string()],
style: v2::Style {
slant: Slant::Upright,
weight: 800,
width: Width::Condensed,
},
code_points: CharSet::new(vec![
0x1, 0x2, 0x3, 0x7, 0x8, 0x9, 0x100,
]),
postscript_name: None,
full_name: None,
}],
},
v2::Asset {
file_name: "FamilyA-ExtraLight.ttf".to_string(),
location: v2::AssetLocation::LocalFile(v2::LocalFileLocator {
directory: PathBuf::from("path/to"),
}),
typefaces: vec![v2::Typeface {
index: 0,
languages: vec!["en-US".to_string()],
style: v2::Style {
slant: Slant::Upright,
weight: 200,
width: Width::Normal,
},
code_points: CharSet::new(vec![
0x11, 0x12, 0x13, 0x17, 0x18, 0x19, 0x100,
]),
postscript_name: None,
full_name: None,
}],
},
],
},
v2::Family {
name: "FamilyB".to_string(),
aliases: vec![v2::FontFamilyAliasSet::without_overrides(vec![
"Family B", "B Family",
])?],
generic_family: None,
assets: vec![v2::Asset {
file_name: "FamilyB.ttc".to_string(),
location: v2::AssetLocation::LocalFile(v2::LocalFileLocator {
directory: PathBuf::from(""),
}),
typefaces: vec![
v2::Typeface {
index: 0,
languages: vec!["en-US".to_string()],
style: v2::Style {
slant: Slant::Upright,
weight: 800,
width: Width::Condensed,
},
code_points: CharSet::new(vec![
0x1, 0x2, 0x3, 0x7, 0x8, 0x9, 0x100,
]),
postscript_name: None,
full_name: None,
},
v2::Typeface {
index: 1,
languages: vec!["zh-Hant".to_string()],
style: v2::Style {
slant: Slant::Upright,
weight: 200,
width: Width::Normal,
},
code_points: CharSet::new(vec![
0x11, 0x12, 0x13, 0x17, 0x18, 0x19, 0x100,
]),
postscript_name: None,
full_name: None,
},
],
}],
},
],
fallback_chain: vec![
v2::TypefaceId {
file_name: "FamilyA-ExtraBold-Condensed.ttf".to_string(),
index: 0,
},
v2::TypefaceId { file_name: "FamilyA-ExtraLight.ttf".to_string(), index: 0 },
],
settings: v2::Settings::default(),
};
assert_eq!(v2::FontsManifest::try_from(old)?, expected);
Ok(())
}
}
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.