text stringlengths 8 4.13M |
|---|
#![allow(dead_code)]
/// Calculate the standard deviation (population) of a slice
#[inline]
pub fn stddev(slice: &[f32]) -> f32 {
let (sum, len) = slice.iter().fold((0.0, 0), |acc, x| (acc.0 + x, acc.1 + 1));
let n = len as f32;
let mean = sum / n;
(slice.iter().fold(0.0f32, |acc, x| acc + (x - mean).powi(2)) / n).sqrt()
}
/// Calculate the coefficient of variation (population) of a slice
#[inline]
pub fn coefficient_variation(slice: &[f32]) -> f32 {
let (sum, len) = slice.iter().fold((0.0, 0), |acc, x| (acc.0 + x, acc.1 + 1));
let n = len as f32;
let mean = sum / n;
(slice.iter().fold(0.0f32, |acc, x| acc + (x - mean).powi(2)) / n).sqrt() / mean
}
|
extern crate drop_guard;
use drop_guard::DropGuard;
fn main() {
let s = String::from("a commonString");
let mut s = DropGuard::new(s, |final_string| println!("s became {} at last", final_string));
// much code and time passes by ...
*s = "a rainbow".to_string();
// by the end of this function the String will have become a rainbow
}
|
pub mod tabs;
pub mod token;
pub use tabs::*;
pub use token::*;
|
//! RZBackup is a library, and a collection of binaries, implementing a partial
//! clone of [ZBackup](http://zbackup.org).
//!
//! The main class is `Repository`, which has static methods for opening and
//! accessing data from a ZBackup repository. The `restore` method will restore
//! a backup to a provided `Writer`.
//!
//! `Repository` implements `Clone` and is fully thread-safe. It performs
//! parallel decompression operations using a background thread pool and it has
//! a three-layer cache. The parameters for cache sizes and number of threads
//! are fully configurable.
//!
//! There is also a `RandomAccess` class which implements `Seek` and `Read`, and
//! can be constructed from a `Repository` and the name of a backup.
#![ allow (unused_parens) ]
#[ macro_use ]
extern crate lazy_static;
#[ macro_use ]
extern crate output;
extern crate adler32;
extern crate byteorder;
extern crate clap;
extern crate crypto as rust_crypto;
extern crate errno;
extern crate futures;
extern crate futures_cpupool;
extern crate libc;
extern crate lru_cache;
extern crate minilzo;
extern crate num_cpus;
extern crate protobuf;
extern crate rand;
extern crate regex;
extern crate rustc_serialize;
#[ doc (hidden) ]
#[ macro_use ]
pub mod misc;
#[ doc (hidden) ]
pub mod client;
#[ doc (hidden) ]
pub mod commands;
#[ doc (hidden) ]
pub mod convert;
#[ doc (hidden) ]
pub mod server;
mod compress;
mod metadata;
mod zbackup;
pub use metadata::*;
pub use misc::AtomicFileWriter;
pub use zbackup::crypto;
pub use zbackup::data::*;
pub use zbackup::disk_format;
pub use zbackup::randaccess::RandomAccess;
pub use zbackup::repository::Repository as ZBackupRepository;
pub use zbackup::repository::RepositoryConfig as ZBackupRepositoryConfig;
pub use server::run_server;
// ex: noet ts=f filetype=rust
|
use std::ffi::CString;
use raw;
use gs::texture;
pub struct ImageFile {
raw: *mut raw::ImageFile
}
impl ImageFile {
pub fn open(path: &str) -> ImageFile {
let path = CString::new(path).expect("string contains null");
unsafe {
ImageFile {
raw: raw::rust_gs_image_file_open(path.as_ptr())
}
}
}
pub fn texture(&self) -> texture::Ref {
unsafe {
let texture = raw::rust_gs_image_file_texture(self.raw);
texture::Ref::from_raw(texture)
}
}
pub fn width(&self) -> u32 {
unsafe {
raw::rust_gs_image_file_width(self.raw)
}
}
pub fn height(&self) -> u32 {
unsafe {
raw::rust_gs_image_file_height(self.raw)
}
}
}
impl Drop for ImageFile {
fn drop(&mut self) {
unsafe {
raw::rust_gs_image_file_destroy(self.raw);
}
}
}
|
use nails_derive::Preroute;
#[derive(Preroute)]
#[nails(path = "/api/posts/{id}")]
struct GetPostRequest {
#[nails(path = "idd")]
id: String,
}
#[derive(Preroute)]
#[nails(path = "/api/posts/{id}")]
struct GetPostRequest2 {
#[nails(path)]
idd: String,
}
fn main() {}
|
fn add_string(x: &str,y: &str) -> String{
let mut s = String::new();
let num = x.chars().count();
for _i in 0..num {
s.push(x.chars().nth(_i).unwrap());
s.push(y.chars().nth(_i).unwrap());
}
s.to_string()
}
fn main(){
let s1 = String::from("パトカー");
let s2 = String::from("タクシー");
println!("{}",add_string(&s1,&s2));
}
|
#[doc = "Reader of register ICENABLER5"]
pub type R = crate::R<u32, super::ICENABLER5>;
#[doc = "Writer for register ICENABLER5"]
pub type W = crate::W<u32, super::ICENABLER5>;
#[doc = "Register ICENABLER5 `reset()`'s with value 0"]
impl crate::ResetValue for super::ICENABLER5 {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `ICENABLER5`"]
pub type ICENABLER5_R = crate::R<u32, u32>;
#[doc = "Write proxy for field `ICENABLER5`"]
pub struct ICENABLER5_W<'a> {
w: &'a mut W,
}
impl<'a> ICENABLER5_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u32) -> &'a mut W {
self.w.bits = (self.w.bits & !0xffff_ffff) | ((value as u32) & 0xffff_ffff);
self.w
}
}
impl R {
#[doc = "Bits 0:31 - interrupt clear-enable 0"]
#[inline(always)]
pub fn icenabler5(&self) -> ICENABLER5_R {
ICENABLER5_R::new((self.bits & 0xffff_ffff) as u32)
}
}
impl W {
#[doc = "Bits 0:31 - interrupt clear-enable 0"]
#[inline(always)]
pub fn icenabler5(&mut self) -> ICENABLER5_W {
ICENABLER5_W { w: self }
}
}
|
//
// Copyright 2020 The Project Oak Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
use crate::proto::oak::examples::trusted_database::{
GetPointOfInterestRequest, GetPointOfInterestResponse, ListPointsOfInterestRequest,
ListPointsOfInterestResponse, Location, PointOfInterestMap, TrustedDatabase,
TrustedDatabaseDispatcher, TrustedDatabaseInit,
};
use log::{debug, error, warn};
use oak::grpc;
// Error messages.
const NO_LOCATION_ERROR: &str = "Location is not specified";
const ID_NOT_FOUND_ERROR: &str = "ID not found";
const EMPTY_DATABASE_ERROR: &str = "Empty database";
/// Oak Handler Node that contains a copy of the database and handles client requests.
#[derive(Default)]
pub struct Handler {
points_of_interest: PointOfInterestMap,
}
impl oak::WithInit for Handler {
type Init = TrustedDatabaseInit;
fn create(init: Self::Init) -> Self {
oak::logger::init(init.log_sender.unwrap(), log::Level::Debug).unwrap();
let points_of_interest = init.points_of_interest.expect("Couldn't receive database");
Self { points_of_interest }
}
}
/// A gRPC service implementation for the Private Information Retrieval example.
impl TrustedDatabase for Handler {
// Find Point Of Interest based on id.
fn get_point_of_interest(
&mut self,
request: GetPointOfInterestRequest,
) -> grpc::Result<GetPointOfInterestResponse> {
debug!("Received request: {:?}", request);
match self.points_of_interest.entries.get(&request.id) {
Some(point) => {
debug!("Found Point Of Interest: {:?}", point);
Ok(GetPointOfInterestResponse {
point_of_interest: Some(point.clone()),
})
}
None => {
let err = grpc::build_status(grpc::Code::NotFound, ID_NOT_FOUND_ERROR);
error!("{:?}", err);
Err(err)
}
}
}
/// Find the nearest Point Of Interest based on linear search in the database.
fn list_points_of_interest(
&mut self,
request: ListPointsOfInterestRequest,
) -> grpc::Result<ListPointsOfInterestResponse> {
error!("Received request: {:?}", request);
let request_location = request.location.ok_or_else(|| {
let err = grpc::build_status(grpc::Code::InvalidArgument, NO_LOCATION_ERROR);
warn!("{:?}", err);
err
})?;
let nearest_point = self.points_of_interest.entries.values().fold(
(None, f32::MAX),
|(current_closest_point, current_closest_point_distance), point| {
let point_location = point
.location
.as_ref()
.expect("Non-existing location")
.clone();
let distance = distance(request_location.clone(), point_location);
if distance < current_closest_point_distance {
(Some(point.clone()), distance)
} else {
(current_closest_point, current_closest_point_distance)
}
},
);
match nearest_point.0 {
Some(point) => {
debug!("Found the nearest Point Of Interest: {:?}", point);
Ok(ListPointsOfInterestResponse {
point_of_interest: Some(point),
})
}
None => {
let err = grpc::build_status(grpc::Code::Internal, EMPTY_DATABASE_ERROR);
error!("{:?}", err);
Err(err)
}
}
}
}
// Earth radius in kilometers.
const EARTH_RADIUS: f32 = 6371.0_f32;
/// Returns a distance (in kilometers) between two locations using the Haversine formula
/// (ignoring height variations):
/// https://en.wikipedia.org/wiki/Haversine_formula
pub fn distance(first: Location, second: Location) -> f32 {
let first_latitude_radians = first.latitude_degrees.to_radians();
let second_latitude_radians = second.latitude_degrees.to_radians();
let latitude_difference_radians =
(first.latitude_degrees - second.latitude_degrees).to_radians();
let longitude_difference_radians =
(first.longitude_degrees - second.longitude_degrees).to_radians();
let central_angle = 2.0
* ((latitude_difference_radians / 2.0).sin().powi(2)
+ (first_latitude_radians.cos()
* second_latitude_radians.cos()
* (longitude_difference_radians / 2.0).sin().powi(2)))
.sqrt()
.asin();
// Compute distance.
EARTH_RADIUS * central_angle
}
oak::entrypoint_command_handler_init!(handler => Handler);
oak::impl_dispatcher!(impl Handler : TrustedDatabaseDispatcher);
|
use crate::ray::Ray;
use crate::vec3::Vec3;
#[derive(Debug, Clone, Copy)]
pub struct HitRecord {
pub p: Vec3,
pub normal: Vec3,
pub t: f64,
pub front_face: bool,
}
impl HitRecord {
pub fn new(ray: &Ray, p: Vec3, outward_normal: &Vec3, t: f64) -> Self {
let front_face = ray.direction.dot(outward_normal) < 0.0;
let normal = match front_face {
true => outward_normal.clone(),
false => -1.0 * outward_normal,
};
Self {
p,
normal,
t,
front_face,
}
}
}
|
#[multiversion::multiversion(targets("x86_64+avx2"))]
fn sum(input: impl AsRef<[i64]>) -> i64 {
input.as_ref().iter().sum()
}
#[test]
fn impl_trait() {
assert_eq!(sum([0, 1, 2, 3]), 6);
}
|
// reimplementation of <https://www.sfml-dev.org/documentation/2.5.1/classsf_1_1View.php>
pub struct SfView {
pub center: (f32, f32),
pub size: (f32, f32),
pub rotation: f32,
}
#[rustfmt::skip]
pub const OPENGL_TO_WGPU_MATRIX4: cgmath::Matrix4<f32> = cgmath::Matrix4::new(
1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 0.5, 0.0,
0.0, 0.0, 0.5, 1.0,
);
impl SfView {
pub fn get_matrix4(&self) -> cgmath::Matrix4<f32> {
// https://github.com/SFML/SFML/blob/master/src/SFML/Graphics/View.cpp#L198
use cgmath::Angle;
let rotation = self.rotation;
let center = self.center;
let size = self.size;
let angle = rotation * std::f32::consts::PI / 180f32; // in radians now
let cosine = cgmath::Rad::cos(cgmath::Rad(angle));
let sine = cgmath::Rad::sin(cgmath::Rad(angle));
let tx = -center.0 * cosine - center.1 * sine + center.0;
let ty = center.0 * sine - center.1 * cosine + center.1;
let a = 2f32 / size.0;
let b = -2f32 / size.1;
let c = -a * center.0;
let d = -b * center.1;
// note: SFML matrices are row-major, but cgmath is column-major
#[rustfmt::skip]
let m4 = cgmath::Matrix4::new(
a*cosine, -b*sine, 0f32, 0f32,
a*sine, b*cosine, 0f32, 0f32,
0f32, 0f32, 1f32, 0f32,
a*tx+c, b*ty+d, 0f32, 1f32,
);
m4
}
}
|
pub(super) mod arithmetic;
pub(super) mod branch;
pub(super) mod data_transfer;
pub(super) mod io;
pub(super) mod logical;
pub(super) mod special;
pub(super) mod stack;
|
use ast::*;
use linked_hash_map::LinkedHashMap;
#[derive(Serialize, Deserialize)]
#[serde(untagged)]
pub enum JsonType {
#[serde(rename = "null")] Null,
I(i64),
F(f64),
B(bool),
S(String),
// Any recursive JsonTypes must be Options to support null
A(Vec<JsonType>),
O(LinkedHashMap<String, JsonType>),
}
fn pad(depth: u32) -> String {
(0..depth).map(|_| "\t").collect()
}
pub fn to_go_bson(input: JsonType) -> String {
input.to_go_bson(0)
}
pub trait ToGoBson {
fn to_go_bson(&self, depth: u32) -> String;
}
impl ToGoBson for JsonType {
fn to_go_bson(&self, depth: u32) -> String {
use self::JsonType::*;
match *self {
Null => format!("{}{}", pad(depth), "nil"),
I(i) => format!("{}{}", pad(depth), i.to_string()),
F(f) => format!("{}{}", pad(depth), f.to_string()),
B(b) => format!("{}{}", pad(depth), b.to_string()),
S(ref s) => format!("{}\"{}\"", pad(depth), s),
A(ref v) => {
pad(depth) + "[]interface{}{\n" +
v.iter()
.fold("".to_string(), |acc, ref x| {
acc + x.to_go_bson(depth + 1).as_str() + ",\n"
})
.as_str() + &pad(depth) + "}"
}
O(ref o) => {
pad(depth) + "bson.D{\n" +
o.iter()
.fold("".to_string(), |acc, (ref k, ref v)| {
acc + pad(depth + 1).as_str() + "{\"" + &k + "\",\n" +
&v.to_go_bson(depth + 1) + ",\n" +
&pad(depth + 1) + "}" + ",\n"
})
.as_str() + &pad(depth) + "}"
}
}
}
}
pub trait Convert<T> {
fn convert(self) -> T;
}
pub trait ConvertMatch<T> {
fn convert_match(self) -> T;
}
impl Convert<JsonType> for Expr {
fn convert(self) -> JsonType {
use self::JsonType::*;
match self {
Expr::Null => Null,
Expr::Number(n) => I(n),
Expr::Float(f) => F(f),
Expr::Bool(b) => B(b),
Expr::Str(s) => S(s.replace(r#"\"#, r#""#)),
// Variables introduced by let should have $$ prefixed
Expr::ID(s) => S("$$".to_string() + &s),
// Cols still have $ prefixed, whereas IDs did not
Expr::Col(s) => S(s),
Expr::Cond(c) => c.convert(),
Expr::Switch(sw) => sw.convert(),
Expr::Let(l) => l.convert(),
Expr::Map(m) => m.convert(),
Expr::Filter(f) => f.convert(),
Expr::Reduce(r) => r.convert(),
Expr::Zip(z) => z.convert(),
Expr::App(s, args) => {
O(linked_hash_map![
// check for inArray, we had to use that because in is
// a keyword
"$".to_string() + if s == "inArray" { "in" } else { &s }
=>
if args.len() > 1 {
args.convert()
}
// TODO: Revaluate if we get functions
// that take 0 args.
else {
args.into_iter().nth(0).unwrap().convert()
}
])
}
Expr::Array(arr) => arr.convert(),
Expr::Object(items) => {
let ret: LinkedHashMap<String, JsonType> =
items.into_iter().map(|(k, v)| (k, v.convert())).collect();
O(ret)
}
Expr::Op(..) => panic!("Should not be converting Op, make sure to normalize first"),
Expr::Error => panic!("Should not be converting Error!"),
}
}
}
impl Convert<JsonType> for Vec<Box<Expr>> {
fn convert(self) -> JsonType {
use self::JsonType::*;
let ret: Vec<JsonType> = self.into_iter().map(|e| e.convert()).collect();
A(ret)
}
}
impl Convert<JsonType> for Pipeline {
fn convert(self) -> JsonType {
use self::JsonType::*;
let ret: Vec<JsonType> = self.stages
.into_iter()
.map(|PipelineItem { stage_name, stage }| {
O(linked_hash_map!["$".to_string() + &stage_name => stage.convert()])
})
.collect();
A(ret)
}
}
//
//{
// $cond: {
// if: <boolean-expression>,
// then: <true-case>,
// else: <false-case->
// }
//}
//
impl Convert<JsonType> for Cond {
fn convert(self) -> JsonType {
use self::JsonType::*;
O(linked_hash_map![
"$cond".to_string() =>
O(linked_hash_map![
"if".to_string() => self.cond.convert(),
"then".to_string() => self.then.convert(),
"else".to_string() => self.otherwise.convert()
]
)
])
}
}
//{
// $switch: {
// branches: [
// { case: <expression>, then: <expression> },
// { case: <expression>, then: <expression> },
// ...
// ],
// default: <expression>
// }
//}
//
impl Convert<JsonType> for Switch {
fn convert(self) -> JsonType {
use self::JsonType::*;
let branches: Vec<JsonType> = self.cases
.into_iter()
.map(|(i, t)| {
O(linked_hash_map![
"case".to_string() => i.convert(),
"then".to_string() => t.convert()
])
})
.collect();
let default: JsonType = self.default.convert();
O(linked_hash_map![
"$switch".to_string() =>
O(linked_hash_map![
"branches".to_string() => A(branches),
"default".to_string() => default
]
)
])
}
}
// {
// "$let":
// {
// "vars" : { "var1" : exp1, ...},
// "in" : expr
// }
// }
//
impl Convert<JsonType> for Let {
fn convert(self) -> JsonType {
use self::JsonType::*;
let vars: LinkedHashMap<String, JsonType> = self.assignments
.into_iter()
.map(|(s, e)| (s, e.convert()))
.collect();
let expr: JsonType = self.expr.convert();
O(linked_hash_map![
"$let".to_string() =>
O(linked_hash_map![
"vars".to_string() => JsonType::O(vars),
"in".to_string() => expr
]
)
])
}
}
// {
// "$map":
// {
// "input": expr,
// "as" : string,
// "in" : expr
// }
// }
//
impl Convert<JsonType> for Map {
fn convert(self) -> JsonType {
use self::JsonType::*;
let input: JsonType = self.input.convert();
let ename = S(self.ename);
let expr: JsonType = self.expr.convert();
O(linked_hash_map![
"$map".to_string() =>
O(linked_hash_map![
"input".to_string() => input,
"as".to_string() => ename,
"in".to_string() => expr
]
)
])
}
}
// {
// "$filter":
// {
// "input": expr,
// "as" : string,
// "cond" : expr
// }
// }
//
impl Convert<JsonType> for Filter {
fn convert(self) -> JsonType {
use self::JsonType::*;
let input: JsonType = self.input.convert();
let ename = S(self.ename);
let cond: JsonType = self.cond.convert();
O(linked_hash_map![
"$filter".to_string() =>
O(linked_hash_map![
"input".to_string() => input,
"as".to_string() => ename,
"cond".to_string() => cond
]
)
])
}
}
// {
// "$reduce":
// {
// "input" : expr,
// "initialValue" : expr,
// "in" : expr
// }
// }
//
impl Convert<JsonType> for Reduce {
fn convert(self) -> JsonType {
use self::JsonType::*;
let input: JsonType = self.input.convert();
let init: JsonType = self.init.convert();
let expr: JsonType = self.expr.convert();
O(linked_hash_map![
"$reduce".to_string() =>
O(linked_hash_map![
"input".to_string() => input,
"initialValue".to_string() => init,
"in".to_string() => expr
]
)
])
}
}
// {
// "$zip":
// {
// "inputs" : arrayExp,
// "useLongestLength" : bool,
// "defaults" : arrayExp
// }
// }
//
impl Convert<JsonType> for Zip {
fn convert(self) -> JsonType {
use self::JsonType::*;
let inputs: JsonType = self.inputs.convert();
let longest = B(self.longest);
let defaults: Option<JsonType> = self.defaults.map(|x| x.convert());
O(linked_hash_map![
"$zip".to_string() =>
if self.longest {
O(linked_hash_map![
"inputs".to_string() => inputs,
"useLongestLength".to_string() => longest,
"defaults".to_string() =>
if let Some(def) = defaults {
def
} else {
Null
}
]
)
} else {
O(linked_hash_map![
"inputs".to_string() => inputs
]
)
}
])
}
}
|
use std::fmt::Debug;
use std::sync::Arc;
use crate::prelude::*;
use crate::bxdf::TransportMode;
use crate::interaction::SurfaceInteraction;
use crate::texture::Texture;
mod matte;
pub use self::matte::MatteMaterial;
pub trait Material: Debug {
fn compute_scattering_functions(&self, isect: SurfaceInteraction<'a>, arena: &(), mode: TransportMode, allow_multiple_lobes: bool) -> SurfaceInteraction<'a>;
}
pub fn bump(_si: &SurfaceInteraction<'a>, _t: &Arc<dyn Texture<Float> + Send + Sync>) -> SurfaceInteraction<'a> {
unimplemented!()
}
|
use std::iter::Map;
use crate::{AnyBin, BinSegment, SegmentIterator, StrSegment};
use std::marker::PhantomData;
/// Converts a string segment iterator to a binary segment iterator.
pub struct SegmentIteratorConverter<'a, TInnerIterator, TAnyBin>
where
TInnerIterator: SegmentIterator<StrSegment<'a, TAnyBin>>,
TAnyBin: AnyBin,
{
inner: TInnerIterator,
_phantom1: PhantomData<&'a ()>,
_phantom2: PhantomData<TAnyBin>,
}
impl<'a, TInnerIterator, TAnyBin> SegmentIteratorConverter<'a, TInnerIterator, TAnyBin>
where
TInnerIterator: SegmentIterator<StrSegment<'a, TAnyBin>>,
TAnyBin: AnyBin,
{
pub fn new(string_segment_iterator: TInnerIterator) -> Self {
Self {
inner: string_segment_iterator,
_phantom1: Default::default(),
_phantom2: Default::default(),
}
}
}
impl<'a, TInnerIterator, TAnyBin> SegmentIterator<BinSegment<'a, TAnyBin>>
for SegmentIteratorConverter<'a, TInnerIterator, TAnyBin>
where
TInnerIterator: SegmentIterator<StrSegment<'a, TAnyBin>>,
TAnyBin: AnyBin,
{
fn exact_number_of_bytes(&self) -> Option<usize> {
// that's the same
self.inner.exact_number_of_bytes()
}
fn is_empty(&self) -> bool {
self.inner.is_empty()
}
fn single(self) -> Result<BinSegment<'a, TAnyBin>, Self>
where
Self: Sized,
{
match self.inner.single() {
Ok(single) => Ok(single.into()),
Err(err) => Err(Self {
inner: err,
_phantom1: Default::default(),
_phantom2: Default::default(),
}),
}
}
}
impl<'a, TInnerIterator, TAnyBin> IntoIterator
for SegmentIteratorConverter<'a, TInnerIterator, TAnyBin>
where
TInnerIterator: SegmentIterator<StrSegment<'a, TAnyBin>>,
TAnyBin: AnyBin,
{
type Item = BinSegment<'a, TAnyBin>;
type IntoIter = Map<
<TInnerIterator as IntoIterator>::IntoIter,
StrSegmentToBinSegmentConverterFn<'a, TAnyBin>,
>;
fn into_iter(self) -> Self::IntoIter {
self.inner.into_iter().map(convert_fn)
}
}
type StrSegmentToBinSegmentConverterFn<'a, TAnyBin> =
fn(StrSegment<'a, TAnyBin>) -> BinSegment<'a, TAnyBin>;
#[inline]
fn convert_fn<TAnyBin>(str_segment: StrSegment<TAnyBin>) -> BinSegment<TAnyBin>
where
TAnyBin: AnyBin,
{
str_segment.into()
}
|
#![no_main]
#![no_std]
extern crate cortex_m_rt as rt;
use rt::entry;
use rt::exception;
extern crate cortex_m as cm;
extern crate stm32f0;
use stm32f0::stm32f0x0;
use core::panic::PanicInfo;
#[panic_handler]
fn panic(_panic: &PanicInfo) -> ! {
loop {
cm::asm::bkpt();
}
}
#[entry]
fn main() -> ! {
let peripherals = stm32f0x0::Peripherals::take().unwrap();
led2_init(&peripherals);
loop {
led2_blink(&peripherals, 3000, 1000);
}
}
fn led2_init(p: &stm32f0x0::Peripherals) {
let gpioa = &p.GPIOA;
let rcc = &p.RCC;
// enable GPIOA peripheral clock
rcc.ahbenr.write(|w| w.iopaen().set_bit());
// configure PA5 as output pin
gpioa.moder.write(|w| w.moder5().output());
// configure PA5 pin as pull-down
gpioa.pupdr.write(|w| w.pupdr5().pull_down());
}
fn led2_blink(p: &stm32f0x0::Peripherals, t1: u32, t2: u32) {
let gpioa = &p.GPIOA;
loop {
gpioa.odr.write(|w| w.odr5().set_bit());
delay(t1);
gpioa.odr.write(|w| w.odr5().clear_bit());
delay(t2);
}
}
fn delay(count: u32) {
for _ in 0..count {
cm::asm::nop();
}
}
#[exception]
fn DefaultHandler(irqn: i16) {
panic!("Unhandled exception (IRQn = {})", irqn);
}
|
mod accepted;
mod calling;
mod completed;
mod errored;
mod proceeding;
mod terminated;
pub use accepted::Accepted;
pub use calling::Calling;
pub use completed::Completed;
pub use errored::Errored;
pub use proceeding::Proceeding;
pub use terminated::Terminated;
|
use std::{error::Error, process::Termination};
pub enum ExitResult<T: Termination> {
Ok(T),
Err(Box<dyn Error>, i32),
}
impl<T: Termination> ExitResult<T> {
pub fn err_from<E: Error + 'static>(e: E, code: i32) -> ExitResult<T> {
ExitResult::Err(Box::new(e), code)
}
}
impl<T: Termination> Termination for ExitResult<T> {
fn report(self) -> i32 {
match self {
ExitResult::Ok(t) => t.report(),
ExitResult::Err(b, c) => {
eprintln!("Error: {:?}", b);
c
}
}
}
}
|
use std::fs::File;
use std::io::{Error as IoError, ErrorKind};
use std::path::PathBuf;
use std::time::UNIX_EPOCH;
use store::Store;
/// Directory store.
///
/// Please note that there is a default directory storage
/// inside the `Loader`, which is automatically used when you call
/// `load`. In case you want another, second, directory for assets,
/// you can instantiate one yourself, too. Please use `Loader::load_from`
/// then.
#[derive(Debug)]
pub struct Directory {
loc: PathBuf,
}
impl Directory {
/// Creates a new directory storage.
pub fn new<P>(loc: P) -> Self
where
P: Into<PathBuf>,
{
Directory { loc: loc.into() }
}
}
impl Store for Directory {
type Error = IoError;
type Result = Result<Vec<u8>, IoError>;
fn modified(&self, category: &str, id: &str, ext: &str) -> Result<u64, IoError> {
use std::fs::metadata;
let mut path = self.loc.clone();
path.push(category);
path.push(id);
path.set_extension(ext);
Ok(
metadata(&path)?
.modified()?
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs(),
)
}
fn load(&self, category: &str, name: &str, exts: &[&str]) -> Result<Vec<u8>, IoError> {
use std::io::Read;
let mut path = self.loc.clone();
path.push(category);
path.push(name);
for ext in exts {
path.set_extension(ext);
let mut v = Vec::new();
match File::open(&path) {
Ok(mut file) => {
file.read_to_end(&mut v)?;
return Ok(v);
}
Err(io_error) => if io_error.kind() != ErrorKind::NotFound {
return Err(io_error);
},
}
}
Err(IoError::new(
ErrorKind::NotFound,
"Unable to find a file matching that path and any of the extensions for the format.",
))
}
}
|
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ButtonsData {
pub select: bool,
pub start: bool,
pub up: bool,
pub right: bool,
pub down: bool,
pub left: bool,
pub lt: bool,
pub rt: bool,
pub triangle: bool,
pub circle: bool,
pub cross: bool,
pub square: bool,
// timestamp: u64;
}
impl From<flatbuffers_structs::net_protocol::ButtonsData> for ButtonsData {
fn from(buttons: flatbuffers_structs::net_protocol::ButtonsData) -> Self {
Self {
select: buttons.select(),
start: buttons.start(),
up: buttons.up(),
right: buttons.right(),
down: buttons.down(),
left: buttons.left(),
lt: buttons.lt(),
rt: buttons.rt(),
triangle: buttons.triangle(),
circle: buttons.circle(),
cross: buttons.cross(),
square: buttons.square(),
// timestamp: buttons.timestamp(),
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Vector3 {
pub x: f32,
pub y: f32,
pub z: f32,
}
impl From<&flatbuffers_structs::net_protocol::Vector3> for Vector3 {
fn from(vector: &flatbuffers_structs::net_protocol::Vector3) -> Self {
Self {
x: vector.x(),
y: vector.y(),
z: vector.z(),
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct MotionData {
pub gyro: Vector3,
pub accelerometer: Vector3,
// timestamp: u64,
}
impl From<flatbuffers_structs::net_protocol::MotionData> for MotionData {
fn from(motion: flatbuffers_structs::net_protocol::MotionData) -> Self {
Self {
gyro: motion.gyro().into(),
accelerometer: motion.accelerometer().into(),
// timestamp: motion.timestamp(),
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct TouchReport {
pub x: u16,
pub y: u16,
pub id: u8,
pub force: u8,
}
impl From<flatbuffers_structs::net_protocol::TouchReport> for TouchReport {
fn from(touch: flatbuffers_structs::net_protocol::TouchReport) -> Self {
Self {
x: touch.x(),
y: touch.y(),
id: touch.id(),
force: touch.pressure(),
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct TouchData {
pub reports: Vec<TouchReport>,
}
impl<'a> From<flatbuffers_structs::net_protocol::TouchData<'a>> for TouchData {
fn from(touch: flatbuffers_structs::net_protocol::TouchData) -> Self {
Self {
reports: touch
.reports()
.unwrap_or_default()
.iter()
.cloned()
.map(Into::into)
.collect(),
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct MainReport {
pub buttons: ButtonsData,
pub lx: u8,
pub ly: u8,
pub rx: u8,
pub ry: u8,
pub front_touch: TouchData,
pub back_touch: TouchData,
pub motion: MotionData,
pub timestamp: u64,
}
impl<'a> TryFrom<flatbuffers_structs::net_protocol::Pad<'a>> for MainReport {
type Error = &'static str;
fn try_from(packet: flatbuffers_structs::net_protocol::Pad) -> Result<Self, Self::Error> {
let buttons = *packet.buttons().ok_or_else(|| "Buttons data is missing")?;
let front_touch = packet
.front_touch()
.ok_or_else(|| "Front touch data is missing")?;
let back_touch = packet
.back_touch()
.ok_or_else(|| "Back touch data is missing")?;
let motion = *packet.motion().ok_or_else(|| "Motion data is missing")?;
Ok(Self {
buttons: buttons.into(),
front_touch: front_touch.into(),
back_touch: back_touch.into(),
motion: motion.into(),
timestamp: packet.timestamp(),
lx: packet.lx(),
ly: packet.ly(),
rx: packet.rx(),
ry: packet.ry(),
})
}
}
|
/*
open storage
memory
filesystem
rocksdb
starts console
Options for <key>/<value>:
asdads / str:asdasd
hex:asdasd
base64:asdasd
base64url:asdasd
file:asdasd
Commands:
get <key> --out --info_only
put <key> <value> --flags
delete
meta
set_flags
do_file -> do file with command list
*/
#![feature(convert)]
#![feature(box_syntax)]
extern crate log;
extern crate linenoise;
extern crate argparse;
extern crate rustc_serialize;
extern crate storage;
use std::io::{Write, Read, Cursor, Result, Error, ErrorKind}; //ErrorKind, Error, Result
use std::fs::File;
use argparse::{ArgumentParser, Store};
use log::{LogRecord, LogLevel, LogMetadata, LogLevelFilter};
use rustc_serialize::base64::{FromBase64};
use rustc_serialize::hex::{FromHex};
use storage::{KeyValueStorage, FilesystemStorage, MemoryStorage};
///
/// Storage console readhandle
///
struct ReadHandle<'a>
{
reader: Box<Read + 'a>,
size: usize
}
///
/// Write handle
///
struct WriteHandle<'a>
{
writer: &'a mut Write,
size: Option<usize>
}
///
/// create a readhandle from a special string
/// can read hex, file, base64 values
///
fn create_readhandle<'a>(input: &'a str) -> ReadHandle<'a> //Result<ReadHandle<'a>>
{
if input.starts_with("hex:") {
let data = Box::new(Cursor::new(input[4..].from_hex().unwrap()));
ReadHandle {
reader: data,
size: input[4..].len()/2
}
}
else if input.starts_with("file:") {
let file = Box::new(File::open(&input[5..]).unwrap());
let len = file.metadata().unwrap().len();
ReadHandle {
reader: file as Box<Read>,
size: len as usize
}
}
else if input.starts_with("base64:") {
let data = Box::new(Cursor::new(input[7..].from_base64().unwrap()));
let len = data.get_ref().len();
ReadHandle {
reader: data,
size: len
}
}
//TODO base64url
else {
ReadHandle {
reader: Box::new(Cursor::new(input.as_bytes())) as Box<Read>,
size: input.len()
}
}
}
///
/// handle line
///
fn handle_line(storage: &mut KeyValueStorage, line: &str) -> Result<()>
{
let mut stdout = std::io::stdout(); //put into context struct
let mut stderr = std::io::stderr();
//get arguments
let mut args : Vec<String> = Vec::new();
args.push(String::from("")); //program arg dummy
for arg in line.split(' ') {
args.push(String::from(arg));
}
//parse arguments
let mut command = "".to_string();
let mut key = "".to_string();
let mut value = "".to_string();
{
let mut ap = ArgumentParser::new();
ap.refer(&mut command).add_argument("command", Store, "Command (get, put, delete)");
ap.refer(&mut key).add_argument("key", Store, "Key of Value");
ap.refer(&mut value).add_argument("value", Store, "Value Data");
let r = ap.parse(args, &mut stdout, &mut stderr);
if r.is_err() {
return Err(Error::new(ErrorKind::Other, "argument parsing failed"));
}
}
//handle commands
match command.as_str()
{
"get" =>
{
//macro? create read + size from value or key looking at prefixed values
//check for value
let mut key_handle = create_readhandle(&key);
let mut out_handle = WriteHandle { writer: &mut stdout, size: None };
{
let mut skey_handle = storage::ReadHandle::Reader(&mut key_handle.reader, Some(key_handle.size));
let mut sout_handle = storage::WriteHandle::Writer(&mut out_handle.writer, out_handle.size);
try!(storage.get(&mut skey_handle, &mut sout_handle));
}
try!(out_handle.writer.write("\n".as_bytes()));
try!(out_handle.writer.flush());
}
"put" =>
{
let mut key_handle = create_readhandle(&key);
let mut value_handle = create_readhandle(&value);
let mut skey_handle = storage::ReadHandle::Reader(&mut key_handle.reader, Some(key_handle.size));
let mut svalue_handle = storage::ReadHandle::Reader(&mut value_handle.reader, Some(value_handle.size));
try!(storage.put(&mut skey_handle, &mut svalue_handle));
}
"delete" =>
{
let mut key_handle = create_readhandle(&key);
let mut skey_handle = storage::ReadHandle::Reader(&mut key_handle.reader, Some(key_handle.size));
try!(storage.delete(&mut skey_handle));
}
//TODO delete command
//TODO meta command
//TODO set_flags command
//TODO do_file command
_ => { println!("Wrong command: {}", command.as_str()); }
}
Ok(())
}
///
/// The main function
///
fn main()
{
//setup logger
let r = log::set_logger(|max_log_level| {
max_log_level.set(LogLevelFilter::Debug);
Box::new(StdoutLogger)
});
if r.is_err() {
println!("failed to initialize the logger");
return;
}
let mut repo_type = "".to_string();
let mut repo_path = "".to_string();
{
let mut ap = ArgumentParser::new();
ap.set_description("Storage Console");
ap.refer(&mut repo_type).add_argument("repo_type", Store, "Repository Type");
ap.refer(&mut repo_path).add_argument("repo_path", Store, "Repository Path");
//TODO support --dofile here?
ap.parse_args_or_exit();
}
let mut storage : Option<Box<KeyValueStorage>> = None;
match repo_type.as_str()
{
"fs" => {
if repo_path.is_empty() {
println!("No repo path is given");
return;
}
storage = Some(Box::new(FilesystemStorage::open(repo_path.as_str()).unwrap()));
//create file system
}
"mem" => {
storage = Some(Box::new(MemoryStorage::new()));
}
_ => {}
}
if storage.is_none() {
println!("Invalid storage type");
return;
}
let mut storage = storage.unwrap();
//create storage
loop
{
let val = linenoise::input("> ");
match val
{
None => { break }
Some(input) =>
{
if input == "exit"
|| input == "q"
|| input == "quit" {
break;
}
linenoise::history_add(input.as_str());
let r = handle_line(&mut *storage, input.as_str());
if r.is_err() {
println!("error: {}", r.err().unwrap());
}
}
}
}
}
/// phantom struct for implementing a stdout logger
struct StdoutLogger;
impl log::Log for StdoutLogger
{
fn enabled(&self, metadata: &LogMetadata) -> bool
{
metadata.level() <= LogLevel::Debug
}
fn log(&self, record: &LogRecord)
{
if self.enabled(record.metadata()) {
println!("{}", record.args());
}
}
}
|
#[doc = "Reader of register FDCAN_HPMS"]
pub type R = crate::R<u32, super::FDCAN_HPMS>;
#[doc = "Reader of field `BIDX`"]
pub type BIDX_R = crate::R<u8, u8>;
#[doc = "MSI\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum MSI_A {
#[doc = "0: No FIFO selected"]
B_0X0 = 0,
#[doc = "1: FIFO overrun"]
B_0X1 = 1,
#[doc = "2: Message stored in FIFO\r\n 0"]
B_0X2 = 2,
#[doc = "3: Message stored in FIFO\r\n 1"]
B_0X3 = 3,
}
impl From<MSI_A> for u8 {
#[inline(always)]
fn from(variant: MSI_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `MSI`"]
pub type MSI_R = crate::R<u8, MSI_A>;
impl MSI_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> MSI_A {
match self.bits {
0 => MSI_A::B_0X0,
1 => MSI_A::B_0X1,
2 => MSI_A::B_0X2,
3 => MSI_A::B_0X3,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `B_0X0`"]
#[inline(always)]
pub fn is_b_0x0(&self) -> bool {
*self == MSI_A::B_0X0
}
#[doc = "Checks if the value of the field is `B_0X1`"]
#[inline(always)]
pub fn is_b_0x1(&self) -> bool {
*self == MSI_A::B_0X1
}
#[doc = "Checks if the value of the field is `B_0X2`"]
#[inline(always)]
pub fn is_b_0x2(&self) -> bool {
*self == MSI_A::B_0X2
}
#[doc = "Checks if the value of the field is `B_0X3`"]
#[inline(always)]
pub fn is_b_0x3(&self) -> bool {
*self == MSI_A::B_0X3
}
}
#[doc = "Reader of field `FIDX`"]
pub type FIDX_R = crate::R<u8, u8>;
#[doc = "FLST\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum FLST_A {
#[doc = "0: Standard Filter List"]
B_0X0 = 0,
#[doc = "1: Extended Filter List"]
B_0X1 = 1,
}
impl From<FLST_A> for bool {
#[inline(always)]
fn from(variant: FLST_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `FLST`"]
pub type FLST_R = crate::R<bool, FLST_A>;
impl FLST_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> FLST_A {
match self.bits {
false => FLST_A::B_0X0,
true => FLST_A::B_0X1,
}
}
#[doc = "Checks if the value of the field is `B_0X0`"]
#[inline(always)]
pub fn is_b_0x0(&self) -> bool {
*self == FLST_A::B_0X0
}
#[doc = "Checks if the value of the field is `B_0X1`"]
#[inline(always)]
pub fn is_b_0x1(&self) -> bool {
*self == FLST_A::B_0X1
}
}
impl R {
#[doc = "Bits 0:5 - BIDX"]
#[inline(always)]
pub fn bidx(&self) -> BIDX_R {
BIDX_R::new((self.bits & 0x3f) as u8)
}
#[doc = "Bits 6:7 - MSI"]
#[inline(always)]
pub fn msi(&self) -> MSI_R {
MSI_R::new(((self.bits >> 6) & 0x03) as u8)
}
#[doc = "Bits 8:14 - FIDX"]
#[inline(always)]
pub fn fidx(&self) -> FIDX_R {
FIDX_R::new(((self.bits >> 8) & 0x7f) as u8)
}
#[doc = "Bit 15 - FLST"]
#[inline(always)]
pub fn flst(&self) -> FLST_R {
FLST_R::new(((self.bits >> 15) & 0x01) != 0)
}
}
|
#[doc = "Register `MTLTXQOMR` reader"]
pub type R = crate::R<MTLTXQOMR_SPEC>;
#[doc = "Register `MTLTXQOMR` writer"]
pub type W = crate::W<MTLTXQOMR_SPEC>;
#[doc = "Field `FTQ` reader - Flush Transmit Queue When this bit is set, the Tx queue controller logic is reset to its default values. Therefore, all the data in the Tx queue is lost or flushed. This bit is internally reset when the flushing operation is complete. Until this bit is reset, you should not write to the ETH_MTLTXQOMR register. The data which is already accepted by the MAC transmitter is not flushed. It is scheduled for transmission and results in underflow and runt packet transmission. Note: The flush operation is complete only when the Tx queue is empty and the application has accepted the pending Tx Status of all transmitted packets. To complete this flush operation, the PHY Tx clock (eth_mii_tx_clk) should be active."]
pub type FTQ_R = crate::BitReader;
#[doc = "Field `FTQ` writer - Flush Transmit Queue When this bit is set, the Tx queue controller logic is reset to its default values. Therefore, all the data in the Tx queue is lost or flushed. This bit is internally reset when the flushing operation is complete. Until this bit is reset, you should not write to the ETH_MTLTXQOMR register. The data which is already accepted by the MAC transmitter is not flushed. It is scheduled for transmission and results in underflow and runt packet transmission. Note: The flush operation is complete only when the Tx queue is empty and the application has accepted the pending Tx Status of all transmitted packets. To complete this flush operation, the PHY Tx clock (eth_mii_tx_clk) should be active."]
pub type FTQ_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TSF` reader - Transmit Store and Forward When this bit is set, the transmission starts when a full packet resides in the MTL Tx queue. When this bit is set, the TTC values specified in Bits\\[6:4\\]
of this register are ignored. This bit should be changed only when the transmission is stopped."]
pub type TSF_R = crate::BitReader;
#[doc = "Field `TSF` writer - Transmit Store and Forward When this bit is set, the transmission starts when a full packet resides in the MTL Tx queue. When this bit is set, the TTC values specified in Bits\\[6:4\\]
of this register are ignored. This bit should be changed only when the transmission is stopped."]
pub type TSF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TXQEN` reader - Transmit Queue Enable This field is used to enable/disable the transmit queue . Others: Reserved, must not be used. Note: In multiple Tx queues configuration, all the queues are disabled by default. Enable the Tx queue by programming this field."]
pub type TXQEN_R = crate::FieldReader;
#[doc = "Field `TTC` reader - Transmit Threshold Control These bits control the threshold level of the MTL Tx queue. The transmission starts when the packet size within the MTL Tx queue is larger than the threshold. In addition, full packets with length less than the threshold are also transmitted. These bits are used only when the TSF bit is reset."]
pub type TTC_R = crate::FieldReader;
#[doc = "Field `TTC` writer - Transmit Threshold Control These bits control the threshold level of the MTL Tx queue. The transmission starts when the packet size within the MTL Tx queue is larger than the threshold. In addition, full packets with length less than the threshold are also transmitted. These bits are used only when the TSF bit is reset."]
pub type TTC_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 3, O>;
#[doc = "Field `TQS` reader - Transmit queue size This field indicates the size of the allocated transmit queues in blocks of 256 bytes. Queue size range from 256 bytes (TQS=0b000) to 2048 bytes (TQS=0b111)."]
pub type TQS_R = crate::FieldReader;
#[doc = "Field `TQS` writer - Transmit queue size This field indicates the size of the allocated transmit queues in blocks of 256 bytes. Queue size range from 256 bytes (TQS=0b000) to 2048 bytes (TQS=0b111)."]
pub type TQS_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 3, O>;
impl R {
#[doc = "Bit 0 - Flush Transmit Queue When this bit is set, the Tx queue controller logic is reset to its default values. Therefore, all the data in the Tx queue is lost or flushed. This bit is internally reset when the flushing operation is complete. Until this bit is reset, you should not write to the ETH_MTLTXQOMR register. The data which is already accepted by the MAC transmitter is not flushed. It is scheduled for transmission and results in underflow and runt packet transmission. Note: The flush operation is complete only when the Tx queue is empty and the application has accepted the pending Tx Status of all transmitted packets. To complete this flush operation, the PHY Tx clock (eth_mii_tx_clk) should be active."]
#[inline(always)]
pub fn ftq(&self) -> FTQ_R {
FTQ_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - Transmit Store and Forward When this bit is set, the transmission starts when a full packet resides in the MTL Tx queue. When this bit is set, the TTC values specified in Bits\\[6:4\\]
of this register are ignored. This bit should be changed only when the transmission is stopped."]
#[inline(always)]
pub fn tsf(&self) -> TSF_R {
TSF_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bits 2:3 - Transmit Queue Enable This field is used to enable/disable the transmit queue . Others: Reserved, must not be used. Note: In multiple Tx queues configuration, all the queues are disabled by default. Enable the Tx queue by programming this field."]
#[inline(always)]
pub fn txqen(&self) -> TXQEN_R {
TXQEN_R::new(((self.bits >> 2) & 3) as u8)
}
#[doc = "Bits 4:6 - Transmit Threshold Control These bits control the threshold level of the MTL Tx queue. The transmission starts when the packet size within the MTL Tx queue is larger than the threshold. In addition, full packets with length less than the threshold are also transmitted. These bits are used only when the TSF bit is reset."]
#[inline(always)]
pub fn ttc(&self) -> TTC_R {
TTC_R::new(((self.bits >> 4) & 7) as u8)
}
#[doc = "Bits 16:18 - Transmit queue size This field indicates the size of the allocated transmit queues in blocks of 256 bytes. Queue size range from 256 bytes (TQS=0b000) to 2048 bytes (TQS=0b111)."]
#[inline(always)]
pub fn tqs(&self) -> TQS_R {
TQS_R::new(((self.bits >> 16) & 7) as u8)
}
}
impl W {
#[doc = "Bit 0 - Flush Transmit Queue When this bit is set, the Tx queue controller logic is reset to its default values. Therefore, all the data in the Tx queue is lost or flushed. This bit is internally reset when the flushing operation is complete. Until this bit is reset, you should not write to the ETH_MTLTXQOMR register. The data which is already accepted by the MAC transmitter is not flushed. It is scheduled for transmission and results in underflow and runt packet transmission. Note: The flush operation is complete only when the Tx queue is empty and the application has accepted the pending Tx Status of all transmitted packets. To complete this flush operation, the PHY Tx clock (eth_mii_tx_clk) should be active."]
#[inline(always)]
#[must_use]
pub fn ftq(&mut self) -> FTQ_W<MTLTXQOMR_SPEC, 0> {
FTQ_W::new(self)
}
#[doc = "Bit 1 - Transmit Store and Forward When this bit is set, the transmission starts when a full packet resides in the MTL Tx queue. When this bit is set, the TTC values specified in Bits\\[6:4\\]
of this register are ignored. This bit should be changed only when the transmission is stopped."]
#[inline(always)]
#[must_use]
pub fn tsf(&mut self) -> TSF_W<MTLTXQOMR_SPEC, 1> {
TSF_W::new(self)
}
#[doc = "Bits 4:6 - Transmit Threshold Control These bits control the threshold level of the MTL Tx queue. The transmission starts when the packet size within the MTL Tx queue is larger than the threshold. In addition, full packets with length less than the threshold are also transmitted. These bits are used only when the TSF bit is reset."]
#[inline(always)]
#[must_use]
pub fn ttc(&mut self) -> TTC_W<MTLTXQOMR_SPEC, 4> {
TTC_W::new(self)
}
#[doc = "Bits 16:18 - Transmit queue size This field indicates the size of the allocated transmit queues in blocks of 256 bytes. Queue size range from 256 bytes (TQS=0b000) to 2048 bytes (TQS=0b111)."]
#[inline(always)]
#[must_use]
pub fn tqs(&mut self) -> TQS_W<MTLTXQOMR_SPEC, 16> {
TQS_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "Tx queue operating mode Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`mtltxqomr::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`mtltxqomr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct MTLTXQOMR_SPEC;
impl crate::RegisterSpec for MTLTXQOMR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`mtltxqomr::R`](R) reader structure"]
impl crate::Readable for MTLTXQOMR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`mtltxqomr::W`](W) writer structure"]
impl crate::Writable for MTLTXQOMR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets MTLTXQOMR to value 0x0007_0008"]
impl crate::Resettable for MTLTXQOMR_SPEC {
const RESET_VALUE: Self::Ux = 0x0007_0008;
}
|
#[doc = "Register `TTLGT` reader"]
pub type R = crate::R<TTLGT_SPEC>;
#[doc = "Field `LT` reader - Local Time"]
pub type LT_R = crate::FieldReader<u16>;
#[doc = "Field `GT` reader - Global Time"]
pub type GT_R = crate::FieldReader<u16>;
impl R {
#[doc = "Bits 0:15 - Local Time"]
#[inline(always)]
pub fn lt(&self) -> LT_R {
LT_R::new((self.bits & 0xffff) as u16)
}
#[doc = "Bits 16:31 - Global Time"]
#[inline(always)]
pub fn gt(&self) -> GT_R {
GT_R::new(((self.bits >> 16) & 0xffff) as u16)
}
}
#[doc = "FDCAN TT Local and Global Time Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ttlgt::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct TTLGT_SPEC;
impl crate::RegisterSpec for TTLGT_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`ttlgt::R`](R) reader structure"]
impl crate::Readable for TTLGT_SPEC {}
#[doc = "`reset()` method sets TTLGT to value 0"]
impl crate::Resettable for TTLGT_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
#[path = "support/macros.rs"]
#[macro_use]
mod macros;
use criterion::{criterion_group, criterion_main, Criterion};
fn bench_mat2_transpose(c: &mut Criterion) {
use criterion::Benchmark;
c.bench(
"mat2 transpose",
Benchmark::new("glam", |b| {
use glam::Mat2;
bench_unop!(b, op => transpose, ty => Mat2)
})
.with_function("cgmath", |b| {
use cgmath::{prelude::*, Matrix2};
bench_unop!(b, op => transpose, ty => Matrix2<f32>)
})
.with_function("nalgebra", |b| {
use nalgebra::Matrix2;
bench_unop!(b, op => transpose, ty => Matrix2<f32>)
}),
);
}
fn bench_mat2_determinant(c: &mut Criterion) {
use criterion::Benchmark;
c.bench(
"mat2 determinant",
Benchmark::new("glam", |b| {
use glam::Mat2;
bench_unop!(b, op => determinant, ty => Mat2)
})
.with_function("cgmath", |b| {
use cgmath::{prelude::*, Matrix2};
bench_unop!(b, op => determinant, ty => Matrix2<f32>)
})
.with_function("nalgebra", |b| {
use nalgebra::Matrix2;
bench_unop!(b, op => determinant, ty => Matrix2<f32>)
}),
);
}
fn bench_mat2_inverse(c: &mut Criterion) {
use criterion::Benchmark;
c.bench(
"mat2 inverse",
Benchmark::new("glam", |b| {
use glam::Mat2;
bench_unop!(b, op => inverse, ty => Mat2)
})
.with_function("cgmath", |b| {
use cgmath::{prelude::*, Matrix2};
bench_unop!(b, op => invert, ty => Matrix2<f32>)
})
.with_function("nalgebra", |b| {
use nalgebra::Matrix2;
bench_unop!(b, op => try_inverse, ty => Matrix2<f32>)
}),
);
}
fn bench_mat2_mul_mat2(c: &mut Criterion) {
use criterion::Benchmark;
use std::ops::Mul;
c.bench(
"mat2 mul mat2",
Benchmark::new("glam", |b| {
use glam::Mat2;
bench_binop!(b, op => mul, ty1 => Mat2, ty2 => Mat2)
})
.with_function("cgmath", |b| {
use cgmath::Matrix2;
bench_binop!(b, op => mul, ty1 => Matrix2<f32>, ty2 => Matrix2<f32>)
})
.with_function("nalgebra", |b| {
use nalgebra::Matrix2;
bench_binop!(b, op => mul, ty1 => Matrix2<f32>, ty2 => Matrix2<f32>)
}),
);
}
criterion_group!(
mat2_benches,
bench_mat2_transpose,
bench_mat2_determinant,
bench_mat2_inverse,
bench_mat2_mul_mat2,
);
criterion_main!(mat2_benches);
|
use crate::{packed, prelude::*};
macro_rules! impl_std_cmp_eq_and_hash {
($struct:ident) => {
impl PartialEq for packed::$struct {
#[inline]
fn eq(&self, other: &Self) -> bool {
self.as_slice() == other.as_slice()
}
}
impl Eq for packed::$struct {}
impl ::std::hash::Hash for packed::$struct {
#[inline]
fn hash<H: ::std::hash::Hasher>(&self, state: &mut H) {
state.write(self.as_slice())
}
}
};
}
impl_std_cmp_eq_and_hash!(Byte32);
impl_std_cmp_eq_and_hash!(Uint256);
impl_std_cmp_eq_and_hash!(ProposalShortId);
impl_std_cmp_eq_and_hash!(Script);
impl_std_cmp_eq_and_hash!(CellDep);
impl_std_cmp_eq_and_hash!(OutPoint);
impl_std_cmp_eq_and_hash!(CellInput);
impl_std_cmp_eq_and_hash!(CellOutput);
impl_std_cmp_eq_and_hash!(Alert);
impl_std_cmp_eq_and_hash!(UncleBlock);
impl_std_cmp_eq_and_hash!(Block);
impl ::std::cmp::Ord for packed::Byte32 {
#[inline]
fn cmp(&self, other: &Self) -> ::std::cmp::Ordering {
self.as_slice().cmp(other.as_slice())
}
}
impl ::std::cmp::PartialOrd for packed::Byte32 {
#[inline]
fn partial_cmp(&self, other: &Self) -> Option<::std::cmp::Ordering> {
Some(self.cmp(other))
}
}
|
use std::fs;
use std::fs::File;
use std::error::Error;
use std::io::{stdout, Read, Write};
use std::collections::HashMap;
use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::collections::HashSet;
use std::path::{Path,PathBuf};
use zip;
use std::collections::VecDeque;
use std::thread;
use std::sync::{Mutex,RwLock,Arc,Barrier,Weak};
use appData::AppData;
use version::Version;
use description;
pub struct ModDescription{
name:String,
version:Version,
gameVersion:Version,
description:String,
dependencies:Vec< (String,Version) >,
}
impl ModDescription {
fn read( text:&String ) -> Result<ModDescription, String> {
let modDescription: ModDescription = try!(description::parse( text, |root| {
Ok(
ModDescription{
name:try!(root.getString("name")).clone(),
version:match Version::parse( try!(root.getString("version")) ) {
Ok( v ) => v,
Err( msg ) => return Err( format!("Can not parse version of mod : {}", msg)),
},
gameVersion:match Version::parse( try!(root.getString("game version")) ) {
Ok( v ) => v,
Err( msg ) => return Err( format!("Can not parse version of game for mod : {}", msg)),
},
description:try!(root.getString("description")).clone(),
dependencies:{
let depList=try!( root.getList("dependencies") );
let mut dependencies=Vec::new();
for dep in depList.iter() {
let dependence=try!( dep.getString() );
let mut it=dependence.split('-');
let nameAndVersion:Vec<&str>=dependence.split('-').collect();
if nameAndVersion.len()!=2 {
return Err( format!("Name of dependence mod \"{}\" is invalid - expected format <name of mod>-<version>", dependence));
}
let depModVersion=match Version::parse( &nameAndVersion[1].to_string() ){
Ok( v ) => v,
Err( msg ) => return Err( format!("Can not parse version of dependence mod \"{}\": {}", dependence, msg)),
};
dependencies.push( (nameAndVersion[0].to_string(), depModVersion));
}
dependencies
},
}
)
}));
Ok(modDescription)
}
}
pub struct Mod{
description:ModDescription,
pub fileName:String,
pub isActive:bool,
}
impl Mod{
/*
fn readDescriptionFile( appData: &Arc<AppData>, descriptionFileName:&String ) -> Result<Mod, String>{
let mut descriptionFile=match File::open(descriptionFileName.as_str()) {
Ok( f ) => f,
Err( e ) => return Err(format!("Can not read mod description file \"{}\" : {}", descriptionFileName, e.description())),
};
let mut content = String::new();
match descriptionFile.read_to_string(&mut content){
Ok( c ) => {},
Err( e ) => return Err(format!("Can not read mod description file \"{}\" : {}", descriptionFileName, e.description())),
}
let modDescription = match ModDescription::read( &content ){
Ok( d ) => d,
Err( msg ) => return Err(format!("Can not decode mod description file \"{}\" : {}", descriptionFileName, msg)),
};
Ok(Mod{
description:modDescription,
isInstalled:false,
isActive:false,
})
}
*/
fn readInstalledModDescription( appData: &Arc<AppData>, modPath: PathBuf ) -> Result<Mod,String> {
//=====================Mod Name========================
let modFileName=match modPath.file_name(){
Some( n )=>{
match n.to_str() {
Some( name ) => {
/*
if name.ends_with(".zip") {
let mut n=String::from(name);
n.truncate(name.len()-4);
n
}else{
String::from(name)
}*/
String::from(name)
}
None => return Err((format!("Bad name of mod file"))),
}
},
None => return Err((format!("Mod without name"))),
};
//=====================Is Archive?=====================
//change
let isModArchive={
match modPath.extension(){
Some( e )=>{
match e.to_str() {
Some( extension ) => extension=="zip",
None => false,
}
},
None => false,
}
};
//=====================Read description================
let descriptionFileName=format!("{}/mod.description",modPath.display());
let modDescription=if isModArchive {
let zipFile = match File::open(&modPath) {
Ok( f ) => f,
Err( e ) => return Err(format!("Can not read mod \"{}\" : {}", modPath.display(), e.description())),
};
let mut archive = match zip::ZipArchive::new(zipFile){
Ok( a ) => a,
Err( e ) =>return Err(format!("Can not read archive \"{}\" : {}", modPath.display(), e.description())),
};
let mut descriptionFile = match archive.by_name("test/mod.description"){
Ok( f ) => f,
Err( _ ) => return Err(format!("Archive \"{}\" has no file mod.description", modPath.display())),
};
let mut content = String::new();
match descriptionFile.read_to_string(&mut content){
Ok( c ) => {},
Err( e ) => return Err(format!("Can not read file \"{}\" : {}", descriptionFileName, e.description())),
}
let modDescription = match ModDescription::read( &content ){
Ok( d ) => d,
Err( msg ) => return Err(format!("Can not decode mod description file \"{}\" : {}", descriptionFileName, msg)),
};
modDescription
}else{
let mut descriptionFile=match File::open(descriptionFileName.as_str()) {
Ok( f ) => f,
Err( e ) => return Err(format!("Can not read file \"{}\" : {}", descriptionFileName, e.description())),
};
let mut content = String::new();
match descriptionFile.read_to_string(&mut content){
Ok( c ) => {},
Err( e ) => return Err(format!("Can not read file \"{}\" : {}", descriptionFileName, e.description())),
}
let modDescription = match ModDescription::read( &content ){
Ok( d ) => d,
Err( msg ) => return Err(format!("Can not decode mod description file \"{}\" : {}", descriptionFileName, msg)),
};
modDescription
};
//====================Check==============================
if !modFileName.starts_with(&modDescription.name) {
return Err( format!("Mod \"{}\" has different names of its file and name in mod.description",modPath.display()));
}
//game version
Ok(
Mod{
description:modDescription,
fileName:modFileName.clone(),
isActive:false,
}
)
}
}
fn selectModulesToLoad( appData:&Arc<AppData> ) -> Result< Vec<String>, String >{
//========================Read Installed mods========================
let mut installedMods=HashMap::new();
let mut modErrors=String::with_capacity(256);
let installedModsList=match fs::read_dir("./Mods/"){
Ok( list ) => list,
Err( e ) => return Err(format!("Can not read existing mods from directory Mods : {}", e.description() )),
};
for m in installedModsList {
let modPath=m.unwrap().path();
match Mod::readInstalledModDescription( &appData, modPath ) {
Ok( m ) => {
match installedMods.entry( m.description.name.clone() ){
Vacant( e ) => {e.insert( m );},
Occupied(_) => modErrors.push_str(format!("Mod {} have more than one packages",m.description.name).as_str()),
}
},
Err( msg ) => {
modErrors.push_str( msg.as_str() );
modErrors.push('\n');
}
}
}
if modErrors.len()>0 {
modErrors.insert(0,'\n');
return Err(modErrors);
}
//========================Read ActivateMods list=====================
let activeModsFileName="activeMods.list";
let mut file=match File::open(activeModsFileName) {
Ok( f ) => f,
Err( e ) => return Err(format!("Can not read file \"{}\" : {}", activeModsFileName, e.description())),
};
let mut content = String::new();
match file.read_to_string(&mut content){
Ok( c ) => {},
Err( e ) => return Err(format!("Can not read file \"{}\" : {}", activeModsFileName, e.description())),
}
let mut activateMods:VecDeque< (String, Option<Version>) >=match description::parse( &content, |root| {
let activeModsList=try!( root.getList("active mods") );
let mut activateMods:VecDeque< (String, Option<Version>) >=VecDeque::new();
for mname in activeModsList.iter() {
activateMods.push_front( (try!(mname.getString()).clone(), None) );
}
Ok(activateMods)
}){
Ok( am ) => am,
Err( msg ) => return Err(format!("Can not decode file \"{}\" : {}", activeModsFileName, msg)),
};
//=======================Check And Activate Mods===================
let mut activatedMods=Vec::new();
for (modName, modVersion) in activateMods.pop_back() {
match installedMods.get_mut( &modName ){
Some( ref mut m ) => {
match modVersion {
Some( mv ) => {
if mv>m.description.version {
return Err( format!("Mod {} is out of date : version is {}, but {} is needed",&modName, m.description.version.print(), mv.print() ) );
}
},
None => {},
}
if !m.isActive {
m.isActive=true;
activatedMods.push( m.fileName.clone() );
for &(ref depModName, ref depModVersion) in m.description.dependencies.iter() {
activateMods.push_front( (depModName.clone(), Some(depModVersion.clone())) );
}
}
},
None => return Err( format!("Mod {} has not been installed",&modName) ),
}
}
Ok(activatedMods)
}
pub fn loadMods( appData:Arc<AppData> ) -> Result< (), String >{
appData.log.write("Checking mods");
let loadMods=try!(selectModulesToLoad( &appData ));
appData.log.write("Loading mods");
Ok(())
}
|
use crate::derive_input_ext::DeriveInputExt;
use darling::{FromDeriveInput, FromMeta};
use inflector::Inflector;
use proc_macro2::TokenStream;
use quote::quote;
use syn::{DeriveInput, Ident, LitStr};
pub fn generate(input: &DeriveInput) -> TokenStream {
let implement = try_ts!(implement(input));
quote! {
#implement
}
}
fn implement(input: &DeriveInput) -> Result<TokenStream, TokenStream> {
let vis = &input.vis;
let entity = &input.ident;
let args = TypeArgs::from_derive_input(input).map_err(|e| e.write_errors())?;
let entity_name = entity.to_string();
let table_name = entity_name.to_plural();
let table_name_lit = LitStr::new(&entity_name, entity.span());
let table_alias = Ident::new(&table_name, entity.span());
let tbl_var = Ident::new(
&format!("___{}_tbl", entity_name.to_snake_case()),
input.ident.span(),
);
let coll_ty = args.collection.ty(entity);
let (gc, gc_collect) = gc(input)?;
Ok(quote! {
#vis type #table_alias = #coll_ty;
fn #tbl_var() -> &'static (storm::TblVar<#table_alias>, storm::Deps, storm::OnRemove<#entity>) {
static CELL: storm::OnceCell<(storm::TblVar<#table_alias>, storm::Deps, storm::OnRemove<#entity>)> = storm::OnceCell::new();
CELL.get_or_init(|| {
#gc_collect
Default::default()
})
}
impl storm::EntityAccessor for #entity {
type Tbl = #table_alias;
#[inline]
fn entity_var() -> &'static storm::TblVar<Self::Tbl> {
&#tbl_var().0
}
#[inline]
fn entity_deps() -> &'static storm::Deps {
&#tbl_var().1
}
#[inline]
fn on_remove() -> &'static storm::OnRemove<Self> {
&#tbl_var().2
}
}
impl storm::LogAccessor for #entity {
#[inline]
fn log_var() -> &'static storm::LogVar<storm::Log<Self>> {
static CELL: storm::OnceCell<storm::LogVar<storm::Log<#entity>>> = storm::OnceCell::new();
CELL.get_or_init(|| {
storm::register_apply_log::<#entity>();
storm::LogVar::default()
})
}
}
impl storm::CtxTypeInfo for #entity {
const NAME: &'static str = #table_name_lit;
}
#gc
})
}
fn gc(input: &DeriveInput) -> Result<(TokenStream, TokenStream), TokenStream> {
let fields = input.fields()?;
let ident = &input.ident;
let types = fields.iter().map(|f| &f.ty);
let fields = fields.iter().map(|f| &f.ident);
Ok((
quote! {
impl storm::Gc for #ident {
const SUPPORT_GC: bool = #(<#types as storm::Gc>::SUPPORT_GC ||)* false;
fn gc(&mut self, ctx: &storm::GcCtx) {
#(storm::Gc::gc(&mut self.#fields, ctx);)*
}
}
},
quote! {
if <#ident as storm::Gc>::SUPPORT_GC {
storm::gc::collectables::register(|ctx| ctx.tbl_gc::<#ident>());
}
},
))
}
#[derive(Clone, Copy, Debug, Eq, FromMeta, PartialEq)]
enum Collection {
HashTable,
VecTable,
}
impl Collection {
fn ty(&self, entity: &Ident) -> TokenStream {
match self {
Self::HashTable => quote!(storm::HashTable<#entity>),
Self::VecTable => quote!(storm::VecTable<#entity>),
}
}
}
impl Default for Collection {
fn default() -> Self {
Self::VecTable
}
}
#[derive(Debug, FromDeriveInput)]
#[darling(attributes(storm), allow_unknown_fields)]
struct TypeArgs {
#[darling(default)]
collection: Collection,
}
|
mod test;
#[macro_use]
extern crate clap;
use clap::App;
use std::fs;
use regex::Regex;
use serde_derive::Deserialize;
#[derive(Deserialize, Debug)]
pub(crate) struct LintConfig {
commit_types: Vec<String>,
commit_scopes: Vec<String>,
}
pub(crate) fn get_lint_config(config_path: &str) -> LintConfig {
let contents = fs::read_to_string(config_path)
.expect("Something went wrong reading the file");
let config: LintConfig = toml::from_str(contents.as_str()).unwrap();
return config;
}
/// 根据配置路径和信息测试是否通过
pub fn judge_message_lint_pass(config_path: &str, message: &str) -> bool {
let skip_regex = Regex::new(r"^Merge branch").unwrap();
if skip_regex.is_match(message) {
println!("skip this messge check");
return true;
}
let lint_config = get_lint_config(config_path);
let reg_source = format!(r"^({})\((({}),?)*\):.{{4,}}?", lint_config.commit_types.join("|"), lint_config.commit_scopes.join("|"));
let commit_regex = Regex::new(reg_source.as_str()).unwrap();
// println!("commit_regex: {:?}", commit_regex);
return commit_regex.is_match(message);
}
pub fn main() {
// The YAML file is found relative to the current file, similar to how modules are found
let yaml = load_yaml!("cli.yml");
let matches = App::from_yaml(yaml).get_matches();
let pass = judge_message_lint_pass(matches.value_of("config_path").unwrap(), matches.value_of("message").unwrap());
if !pass {
eprintln!("commit-lint error: 提交信息不规范,请重新检查( TYPE 和 SCOPE 请参考 .toml 配置文件)");
println!("提交规范: TYPE(SCOPE): MESSAGE");
std::process::exit(-1);
}
println!("commit-lint pass");
} |
pub mod utils;
pub mod banner;
pub mod client;
pub mod config;
pub mod extractor;
pub mod filters;
pub mod heuristics;
pub mod logger;
pub mod parser;
pub mod progress;
pub mod reporter;
pub mod scan_manager;
pub mod scanner;
pub mod statistics;
use crate::utils::{get_url_path_length, status_colorizer};
use console::{style, Color};
use reqwest::header::{HeaderName, HeaderValue};
use reqwest::{header::HeaderMap, Response, StatusCode, Url};
use serde::{ser::SerializeStruct, Deserialize, Deserializer, Serialize, Serializer};
use serde_json::Value;
use std::collections::HashMap;
use std::convert::{TryFrom, TryInto};
use std::str::FromStr;
use std::{error, fmt};
use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender};
/// Generic Result type to ease error handling in async contexts
pub type FeroxResult<T> = std::result::Result<T, Box<dyn error::Error + Send + Sync + 'static>>;
/// Simple Error implementation to allow for custom error returns
#[derive(Debug, Default)]
pub struct FeroxError {
/// fancy string that can be printed via Display
pub message: String,
}
impl error::Error for FeroxError {}
impl fmt::Display for FeroxError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", &self.message)
}
}
/// Generic mpsc::unbounded_channel type to tidy up some code
pub type FeroxChannel<T> = (UnboundedSender<T>, UnboundedReceiver<T>);
/// Version pulled from Cargo.toml at compile time
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
/// Maximum number of file descriptors that can be opened during a scan
pub const DEFAULT_OPEN_FILE_LIMIT: usize = 8192;
/// Default value used to determine near-duplicate web pages (equivalent to 95%)
pub const SIMILARITY_THRESHOLD: u32 = 95;
/// Default wordlist to use when `-w|--wordlist` isn't specified and not `wordlist` isn't set
/// in a [ferox-config.toml](constant.DEFAULT_CONFIG_NAME.html) config file.
///
/// defaults to kali's default install location:
/// - `/usr/share/seclists/Discovery/Web-Content/raft-medium-directories.txt`
pub const DEFAULT_WORDLIST: &str =
"/usr/share/seclists/Discovery/Web-Content/raft-medium-directories.txt";
/// Number of milliseconds to wait between polls of `PAUSE_SCAN` when user pauses a scan
pub static SLEEP_DURATION: u64 = 500;
/// Default list of status codes to report
///
/// * 200 Ok
/// * 204 No Content
/// * 301 Moved Permanently
/// * 302 Found
/// * 307 Temporary Redirect
/// * 308 Permanent Redirect
/// * 401 Unauthorized
/// * 403 Forbidden
/// * 405 Method Not Allowed
pub const DEFAULT_STATUS_CODES: [StatusCode; 9] = [
StatusCode::OK,
StatusCode::NO_CONTENT,
StatusCode::MOVED_PERMANENTLY,
StatusCode::FOUND,
StatusCode::TEMPORARY_REDIRECT,
StatusCode::PERMANENT_REDIRECT,
StatusCode::UNAUTHORIZED,
StatusCode::FORBIDDEN,
StatusCode::METHOD_NOT_ALLOWED,
];
/// Default filename for config file settings
///
/// Expected location is in the same directory as the feroxbuster binary.
pub const DEFAULT_CONFIG_NAME: &str = "ferox-config.toml";
/// FeroxSerialize trait; represents different types that are Serialize and also implement
/// as_str / as_json methods
pub trait FeroxSerialize: Serialize {
/// Return a String representation of the object, generally the human readable version of the
/// implementor
fn as_str(&self) -> String;
/// Return an NDJSON representation of the object
fn as_json(&self) -> String;
}
/// A `FeroxResponse`, derived from a `Response` to a submitted `Request`
#[derive(Debug, Clone)]
pub struct FeroxResponse {
/// The final `Url` of this `FeroxResponse`
url: Url,
/// The `StatusCode` of this `FeroxResponse`
status: StatusCode,
/// The full response text
text: String,
/// The content-length of this response, if known
content_length: u64,
/// The number of lines contained in the body of this response, if known
line_count: usize,
/// The number of words contained in the body of this response, if known
word_count: usize,
/// The `Headers` of this `FeroxResponse`
headers: HeaderMap,
/// Wildcard response status
wildcard: bool,
}
/// Implement Display for FeroxResponse
impl fmt::Display for FeroxResponse {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"FeroxResponse {{ url: {}, status: {}, content-length: {} }}",
self.url(),
self.status(),
self.content_length()
)
}
}
/// `FeroxResponse` implementation
impl FeroxResponse {
/// Get the `StatusCode` of this `FeroxResponse`
pub fn status(&self) -> &StatusCode {
&self.status
}
/// Get the final `Url` of this `FeroxResponse`.
pub fn url(&self) -> &Url {
&self.url
}
/// Get the full response text
pub fn text(&self) -> &str {
&self.text
}
/// Get the `Headers` of this `FeroxResponse`
pub fn headers(&self) -> &HeaderMap {
&self.headers
}
/// Get the content-length of this response, if known
pub fn content_length(&self) -> u64 {
self.content_length
}
/// Set `FeroxResponse`'s `url` attribute, has no affect if an error occurs
pub fn set_url(&mut self, url: &str) {
match Url::parse(&url) {
Ok(url) => {
self.url = url;
}
Err(e) => {
log::error!("Could not parse {} into a Url: {}", url, e);
}
};
}
/// Make a reasonable guess at whether the response is a file or not
///
/// Examines the last part of a path to determine if it has an obvious extension
/// i.e. http://localhost/some/path/stuff.js where stuff.js indicates a file
///
/// Additionally, inspects query parameters, as they're also often indicative of a file
pub fn is_file(&self) -> bool {
let has_extension = match self.url.path_segments() {
Some(path) => {
if let Some(last) = path.last() {
last.contains('.') // last segment has some sort of extension, probably
} else {
false
}
}
None => false,
};
self.url.query_pairs().count() > 0 || has_extension
}
/// Returns line count of the response text.
pub fn line_count(&self) -> usize {
self.line_count
}
/// Returns word count of the response text.
pub fn word_count(&self) -> usize {
self.word_count
}
/// Create a new `FeroxResponse` from the given `Response`
pub async fn from(response: Response, read_body: bool) -> Self {
let url = response.url().clone();
let status = response.status();
let headers = response.headers().clone();
let content_length = response.content_length().unwrap_or(0);
let text = if read_body {
// .text() consumes the response, must be called last
// additionally, --extract-links is currently the only place we use the body of the
// response, so we forego the processing if not performing extraction
match response.text().await {
// await the response's body
Ok(text) => text,
Err(e) => {
log::error!("Could not parse body from response: {}", e);
String::new()
}
}
} else {
String::new()
};
let line_count = text.lines().count();
let word_count = text.lines().map(|s| s.split_whitespace().count()).sum();
FeroxResponse {
url,
status,
content_length,
text,
headers,
line_count,
word_count,
wildcard: false,
}
}
}
/// Implement FeroxSerialusize::from(ize for FeroxRespons)e
impl FeroxSerialize for FeroxResponse {
/// Simple wrapper around create_report_string
fn as_str(&self) -> String {
let lines = self.line_count().to_string();
let words = self.word_count().to_string();
let chars = self.content_length().to_string();
let status = self.status().as_str();
let wild_status = status_colorizer("WLD");
if self.wildcard {
// response is a wildcard, special messages abound when this is the case...
// create the base message
let mut message = format!(
"{} {:>8}l {:>8}w {:>8}c Got {} for {} (url length: {})\n",
wild_status,
lines,
words,
chars,
status_colorizer(&status),
self.url(),
get_url_path_length(&self.url())
);
if self.status().is_redirection() {
// when it's a redirect, show where it goes, if possible
if let Some(next_loc) = self.headers().get("Location") {
let next_loc_str = next_loc.to_str().unwrap_or("Unknown");
let redirect_msg = format!(
"{} {:>9} {:>9} {:>9} {} redirects to => {}\n",
wild_status,
"-",
"-",
"-",
self.url(),
next_loc_str
);
message.push_str(&redirect_msg);
}
}
// base message + redirection message (if appropriate)
message
} else {
// not a wildcard, just create a normal entry
utils::create_report_string(
self.status.as_str(),
&lines,
&words,
&chars,
self.url().as_str(),
)
}
}
/// Create an NDJSON representation of the FeroxResponse
///
/// (expanded for clarity)
/// ex:
/// {
/// "type":"response",
/// "url":"https://localhost.com/images",
/// "path":"/images",
/// "status":301,
/// "content_length":179,
/// "line_count":10,
/// "word_count":16,
/// "headers":{
/// "x-content-type-options":"nosniff",
/// "strict-transport-security":"max-age=31536000; includeSubDomains",
/// "x-frame-options":"SAMEORIGIN",
/// "connection":"keep-alive",
/// "server":"nginx/1.16.1",
/// "content-type":"text/html; charset=UTF-8",
/// "referrer-policy":"origin-when-cross-origin",
/// "content-security-policy":"default-src 'none'",
/// "access-control-allow-headers":"X-Requested-With",
/// "x-xss-protection":"1; mode=block",
/// "content-length":"179",
/// "date":"Mon, 23 Nov 2020 15:33:24 GMT",
/// "location":"/images/",
/// "access-control-allow-origin":"https://localhost.com"
/// }
/// }\n
fn as_json(&self) -> String {
if let Ok(mut json) = serde_json::to_string(&self) {
json.push('\n');
json
} else {
format!("{{\"error\":\"could not convert {} to json\"}}", self.url())
}
}
}
/// Serialize implementation for FeroxResponse
impl Serialize for FeroxResponse {
/// Function that handles serialization of a FeroxResponse to NDJSON
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut headers = HashMap::new();
let mut state = serializer.serialize_struct("FeroxResponse", 7)?;
// need to convert the HeaderMap to a HashMap in order to pass it to the serializer
for (key, value) in &self.headers {
let k = key.as_str().to_owned();
let v = String::from_utf8_lossy(value.as_bytes());
headers.insert(k, v);
}
state.serialize_field("type", "response")?;
state.serialize_field("url", self.url.as_str())?;
state.serialize_field("path", self.url.path())?;
state.serialize_field("wildcard", &self.wildcard)?;
state.serialize_field("status", &self.status.as_u16())?;
state.serialize_field("content_length", &self.content_length)?;
state.serialize_field("line_count", &self.line_count)?;
state.serialize_field("word_count", &self.word_count)?;
state.serialize_field("headers", &headers)?;
state.end()
}
}
/// Deserialize implementation for FeroxResponse
impl<'de> Deserialize<'de> for FeroxResponse {
/// Deserialize a FeroxResponse from a serde_json::Value
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let mut response = Self {
url: Url::parse("http://localhost").unwrap(),
status: StatusCode::OK,
text: String::new(),
content_length: 0,
headers: HeaderMap::new(),
wildcard: false,
line_count: 0,
word_count: 0,
};
let map: HashMap<String, Value> = HashMap::deserialize(deserializer)?;
for (key, value) in &map {
match key.as_str() {
"url" => {
if let Some(url) = value.as_str() {
if let Ok(parsed) = Url::parse(url) {
response.url = parsed;
}
}
}
"status" => {
if let Some(num) = value.as_u64() {
if let Ok(smaller) = u16::try_from(num) {
if let Ok(status) = StatusCode::from_u16(smaller) {
response.status = status;
}
}
}
}
"content_length" => {
if let Some(num) = value.as_u64() {
response.content_length = num;
}
}
"line_count" => {
if let Some(num) = value.as_u64() {
response.line_count = num.try_into().unwrap_or_default();
}
}
"word_count" => {
if let Some(num) = value.as_u64() {
response.word_count = num.try_into().unwrap_or_default();
}
}
"headers" => {
let mut headers = HeaderMap::<HeaderValue>::default();
if let Some(map_headers) = value.as_object() {
for (h_key, h_value) in map_headers {
let h_value_str = h_value.as_str().unwrap_or("");
let h_name = HeaderName::from_str(h_key)
.unwrap_or_else(|_| HeaderName::from_str("Unknown").unwrap());
let h_value_parsed = HeaderValue::from_str(h_value_str)
.unwrap_or_else(|_| HeaderValue::from_str("Unknown").unwrap());
headers.insert(h_name, h_value_parsed);
}
}
response.headers = headers;
}
"wildcard" => {
if let Some(result) = value.as_bool() {
response.wildcard = result;
}
}
_ => {}
}
}
Ok(response)
}
}
#[derive(Serialize, Deserialize, Default)]
/// Representation of a log entry, can be represented as a human readable string or JSON
pub struct FeroxMessage {
#[serde(rename = "type")]
/// Name of this type of struct, used for serialization, i.e. `{"type":"log"}`
kind: String,
/// The log message
pub message: String,
/// The log level
pub level: String,
/// The number of seconds elapsed since the scan started
pub time_offset: f32,
/// The module from which log::* was called
pub module: String,
}
/// Implementation of FeroxMessage
impl FeroxSerialize for FeroxMessage {
/// Create an NDJSON representation of the log message
///
/// (expanded for clarity)
/// ex:
/// {
/// "type": "log",
/// "message": "Sent https://localhost/api to file handler",
/// "level": "DEBUG",
/// "time_offset": 0.86333454,
/// "module": "feroxbuster::reporter"
/// }\n
fn as_json(&self) -> String {
if let Ok(mut json) = serde_json::to_string(&self) {
json.push('\n');
json
} else {
String::from("{\"error\":\"could not convert to json\"}")
}
}
/// Create a string representation of the log message
///
/// ex: 301 10l 16w 173c https://localhost/api
fn as_str(&self) -> String {
let (level_name, level_color) = match self.level.as_str() {
"ERROR" => ("ERR", Color::Red),
"WARN" => ("WRN", Color::Red),
"INFO" => ("INF", Color::Cyan),
"DEBUG" => ("DBG", Color::Yellow),
"TRACE" => ("TRC", Color::Magenta),
"WILDCARD" => ("WLD", Color::Cyan),
_ => ("UNK", Color::White),
};
format!(
"{} {:10.03} {} {}\n",
style(level_name).bg(level_color).black(),
style(self.time_offset).dim(),
self.module,
style(&self.message).dim(),
)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
/// asserts default config name is correct
fn default_config_name() {
assert_eq!(DEFAULT_CONFIG_NAME, "ferox-config.toml");
}
#[test]
/// asserts default wordlist is correct
fn default_wordlist() {
assert_eq!(
DEFAULT_WORDLIST,
"/usr/share/seclists/Discovery/Web-Content/raft-medium-directories.txt"
);
}
#[test]
/// asserts default version is correct
fn default_version() {
assert_eq!(VERSION, env!("CARGO_PKG_VERSION"));
}
#[test]
/// test as_str method of FeroxMessage
fn ferox_message_as_str_returns_string_with_newline() {
let message = FeroxMessage {
message: "message".to_string(),
module: "utils".to_string(),
time_offset: 1.0,
level: "INFO".to_string(),
kind: "log".to_string(),
};
let message_str = message.as_str();
assert!(message_str.contains("INF"));
assert!(message_str.contains("1.000"));
assert!(message_str.contains("utils"));
assert!(message_str.contains("message"));
assert!(message_str.ends_with('\n'));
}
#[test]
/// test as_json method of FeroxMessage
fn ferox_message_as_json_returns_json_representation_of_ferox_message_with_newline() {
let message = FeroxMessage {
message: "message".to_string(),
module: "utils".to_string(),
time_offset: 1.0,
level: "INFO".to_string(),
kind: "log".to_string(),
};
let message_str = message.as_json();
let error_margin = f32::EPSILON;
let json: FeroxMessage = serde_json::from_str(&message_str).unwrap();
assert_eq!(json.module, message.module);
assert_eq!(json.message, message.message);
assert!((json.time_offset - message.time_offset).abs() < error_margin);
assert_eq!(json.level, message.level);
assert_eq!(json.kind, message.kind);
}
}
|
// Here, we train an agent on the mountain car problem
// Currently, the agent does learn to make it to the top of the hill
// (which I think is a nontrivial accomplishment, but I'm not 100% sure)
// However, it takes it much longer than it should to get there
// At some point, I'll need to take some time to verify that I'm doing things
// correctly, and do more exploring with hyper parameters
extern crate renforce as re;
extern crate gym;
use std::io::stdin;
use re::environment::{Environment, Observation};
use re::environment::{Finite, Range};
use re::trainer::EpisodicTrainer;
use re::trainer::PolicyGradient;
use re::agent::Agent;
use re::agent::PolicyAgent;
use re::util::TimePeriod;
use re::util::approx::QLinear;
use re::util::feature::RBFeature;
use re::util::graddesc::GradDescMomentum;
use gym::GymClient;
struct MountainCar {
pub render: bool,
env: gym::Environment,
}
impl Environment for MountainCar {
type State = Vec<Range>;
type Action = Finite;
fn state_space(&self) -> Vec<Range> {
vec![Range::new(-1.2, 0.6), Range::new(-0.07, 0.07)]
}
fn action_space(&self) -> Finite {
// The agent has 3 actions: left, right, neutral
Finite::new(3)
}
fn step(&mut self, action: &u32) -> Observation<Vec<Range>> {
let obs = self.env.step(vec![*action as f64], self.render).unwrap();
Observation {
state: obs.observation,
reward: obs.reward,
done: obs.done
}
}
fn reset(&mut self) -> Observation<Vec<Range>> {
let state = self.env.reset().unwrap();
Observation {
state: state,
reward: 0.0,
done: false
}
}
fn render(&self) {}
}
impl MountainCar {
fn new() -> MountainCar {
let client = GymClient::new("http://localhost:5000".to_string());
let mut env = match client.make("MountainCar-v0") {
Ok(env) => env,
Err(msg) => panic!("Could not make environment because of error:\n{}\n\nMake sure you have a [gym server](https://github.com/openai/gym-http-api) running.", msg)
};
let _ = env.reset();
MountainCar {env: env, render: false}
}
}
fn main() {
let mut env = MountainCar::new();
let mut log_prob_func = QLinear::default(&env.action_space());
for i in 0..18 {
for j in 0..14 {
let (x, y) = (-1.2 + 0.1 * i as f64, -0.07 + 0.01 * j as f64);
log_prob_func.add(Box::new(RBFeature::new(vec![x, y], 0.1)));
}
}
// Creates an agent that acts randomly
// The (log of the) probability of each action is determined by log_prob_func
let mut agent = PolicyAgent::new(env.action_space(), log_prob_func, 0.5);
// PolicyGradient will evalute agents for 3 episode or 20000 time steps
// whichever comes first
let tp = TimePeriod::OR(Box::new(TimePeriod::EPISODES(3)), Box::new(TimePeriod::TIMESTEPS(20000)));
// Train agent using Policy gradients
let mut trainer = PolicyGradient::default(GradDescMomentum::default()).eval_period(tp)
.iters(20);
println!("Training...");
trainer.train(&mut agent, &mut env);
println!("Done training (press enter)");
env.render = true;
let _ = stdin().read_line(&mut String::new());
// Simulate one episode of the environment to see what the agent learned
let mut obs = env.reset();
let mut reward = 0.0;
while !obs.done {
let action = agent.get_action(&obs.state);
obs = env.step(&action);
reward += obs.reward;
}
println!("total reward: {}", reward);
}
|
use std::mem;
use std::ptr::null_mut;
use widestring::WideCStr;
use winapi::shared::guiddef::GUID;
use winapi::shared::minwindef::ULONG;
use winapi::shared::winerror::SUCCEEDED;
use winapi::um::bits::{BG_ERROR_CONTEXT, BG_JOB_PROGRESS, BG_JOB_STATE};
use winapi::um::winnt::HRESULT;
use util::{BCErrHolder, BCJobHolder, BCMHolder};
use {ErrorKind, Result, ResultExt};
const BACKGROUND_COPY_MANAGER: GUID = GUID {
Data1: 0x4991d34b,
Data2: 0x80a1,
Data3: 0x4291,
Data4: [0x83, 0xb6, 0x33, 0x28, 0x36, 0x6b, 0x90, 0x97],
};
pub fn create_job<T: AsRef<WideCStr>>(name: T) -> Result<(GUID, BCJobHolder)> {
// TODO: handle differently error:
// - job already exists
use winapi::um::bits::{IBackgroundCopyJob, BG_JOB_TYPE_DOWNLOAD};
let bcm =
connect_bcm().chain_err(|| ErrorKind::FailMessage("Connect Background Copy Manager"))?;
let mut guid;
let mut pjob: *mut IBackgroundCopyJob = null_mut();
let rc = unsafe {
guid = mem::uninitialized();
(**bcm).CreateJob(
name.as_ref().as_ptr(),
BG_JOB_TYPE_DOWNLOAD,
&mut guid,
&mut pjob,
)
};
if !SUCCEEDED(rc) {
return Err(ErrorKind::OSErrorHRESULT("CreateJob", rc).into());
}
Ok((guid, BCJobHolder(pjob)))
}
pub fn cancel_job(guid: &GUID) -> Result<()> {
let job = get_job(guid)?;
let rc = unsafe { (**job).Cancel() };
if !SUCCEEDED(rc) {
return Err(ErrorKind::OSErrorHRESULT("Cancel job", rc).into());
}
Ok(())
}
pub fn add_file<T, U>(guid: &GUID, remote_url: &T, local_file: &U) -> Result<()>
where
T: AsRef<WideCStr>,
U: AsRef<WideCStr>,
{
let job = get_job(guid)?;
let rc = unsafe { (**job).AddFile(remote_url.as_ref().as_ptr(), local_file.as_ref().as_ptr()) };
if !SUCCEEDED(rc) {
return Err(ErrorKind::OSErrorHRESULT("AddFile to job", rc).into());
}
Ok(())
}
pub fn resume(guid: &GUID) -> Result<()> {
let job = get_job(guid)?;
let rc = unsafe { (**job).Resume() };
if !SUCCEEDED(rc) {
return Err(ErrorKind::OSErrorHRESULT("Resume job", rc).into());
}
Ok(())
}
pub fn suspend(guid: &GUID) -> Result<()> {
let job = get_job(guid)?;
let rc = unsafe { (**job).Suspend() };
if !SUCCEEDED(rc) {
return Err(ErrorKind::OSErrorHRESULT("Suspend job", rc).into());
}
Ok(())
}
pub fn complete(guid: &GUID) -> Result<()> {
let job = get_job(guid)?;
let rc = unsafe { (**job).Complete() };
if !SUCCEEDED(rc) {
return Err(ErrorKind::OSErrorHRESULT("Complete job", rc).into());
}
Ok(())
}
pub struct BCJobError {
pub context: BG_ERROR_CONTEXT,
pub error: HRESULT,
}
pub struct BCJobStatus {
pub state: BG_JOB_STATE,
pub progress: BG_JOB_PROGRESS,
pub error_count: ULONG,
pub error: Option<BCJobError>,
}
pub fn get_status(guid: &GUID) -> Result<BCJobStatus> {
use winapi::um::bits::{BG_JOB_STATE_ERROR, BG_JOB_STATE_TRANSIENT_ERROR};
let job = get_job(guid)?;
let mut state = 0;
let rc = unsafe { (**job).GetState(&mut state) };
if !SUCCEEDED(rc) {
return Err(ErrorKind::OSErrorHRESULT("GetState", rc).into());
}
let mut progress;
let rc = unsafe {
progress = mem::uninitialized();
(**job).GetProgress(&mut progress)
};
if !SUCCEEDED(rc) {
return Err(ErrorKind::OSErrorHRESULT("GetProgress", rc).into());
}
// TODO: is this working properly? haven't seen it report anything but 0 even with a
// transient error, but I'm having trouble causing permanent errors...
let mut error_count = 0;
let rc = unsafe { (**job).GetErrorCount(&mut error_count) };
if !SUCCEEDED(rc) {
return Err(ErrorKind::OSErrorHRESULT("GetErrorCount", rc).into());
}
let error;
if state == BG_JOB_STATE_ERROR || state == BG_JOB_STATE_TRANSIENT_ERROR {
let error_obj = {
let mut perror = null_mut();
let rc = unsafe { (**job).GetError(&mut perror) };
if !SUCCEEDED(rc) {
return Err(ErrorKind::OSErrorHRESULT("GetError for job", rc).into());
}
BCErrHolder(perror)
};
let mut error_context = 0;
let mut error_hresult = 0;
let rc = unsafe { (**error_obj).GetError(&mut error_context, &mut error_hresult) };
if !SUCCEEDED(rc) {
return Err(ErrorKind::OSErrorHRESULT("GetError for error", rc).into());
}
error = Some(BCJobError {
context: error_context,
error: error_hresult,
});
} else {
error = None;
}
Ok(BCJobStatus {
state,
progress,
error_count,
error,
})
}
fn get_job(guid: &GUID) -> Result<BCJobHolder> {
let bcm =
connect_bcm().chain_err(|| ErrorKind::FailMessage("Connect Background Copy Manager"))?;
let mut pjob = null_mut();
let rc = unsafe { (**bcm).GetJob(guid, &mut pjob) };
if !SUCCEEDED(rc) {
return Err(ErrorKind::OSErrorHRESULT("GetJob", rc).into());
}
Ok(BCJobHolder(pjob))
}
fn connect_bcm() -> Result<BCMHolder> {
use winapi::shared::minwindef::LPVOID;
use winapi::shared::wtypesbase::CLSCTX_LOCAL_SERVER;
use winapi::um::bits::IBackgroundCopyManager;
use winapi::um::combaseapi::CoCreateInstance;
use winapi::Interface;
let mut pbcm: *mut IBackgroundCopyManager = null_mut();
let rc = unsafe {
CoCreateInstance(
&BACKGROUND_COPY_MANAGER,
null_mut(), // pUnkOuter
CLSCTX_LOCAL_SERVER,
&IBackgroundCopyManager::uuidof() as *const GUID,
&mut pbcm as *mut *mut IBackgroundCopyManager as *mut LPVOID,
)
};
if !SUCCEEDED(rc) {
return Err(ErrorKind::OSErrorHRESULT("CoCreateInstance", rc).into());
}
Ok(BCMHolder(pbcm))
}
|
// Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![deny(clippy::while_let_on_iterator)]
use std::iter::Iterator;
struct Foo;
impl Foo {
fn foo1<I: Iterator<Item = usize>>(mut it: I) {
while let Some(_) = it.next() {
println!("{:?}", it.size_hint());
}
}
fn foo2<I: Iterator<Item = usize>>(mut it: I) {
while let Some(e) = it.next() {
println!("{:?}", e);
}
}
}
fn main() {
Foo::foo1(vec![].into_iter());
Foo::foo2(vec![].into_iter());
}
|
use devices;
use errors::Result;
pub fn list_devices() -> Result<()> {
for device in devices::list_devices()? {
println!("{} {:?} {:?}", device.name(), device.get_product(), device.get_serial());
}
Ok(())
}
|
// Copyright 2021. The Tari Project
// SPDX-License-Identifier: BSD-3-Clause
use alloc::vec::Vec;
use core::{
cmp::Ordering,
hash::{Hash, Hasher},
ops::{Add, Mul},
};
use rand_core::{CryptoRng, RngCore};
use snafu::prelude::*;
use tari_utilities::ByteArray;
use crate::{
alloc::borrow::ToOwned,
commitment::{HomomorphicCommitment, HomomorphicCommitmentFactory},
keys::{PublicKey, SecretKey},
};
/// An error when creating a commitment signature
#[derive(Clone, Debug, Snafu, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[allow(missing_docs)]
pub enum CommitmentAndPublicKeySignatureError {
#[snafu(display("An invalid challenge was provided"))]
InvalidChallenge,
}
/// # Commitment and public key (CAPK) signatures
///
/// Given a commitment `commitment = a*H + x*G` and group element `pubkey = y*G`, a CAPK signature is based on
/// a representation proof of both openings: `(a, x)` and `y`. It additionally binds to arbitrary message data `m`
/// via the challenge to produce a signature construction.
///
/// It is used in Tari protocols as part of transaction authorization.
///
/// The construction works as follows:
/// - Sample scalar nonces `r_a, r_x, r_y` uniformly at random.
/// - Compute ephemeral values `ephemeral_commitment = r_a*H + r_x*G` and `ephemeral_pubkey = r_y*G`.
/// - Use strong Fiat-Shamir to produce a challenge `e`. If `e == 0` (this is unlikely), abort and start over.
/// - Compute the responses `u_a = r_a + e*a` and `u_x = r_x + e*x` and `u_y = r_y + e*y`.
///
/// The signature is the tuple `(ephemeral_commitment, ephemeral_pubkey, u_a, u_x, u_y)`.
///
/// To verify:
/// - The verifier computes the challenge `e` and rejects the signature if `e == 0` (this is unlikely).
/// - Verification succeeds if and only if the following equations hold: `u_a*H + u*x*G == ephemeral_commitment +
/// e*commitment` `u_y*G == ephemeral_pubkey + e*pubkey`
///
/// We note that it is possible to make verification slightly more efficient. To do so, the verifier selects a nonzero
/// scalar weight `w` uniformly at random (not through Fiat-Shamir!) and accepts the signature if and only if the
/// following equation holds:
/// `u_a*H + (u_x + w*u_y)*G - ephemeral_commitment - w*ephemeral_pubkey - e*commitment - (w*e)*pubkey == 0`
/// The use of efficient multiscalar multiplication algorithms may also be useful for efficiency.
/// The use of precomputation tables for `G` and `H` may also be useful for efficiency.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "borsh", derive(borsh::BorshSerialize, borsh::BorshDeserialize))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct CommitmentAndPublicKeySignature<P, K> {
ephemeral_commitment: HomomorphicCommitment<P>,
ephemeral_pubkey: P,
u_a: K,
u_x: K,
u_y: K,
}
impl<P, K> CommitmentAndPublicKeySignature<P, K>
where
P: PublicKey<K = K>,
K: SecretKey,
{
/// Creates a new [CommitmentSignature]
pub fn new(ephemeral_commitment: HomomorphicCommitment<P>, ephemeral_pubkey: P, u_a: K, u_x: K, u_y: K) -> Self {
CommitmentAndPublicKeySignature {
ephemeral_commitment,
ephemeral_pubkey,
u_a,
u_x,
u_y,
}
}
/// Complete a signature using the given challenge. The challenge is provided by the caller to support the
/// multiparty use case. It is _very important_ that it be computed using strong Fiat-Shamir! Further, the
/// values `r_a, r_x, r_y` are nonces, must be sampled uniformly at random, and must never be reused.
#[allow(clippy::too_many_arguments)]
pub fn sign<C>(
a: &K,
x: &K,
y: &K,
r_a: &K,
r_x: &K,
r_y: &K,
challenge: &[u8],
factory: &C,
) -> Result<Self, CommitmentAndPublicKeySignatureError>
where
K: Mul<P, Output = P>,
for<'a> &'a K: Add<&'a K, Output = K>,
for<'a> &'a K: Mul<&'a K, Output = K>,
C: HomomorphicCommitmentFactory<P = P>,
{
// The challenge must be a valid scalar
let e = match K::from_bytes(challenge) {
Ok(e) => e,
Err(_) => return Err(CommitmentAndPublicKeySignatureError::InvalidChallenge),
};
// The challenge cannot be zero
if e == K::default() {
return Err(CommitmentAndPublicKeySignatureError::InvalidChallenge);
}
// Compute the response values
let ea = &e * a;
let ex = &e * x;
let ey = &e * y;
let u_a = r_a + &ea;
let u_x = r_x + &ex;
let u_y = r_y + &ey;
// Compute the initial values
let ephemeral_commitment = factory.commit(r_x, r_a);
let ephemeral_pubkey = P::from_secret_key(r_y);
Ok(Self::new(ephemeral_commitment, ephemeral_pubkey, u_a, u_x, u_y))
}
/// Verify a signature on a commitment and group element statement using a given challenge (as a byte array)
pub fn verify_challenge<'a, C, R>(
&self,
commitment: &'a HomomorphicCommitment<P>,
pubkey: &'a P,
challenge: &[u8],
factory: &C,
rng: &mut R,
) -> bool
where
for<'b> &'a HomomorphicCommitment<P>: Mul<&'b K, Output = HomomorphicCommitment<P>>,
for<'b> &'b P: Mul<&'b K, Output = P>,
for<'b> &'b HomomorphicCommitment<P>: Add<&'b HomomorphicCommitment<P>, Output = HomomorphicCommitment<P>>,
for<'b> &'b P: Add<&'b P, Output = P>,
for<'b> &'b K: Mul<&'b K, Output = K>,
for<'b> &'b K: Add<&'b K, Output = K>,
C: HomomorphicCommitmentFactory<P = P>,
R: RngCore + CryptoRng,
{
// The challenge must be a valid scalar
let e = match K::from_bytes(challenge) {
Ok(e) => e,
Err(_) => return false,
};
self.verify(commitment, pubkey, &e, factory, rng)
}
/// Verify a signature on a commitment and group element statement using a given challenge (as a scalar)
pub fn verify<'a, C, R>(
&self,
commitment: &'a HomomorphicCommitment<P>,
pubkey: &'a P,
challenge: &K,
factory: &C,
rng: &mut R,
) -> bool
where
for<'b> &'a HomomorphicCommitment<P>: Mul<&'b K, Output = HomomorphicCommitment<P>>,
for<'b> &'b P: Mul<&'b K, Output = P>,
for<'b> &'b HomomorphicCommitment<P>: Add<&'b HomomorphicCommitment<P>, Output = HomomorphicCommitment<P>>,
for<'b> &'b P: Add<&'b P, Output = P>,
for<'b> &'b K: Mul<&'b K, Output = K>,
for<'b> &'b K: Add<&'b K, Output = K>,
C: HomomorphicCommitmentFactory<P = P>,
R: RngCore + CryptoRng,
{
// The challenge cannot be zero
if *challenge == K::default() {
return false;
}
// Use a single weighted equation for verification to avoid unnecessary group operations
// For now, we use naive multiscalar multiplication, but offload the commitment computation
// This allows for the use of precomputation within the commitment itself, which is more efficient
let w = K::random(rng); // must be random and not Fiat-Shamir!
// u_a*H + (u_x + w*u_y)*G == ephemeral_commitment + w*ephemeral_pubkey + e*commitment + (w*e)*pubkey
let verifier_lhs = factory
.commit(&(&self.u_x + &(&w * &self.u_y)), &self.u_a)
.as_public_key()
.to_owned();
let verifier_rhs_unweighted =
self.ephemeral_commitment.as_public_key() + (commitment * challenge).as_public_key();
let verifier_rhs_weighted = &self.ephemeral_pubkey * &w + pubkey * &(&w * challenge);
verifier_lhs == verifier_rhs_unweighted + verifier_rhs_weighted
}
/// Get the signature tuple `(ephemeral_commitment, ephemeral_pubkey, u_a, u_x, u_y)`
pub fn complete_signature_tuple(&self) -> (&HomomorphicCommitment<P>, &P, &K, &K, &K) {
(
&self.ephemeral_commitment,
&self.ephemeral_pubkey,
&self.u_a,
&self.u_x,
&self.u_y,
)
}
/// Get the response value `u_a`
pub fn u_a(&self) -> &K {
&self.u_a
}
/// Get the response value `u_x`
pub fn u_x(&self) -> &K {
&self.u_x
}
/// Get the response value `u_y`
pub fn u_y(&self) -> &K {
&self.u_y
}
/// Get the ephemeral commitment `ephemeral_commitment`
pub fn ephemeral_commitment(&self) -> &HomomorphicCommitment<P> {
&self.ephemeral_commitment
}
/// Get the ephemeral public key `ephemeral_pubkey`
pub fn ephemeral_pubkey(&self) -> &P {
&self.ephemeral_pubkey
}
/// Produce a canonical byte representation of the commitment signature
pub fn to_vec(&self) -> Vec<u8> {
let mut buf = Vec::with_capacity(2 * P::key_length() + 3 * K::key_length());
buf.extend_from_slice(self.ephemeral_commitment().as_bytes());
buf.extend_from_slice(self.ephemeral_pubkey().as_bytes());
buf.extend_from_slice(self.u_a().as_bytes());
buf.extend_from_slice(self.u_x().as_bytes());
buf.extend_from_slice(self.u_y().as_bytes());
buf
}
}
impl<'a, 'b, P, K> Add<&'b CommitmentAndPublicKeySignature<P, K>> for &'a CommitmentAndPublicKeySignature<P, K>
where
P: PublicKey<K = K>,
&'a HomomorphicCommitment<P>: Add<&'b HomomorphicCommitment<P>, Output = HomomorphicCommitment<P>>,
&'a P: Add<&'b P, Output = P>,
K: SecretKey,
&'a K: Add<&'b K, Output = K>,
{
type Output = CommitmentAndPublicKeySignature<P, K>;
fn add(self, rhs: &'b CommitmentAndPublicKeySignature<P, K>) -> CommitmentAndPublicKeySignature<P, K> {
let ephemeral_commitment_sum = self.ephemeral_commitment() + rhs.ephemeral_commitment();
let ephemeral_pubkey_sum_sum = self.ephemeral_pubkey() + rhs.ephemeral_pubkey();
let u_a_sum = self.u_a() + rhs.u_a();
let u_x_sum = self.u_x() + rhs.u_x();
let u_y_sum = self.u_y() + rhs.u_y();
CommitmentAndPublicKeySignature::new(
ephemeral_commitment_sum,
ephemeral_pubkey_sum_sum,
u_a_sum,
u_x_sum,
u_y_sum,
)
}
}
impl<'a, P, K> Add<CommitmentAndPublicKeySignature<P, K>> for &'a CommitmentAndPublicKeySignature<P, K>
where
P: PublicKey<K = K>,
for<'b> &'a HomomorphicCommitment<P>: Add<&'b HomomorphicCommitment<P>, Output = HomomorphicCommitment<P>>,
for<'b> &'a P: Add<&'b P, Output = P>,
K: SecretKey,
for<'b> &'a K: Add<&'b K, Output = K>,
{
type Output = CommitmentAndPublicKeySignature<P, K>;
fn add(self, rhs: CommitmentAndPublicKeySignature<P, K>) -> CommitmentAndPublicKeySignature<P, K> {
let ephemeral_commitment_sum = self.ephemeral_commitment() + rhs.ephemeral_commitment();
let ephemeral_pubkey_sum_sum = self.ephemeral_pubkey() + rhs.ephemeral_pubkey();
let u_a_sum = self.u_a() + rhs.u_a();
let u_x_sum = self.u_x() + rhs.u_x();
let u_y_sum = self.u_y() + rhs.u_y();
CommitmentAndPublicKeySignature::new(
ephemeral_commitment_sum,
ephemeral_pubkey_sum_sum,
u_a_sum,
u_x_sum,
u_y_sum,
)
}
}
impl<P, K> Default for CommitmentAndPublicKeySignature<P, K>
where
P: PublicKey<K = K>,
K: SecretKey,
{
fn default() -> Self {
CommitmentAndPublicKeySignature::new(
HomomorphicCommitment::<P>::default(),
P::default(),
K::default(),
K::default(),
K::default(),
)
}
}
/// Provide a canonical ordering for commitment signatures. We use byte representations of all values in this order:
/// `ephemeral_commitment, ephemeral_pubkey, u_a, u_x, u_y`
impl<P, K> Ord for CommitmentAndPublicKeySignature<P, K>
where
P: PublicKey<K = K>,
K: SecretKey,
{
fn cmp(&self, other: &Self) -> Ordering {
let mut compare = self.ephemeral_commitment().cmp(other.ephemeral_commitment());
if compare != Ordering::Equal {
return compare;
}
compare = self.ephemeral_pubkey().cmp(other.ephemeral_pubkey());
if compare != Ordering::Equal {
return compare;
}
compare = self.u_a().as_bytes().cmp(other.u_a().as_bytes());
if compare != Ordering::Equal {
return compare;
}
compare = self.u_x().as_bytes().cmp(other.u_x().as_bytes());
if compare != Ordering::Equal {
return compare;
}
self.u_y().as_bytes().cmp(other.u_y().as_bytes())
}
}
impl<P, K> PartialOrd for CommitmentAndPublicKeySignature<P, K>
where
P: PublicKey<K = K>,
K: SecretKey,
{
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl<P, K> PartialEq for CommitmentAndPublicKeySignature<P, K>
where
P: PublicKey<K = K>,
K: SecretKey,
{
fn eq(&self, other: &Self) -> bool {
self.ephemeral_commitment().eq(other.ephemeral_commitment()) &&
self.ephemeral_pubkey().eq(other.ephemeral_pubkey()) &&
self.u_a().eq(other.u_a()) &&
self.u_x().eq(other.u_x()) &&
self.u_y().eq(other.u_y())
}
}
impl<P, K> Eq for CommitmentAndPublicKeySignature<P, K>
where
P: PublicKey<K = K>,
K: SecretKey,
{
}
impl<P, K> Hash for CommitmentAndPublicKeySignature<P, K>
where
P: PublicKey<K = K>,
K: SecretKey,
{
fn hash<H: Hasher>(&self, state: &mut H) {
state.write(&self.to_vec())
}
}
|
// Copyright 2020 <盏一 w@hidva.com>
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::access::sv;
use crate::access::TypeDesc;
use crate::catalog::namespace::SessionExt;
use crate::catalog::{qualname_get_type, FormType};
use crate::guc;
use crate::kbbail;
use crate::parser::syn;
use crate::utility::Response;
use crate::utils::{persist, sync_dir};
use crate::utils::{ExecSQLOnDrop, SessionState};
use crate::xact::SessionExt as XACTSessionExt;
use anyhow::ensure;
use std::fs;
struct TupleDesc {
pub desc: Vec<TypeDesc>,
}
// LookupTypeNameExtended
fn get_type_desc(
state: &mut SessionState,
typnam: &syn::TypeName<'_>,
) -> anyhow::Result<Option<FormType>> {
ensure!(typnam.typmods.is_empty(), "typemod is not support now");
let (schema, typname) = state.deconstruct_qualname(&typnam.names)?;
let formtype = if let Some(schema) = schema {
let nsoid = state.get_namespace_oid(schema)?;
qualname_get_type(state, nsoid, typname)?
} else {
state.typname_get_type(typname)?
};
return Ok(formtype);
}
// typenameType
fn typname_type(state: &mut SessionState, typnam: &syn::TypeName<'_>) -> anyhow::Result<TypeDesc> {
let formtype = get_type_desc(state, typnam)?;
if let Some(formtype) = formtype {
if !formtype.isdefined {
kbbail!(
ERRCODE_UNDEFINED_OBJECT,
"type {:?} is only a shell",
typnam
);
}
return Ok(TypeDesc {
id: formtype.id,
len: formtype.len,
align: formtype.align,
mode: -1,
});
}
kbbail!(ERRCODE_UNDEFINED_OBJECT, "type {:?} does not exist", typnam);
}
// BuildDescForRelation
fn build_desc(
state: &mut SessionState,
table_elts: &Vec<syn::ColumnDef<'_>>,
) -> anyhow::Result<TupleDesc> {
let mut ts = TupleDesc {
desc: Vec::with_capacity(table_elts.len()),
};
for cf in table_elts {
ts.desc.push(typname_type(state, &cf.typename)?);
}
return Ok(ts);
}
fn get_relopt(stmt: &syn::CreateTableStmt, state: &mut SessionState) -> String {
let mut ret: Vec<String> = vec![];
let mut meet_mvcc_blk_rows = false;
for defelem in &stmt.opts {
let (name, val) = match defelem {
syn::DefElem::Unspec(v) | syn::DefElem::Add(v) => (&v.defname, &v.arg),
_ => continue,
};
ret.push(format!("{}={}", name, val));
let name: &str = name;
if name == "mvcc_blk_rows" {
meet_mvcc_blk_rows = true;
}
}
if !meet_mvcc_blk_rows {
ret.push(format!(
"mvcc_blk_rows={}",
guc::get_int(&state.gucstate, guc::MvccBlkRows)
));
}
return ret.join(",");
}
pub fn create_table(
stmt: &syn::CreateTableStmt,
state: &mut SessionState,
) -> anyhow::Result<Response> {
state.prevent_in_transblock("CREATE TABLE")?;
let nsoid = state.rv_get_create_ns(&stmt.relation)?;
let tableoid = state.new_oid();
let tupdesc = build_desc(state, &stmt.table_elts)?;
let xid = state.get_xid()?;
state.metaconn.execute("begin")?;
let relopt = get_relopt(stmt, state);
let _rollback = ExecSQLOnDrop::new(&state.metaconn, "rollback");
let relname: &str = &stmt.relation.relname;
state.metaconn.execute(format!(
"insert into kb_class values({}, '{}', {}, false, 114, {}, {}, '{}')",
tableoid,
relname,
nsoid,
tupdesc.desc.len(),
xid,
relopt,
))?;
for attidx in 0..tupdesc.desc.len() {
let attnum = attidx + 1;
let typdesc = &tupdesc.desc[attidx];
let attname: &str = &stmt.table_elts[attidx].colname;
let sql = format!(
"insert into kb_attribute values({}, '{}', {}, {}, {}, {}, {}, 0, 0)",
tableoid, attname, typdesc.id, typdesc.len, typdesc.align, attnum, typdesc.mode
);
state.metaconn.execute(sql)?;
}
fs::create_dir(format!("base/{}/{}", state.reqdb, tableoid))?;
sync_dir(format!("base/{}", state.reqdb))?;
persist(
sv::get_minafest_path(state.reqdb, tableoid),
&sv::INIT_MANIFEST_DAT,
)?;
state.metaconn.execute("commit")?;
std::mem::forget(_rollback);
return Ok(Response::new("CREATE TABLE"));
}
|
/*
chapter 4
syntax and semantics
*/
trait Foo {
fn is_valid(&self) -> bool;
fn is_invalid(&self) -> bool { !self.is_valid() }
}
fn main() {}
// output should be:
/*
*/
|
use crate::VarIntWrite;
use std::io::Write;
use byteorder::WriteBytesExt;
pub struct VelocityVarIntWrite;
impl VarIntWrite for VelocityVarIntWrite {
#[inline]
fn write<W: Write>(mut writer: W, value: i32) -> std::io::Result<()> {
let mut value = value as u32;
loop {
if value & 0xFF_FF_FF_80 == 0 {
writer.write_u8(value as u8)?;
return Ok(());
}
writer.write_u8((value & 0x7F | 0x80) as u8)?;
value >>= 7;
}
}
} |
//! Module handling all connections to clients, including REST and Web Sockets.
//! The module will handle requests and interface between the clients and game/lobby as needed.
//#region Modules and Use Statements
mod account_handlers;
mod errors;
mod game_handlers;
mod validation;
use game_handlers::GameCollection;
use std::collections::HashMap;
use std::convert::Infallible;
use std::sync::{Arc, Mutex};
use validation::TokenManager;
use warp::{
body,
filters::cookie,
reject::{self, Reject},
Filter, Rejection,
};
//#endregion
const API_BASE_PATH: &str = "api";
const REFRESH_TOKEN_COOKIE: &str = "refreshToken";
#[derive(Debug, PartialEq)]
struct InvalidTokenRejection;
impl Reject for InvalidTokenRejection {}
/// Main entry point. Serves all warp connections and paths.
/// This function does not return unless warp crashes (bad),
/// or the server is being shut down.
pub async fn serve_connections() {
let token_manager = TokenManager::new();
let game_collection: GameCollection = Arc::new(Mutex::new(HashMap::new()));
// TEST ROUTES
let path_test = warp::path("hi").map(|| "Hello, World!");
let restricted_path_test = warp::path("restricted_hi")
.and(authorize_request(&token_manager))
.map(|_| "Hello, restricted world!");
// Account and Security
let add_user_route = warp::path!("add" / "user")
.and(body::json())
.and(with_token_manager(token_manager.clone()))
.and_then(account_handlers::handle_add_user);
let login_route = warp::path!("auth" / "login")
.and(body::json())
.and(with_token_manager(token_manager.clone()))
.and_then(account_handlers::handle_user_login);
let logout_route = warp::path!("auth" / "logout")
.and(cookie::cookie(REFRESH_TOKEN_COOKIE))
.and(with_token_manager(token_manager.clone()))
.and_then(account_handlers::handle_logout);
let get_user_info_route = warp::path!("get" / "user")
.and(authorize_request(&token_manager))
.and_then(account_handlers::get_user_account_info);
let refresh_jwt_route = warp::path!("auth" / "refresh")
.and(cookie::cookie(REFRESH_TOKEN_COOKIE))
.and(with_token_manager(token_manager.clone()))
.and_then(account_handlers::renew_refresh_token);
let delete_user_route = warp::path!("remove" / "user")
.and(authorize_request(&token_manager))
.and_then(account_handlers::delete_user);
let update_user_route = warp::path!("update" / "user")
.and(body::json())
.and(authorize_request(&token_manager))
.and_then(account_handlers::update_user);
let verify_account_route = warp::path!("update" / "verifed_email")
.and(body::json())
.and_then(account_handlers::verify_account);
// Game routes
let create_game_route = warp::path!("add" / "game")
.and(authorize_request(&token_manager))
.and(with_game_collection(game_collection.clone()))
.and_then(game_handlers::create_game);
let join_game_route = warp::path!("join" / "game")
.and(body::json())
.and(authorize_request(&token_manager))
.and(with_game_collection(game_collection.clone()))
.and_then(game_handlers::join_game);
let ws_route = warp::path("ws")
.and(warp::ws())
.and(warp::path::param())
.and(warp::path::param())
.and(with_game_collection(game_collection.clone()))
.and_then(game_handlers::connect_ws);
// Putting everything together
let get_routes = warp::get().and(
path_test
.or(restricted_path_test)
.or(get_user_info_route)
.or(ws_route),
);
let post_routes = warp::post().and(
add_user_route
.or(login_route)
.or(refresh_jwt_route)
.or(logout_route)
.or(create_game_route)
.or(join_game_route),
);
let delete_routes = warp::delete().and(delete_user_route);
let put_routes = warp::put().and(update_user_route.or(verify_account_route));
let cors = warp::cors()
.allow_any_origin()
.allow_headers(vec![
"User-Agent",
"Sec-Fetch-Mode",
"Referer",
"Origin",
"Access-Control-Request-Method",
"Access-Control-Request-Headers",
"Content-Type",
"Authorization",
])
.allow_methods(vec!["POST", "GET", "PUT", "DELETE"])
.allow_credentials(true);
let all_routes = warp::path(API_BASE_PATH)
.and(get_routes.or(post_routes).or(delete_routes).or(put_routes))
.recover(errors::recover_errors)
.with(cors);
warp::serve(all_routes).run(([0, 0, 0, 0], 8001)).await;
}
/// Authorizes a request for downstream endpoints.
/// This function returns a filter that passes along the user ID or a rejection.
fn authorize_request(
token_manager: &TokenManager,
) -> impl Filter<Extract = (String,), Error = Rejection> + Clone {
log::info!("Restricted API called. Validating auth header.");
warp::header::<String>("Authorization")
.and(with_token_manager(token_manager.clone()))
.and_then(authorize_user)
}
/// Authorizes a user via JWT.
/// Returns either the user ID or a rejection if the user isn't authorized.
async fn authorize_user(header: String, token_manager: TokenManager) -> Result<String, Rejection> {
log::info!("Authorizing user for restricted API by JWT.");
let token_pieces: Vec<&str> = header.split(' ').collect();
if token_pieces.len() < 2 {
log::info!(
"Invalid header format received. Received {}. Expected \"Basic <token>\".",
header
);
return Err(reject::custom(InvalidTokenRejection));
}
let token = token_pieces[1];
let player_id = match token_manager.validate_jwt(token).await {
Ok(player_id) => player_id,
Err(_) => {
log::info!("JWT is not valid. Rejecting request.");
return Err(reject::custom(InvalidTokenRejection));
}
};
log::info!(
"User {} is authorized for the requested service.",
player_id
);
Ok(player_id)
}
/// Moves a token_store reference into downstream filters.
/// Used to add and validate refresh tokens and JWTs.
///
/// # Arguments
///
/// `token_store` - A token store with all active refresh tokens
fn with_token_manager(
token_manager: TokenManager,
) -> impl Filter<Extract = (TokenManager,), Error = Infallible> + Clone {
warp::any().map(move || token_manager.clone())
}
fn with_game_collection(
game_collection: GameCollection,
) -> impl Filter<Extract = (GameCollection,), Error = Infallible> + Clone {
warp::any().map(move || game_collection.clone())
}
|
use crate::error::{NiaServerError, NiaServerResult};
use crate::protocol::{KeyDescription, Serializable, DEFAULT_DEVICE_MODEL};
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DeviceModel {
key_descriptions: Vec<KeyDescription>,
device_width: i32,
device_height: i32,
}
impl DeviceModel {
pub fn new(
key_descriptions: Vec<KeyDescription>,
device_width: i32,
device_height: i32,
) -> DeviceModel {
DeviceModel {
key_descriptions,
device_width,
device_height,
}
}
pub fn from_string<S>(string: S) -> NiaServerResult<DeviceModel>
where
S: Into<String>,
{
let string = string.into();
let integers: Vec<i32> = string
.lines()
.flat_map(|line| line.split_whitespace())
.map(|part| part.parse().expect("Cannot convert an integer"))
.collect();
let mut iter = integers.into_iter().peekable();
let device_width = iter.next().ok_or_else(|| {
NiaServerError::deserialization_error("Invalid kbm file")
})?;
let device_height = iter.next().ok_or_else(|| {
NiaServerError::deserialization_error("Invalid kbm file")
})?;
let mut key_descriptions = Vec::new();
while iter.peek().is_some() {
let x = iter.next().ok_or_else(|| {
NiaServerError::deserialization_error("Invalid kbm file")
})?;
let y = iter.next().ok_or_else(|| {
NiaServerError::deserialization_error("Invalid kbm file")
})?;
let width = iter.next().ok_or_else(|| {
NiaServerError::deserialization_error("Invalid kbm file")
})?;
let height = iter.next().ok_or_else(|| {
NiaServerError::deserialization_error("Invalid kbm file")
})?;
let key_code = iter.next().ok_or_else(|| {
NiaServerError::deserialization_error("Invalid kbm file")
})?;
let key_description =
KeyDescription::new(x, y, width, height, key_code);
key_descriptions.push(key_description)
}
let device_model =
DeviceModel::new(key_descriptions, device_width, device_height);
Ok(device_model)
}
pub fn default() -> DeviceModel {
DeviceModel::from_string(DEFAULT_DEVICE_MODEL)
.expect("Failure: default device model is invalid.")
}
pub fn get_key_descriptions(&self) -> &Vec<KeyDescription> {
&self.key_descriptions
}
pub fn get_device_width(&self) -> i32 {
self.device_width
}
pub fn get_device_height(&self) -> i32 {
self.device_height
}
}
impl Serializable<DeviceModel, nia_protocol_rust::DeviceModel> for DeviceModel {
fn to_pb(&self) -> nia_protocol_rust::DeviceModel {
let mut keyboard_model_pb = nia_protocol_rust::DeviceModel::new();
keyboard_model_pb.set_device_height(self.device_height);
keyboard_model_pb.set_device_width(self.device_width);
keyboard_model_pb.set_key_descriptions(
self.key_descriptions
.iter()
.map(|key_description| key_description.to_pb())
.collect(),
);
keyboard_model_pb
}
fn from_pb(
object_pb: nia_protocol_rust::DeviceModel,
) -> NiaServerResult<DeviceModel> {
let mut object_pb = object_pb;
let width = object_pb.get_device_width();
let height = object_pb.get_device_height();
let mut key_descriptions = Vec::new();
for key_description_pb in object_pb.take_key_descriptions().into_iter()
{
let key_description = KeyDescription::from_pb(key_description_pb)?;
key_descriptions.push(key_description);
}
let keyboard_model = DeviceModel::new(key_descriptions, width, height);
Ok(keyboard_model)
}
}
#[cfg(test)]
mod tests {
#[allow(unused_imports)]
use super::*;
#[test]
fn serializes_and_deserializes() {
let expected_keyboard_model = DeviceModel::new(
vec![
KeyDescription::new(1, 2, 3, 4, 5),
KeyDescription::new(3, 2, 4, 1, 2),
],
100,
200,
);
let bytes = expected_keyboard_model.to_bytes().unwrap();
let actual_keyboard_model = DeviceModel::from_bytes(bytes).unwrap();
assert_eq!(expected_keyboard_model, actual_keyboard_model)
}
}
|
use crate::println;
use bootloader::bootinfo::{MemoryMap, MemoryRegionType};
use x86_64::structures::paging::{
FrameAllocator, MappedPageTable, Mapper, MapperAllSizes, Page, PageTable, PageTableIndex, PhysFrame, UnusedPhysFrame, Size4KiB,
};
use x86_64::{PhysAddr, VirtAddr};
const X86_64_PAGE_TABLE_DEPTH: usize = 4;
type PageTableOffsets = [PageTableIndex; X86_64_PAGE_TABLE_DEPTH];
pub unsafe fn init(phys_mem_offset: VirtAddr) -> impl MapperAllSizes {
let l4_table = active_l4_table(phys_mem_offset);
let c = move |f: PhysFrame| -> *mut PageTable { _frame_to_page_table(phys_mem_offset, f) };
MappedPageTable::new(l4_table, c)
}
pub fn active_l4_table(phys_mem_offset: VirtAddr) -> &'static mut PageTable {
let (l4_table_phys, _) = x86_64::registers::control::Cr3::read();
unsafe { _frame_to_page_table(phys_mem_offset, l4_table_phys) }
}
pub fn dump_page_tables() -> () {
let (l4_table, _) = x86_64::registers::control::Cr3::read();
/* gives a phy addr, which we can't directly access */
println!("L4 page table at: {:?}", l4_table.start_address());
/* however, the bootloader maps the last page of the kernel's virtual address space to the
* frame of the L4 page table */
let l4_virt_ptr = 0xffff_ffff_ffff_f000 as *const PageTable;
let l4_tbl = unsafe { &*l4_virt_ptr };
for i in 0..10 {
println!("Entry {}: {:?}", i, l4_tbl[i]);
}
}
unsafe fn _frame_to_page_table(phys_mem_offset: VirtAddr, frame: PhysFrame) -> &'static mut PageTable {
let virt = phys_mem_offset + frame.start_address().as_u64();
let ptr = virt.as_mut_ptr();
&mut *ptr // unsafe
}
pub fn dump_page_tables_2(phys_mem_offset: VirtAddr, stop: usize) -> () {
if stop < 1 || stop > X86_64_PAGE_TABLE_DEPTH {
return;
}
let (l4_table_phys, _) = x86_64::registers::control::Cr3::read();
_dump_table(
phys_mem_offset,
l4_table_phys,
stop,
X86_64_PAGE_TABLE_DEPTH,
);
}
fn _dump_table(phys_mem_offset: VirtAddr, phys: PhysFrame, stop: usize, level: usize) -> () {
let table = unsafe { _frame_to_page_table(phys_mem_offset, phys) };
for (i, entry) in table.iter().enumerate() {
if !entry.is_unused() {
println!("L{} Entry {}: {:?}", level, i, entry);
if level > stop {
_dump_table(phys_mem_offset, entry.frame().unwrap(), stop, level - 1);
}
}
}
}
pub unsafe fn translate_addr_mt(physical_memory_offset: VirtAddr, addr: VirtAddr) -> Option<PhysAddr> {
_translate_addr(physical_memory_offset, addr)
}
fn _translate_addr(phys_mem_offset: VirtAddr, addr: VirtAddr) -> Option<PhysAddr> {
let (l4_table_phys, _) = x86_64::registers::control::Cr3::read();
let table_indices = [
addr.p1_index(),
addr.p2_index(),
addr.p3_index(),
addr.p4_index(),
];
let frame_base = _traverse_table(
phys_mem_offset,
l4_table_phys,
table_indices,
X86_64_PAGE_TABLE_DEPTH,
);
frame_base.map(|b| b + u64::from(addr.page_offset()))
}
fn _traverse_table(
phys_mem_offset: VirtAddr,
table_phys: PhysFrame,
table_indices: PageTableOffsets,
level: usize,
) -> Option<PhysAddr> {
use x86_64::structures::paging::page_table::FrameError;
let table = unsafe { _frame_to_page_table(phys_mem_offset, table_phys) };
let entry = &table[table_indices[level - 1]];
let frame = match entry.frame() {
Ok(f) => f,
Err(FrameError::FrameNotPresent) => return None,
Err(FrameError::HugeFrame) => panic!("Huge pages not supported"),
};
if level == 1 {
// base case
return Some(frame.start_address());
} else {
// recursive case
return _traverse_table(phys_mem_offset, frame, table_indices, level - 1);
}
}
pub unsafe fn translate_addr_ref(addr: VirtAddr, physical_memory_offset: VirtAddr) -> Option<PhysAddr> {
translate_addr_inner(addr, physical_memory_offset)
}
fn translate_addr_inner(addr: VirtAddr, physical_memory_offset: VirtAddr) -> Option<PhysAddr> {
use x86_64::registers::control::Cr3;
use x86_64::structures::paging::page_table::FrameError;
// read the active level 4 frame from the CR3 register
let (level_4_table_frame, _) = Cr3::read();
let table_indexes = [
addr.p4_index(),
addr.p3_index(),
addr.p2_index(),
addr.p1_index(),
];
let mut frame = level_4_table_frame;
// traverse the multi-level page table
for &index in &table_indexes {
// convert the frame into a page table reference
let virt = physical_memory_offset + frame.start_address().as_u64();
let table_ptr: *const PageTable = virt.as_ptr();
let table = unsafe { &*table_ptr };
// read the page table entry and update `frame`
let entry = &table[index];
frame = match entry.frame() {
Ok(frame) => frame,
Err(FrameError::FrameNotPresent) => return None,
Err(FrameError::HugeFrame) => panic!("huge pages not supported"),
};
}
// calculate the physical address by adding the page offset
Some(frame.start_address() + u64::from(addr.page_offset()))
}
pub fn create_mapping(
page: Page,
frame: PhysFrame,
mapper: &mut impl Mapper<Size4KiB>,
frame_allocator: &mut impl FrameAllocator<Size4KiB>,
) {
use x86_64::structures::paging::PageTableFlags as Flags;
let fs = Flags::PRESENT | Flags::WRITABLE;
let unused_frame = unsafe { UnusedPhysFrame::new(frame) };
let res = mapper.map_to(page, unused_frame, fs, frame_allocator);
res.expect("Failed to create new mapping").flush();
}
pub struct EmptyFrameAllocator;
unsafe impl FrameAllocator<Size4KiB> for EmptyFrameAllocator {
fn allocate_frame(&mut self) -> Option<UnusedPhysFrame> {
None
}
}
pub struct BootInfoFrameAllocator<I>
where
I: Iterator<Item = UnusedPhysFrame>,
{
frames: I,
}
impl<I> BootInfoFrameAllocator<I>
where
I: Iterator<Item = UnusedPhysFrame>,
{
pub fn new(
memory_map: &'static MemoryMap,
) -> BootInfoFrameAllocator<impl Iterator<Item = UnusedPhysFrame>> {
let frames = memory_map
.iter()
.filter(|r| r.region_type == MemoryRegionType::Usable)
.map(|r| r.range.start_addr()..r.range.end_addr())
.flat_map(|r| r.step_by(4096))
.map(|addr| PhysFrame::containing_address(PhysAddr::new(addr)))
.map(|f| unsafe { UnusedPhysFrame::new(f) });
BootInfoFrameAllocator { frames }
}
}
pub fn BootInfoFrameAllocator_new(
memory_map: &'static MemoryMap,
) -> BootInfoFrameAllocator<impl Iterator<Item = UnusedPhysFrame>> {
let frames = memory_map
.iter()
.filter(|r| r.region_type == MemoryRegionType::Usable)
.map(|r| r.range.start_addr()..r.range.end_addr())
.flat_map(|r| r.step_by(4096))
.map(|addr| PhysFrame::containing_address(PhysAddr::new(addr)))
.map(|f| unsafe { UnusedPhysFrame::new(f) });
BootInfoFrameAllocator { frames }
}
unsafe impl<I> FrameAllocator<Size4KiB> for BootInfoFrameAllocator<I>
where
I: Iterator<Item = UnusedPhysFrame>,
{
fn allocate_frame(&mut self) -> Option<UnusedPhysFrame> {
self.frames.next()
}
}
|
//! Attributes implementation.
use arctk::img::Gradient;
/// Surface attributes.
pub enum Attribute<'a> {
/// Opaque coloured surface.
Opaque(&'a Gradient),
/// Partially reflective mirror, absorption fraction.
Mirror(&'a Gradient, f64),
/// Partially transparent, absorption fraction.
Transparent(&'a Gradient, f64),
/// Refractive, absorption fraction, inside and outside refractive indices.
Refractive(&'a Gradient, f64, [f64; 2]),
/// Luminous surface, brightness multiplier.
Luminous(&'a Gradient, f64),
}
|
use rand;
use rand::rngs::ThreadRng;
use rtc::camera::{Camera, CameraConfig};
use rtc::ray::Ray;
use rtc::scenes::{
cornell_box, cornell_smoke, earth, last, random, simple_light, two_perlin_spheres, two_spheres,
};
use rtc::shape::Shape;
use rtc::vec3::{Color, Point3};
fn ray_color<T: Shape>(
ray: &Ray,
background: Option<Color>,
world: &T,
depth: u32,
rng: &mut ThreadRng,
) -> Color {
if depth <= 0 {
return Color::default();
}
if let Some(rec) = world.hit(ray, 0.001, f64::INFINITY, rng) {
let emitted = rec.material().emitted(rec.u(), rec.v(), rec.point());
if let Some((scattered, attenuation)) = rec.material().scatter(&ray, &rec, rng) {
return attenuation * ray_color(&scattered, background, world, depth - 1, rng);
}
return emitted;
}
if let Some(background) = background {
return background;
}
let unit = ray.direction().normalized();
let t = 0.5 * (unit.y() + 1.0);
Color::new(1.0, 1.0, 1.0) * (1.0 - t) + Color::new(0.5, 0.7, 1.0) * t
}
fn main() {
// Image
let mut aspect_ratio: f64 = 16.0 / 9.0;
let mut image_width: u32 = 400;
let mut samples_per_pixel: u32 = 100;
const MAX_DEPTH: u32 = 50;
// World
let mut rng = rand::thread_rng();
let world;
let from;
let mut at = Point3::new(0.0, 0.0, 0.0);
let vfov;
let mut background = None;
let mut aperture = 0.0;
let case = 0;
match case {
1 => {
world = random::build(&mut rng);
from = Point3::new(13.0, 2.0, 3.0);
vfov = 20.0;
aperture = 1.0;
}
2 => {
world = two_spheres::build();
from = Point3::new(13.0, 2.0, 3.0);
vfov = 20.0;
}
3 => {
world = two_perlin_spheres::build(&mut rng);
from = Point3::new(13.0, 2.0, 3.0);
vfov = 20.0;
}
4 => {
world = earth::build();
from = Point3::new(13.0, 2.0, 3.0);
vfov = 20.0;
}
5 => {
world = simple_light::build(&mut rng);
background = Some(Color::new(0.0, 0.0, 0.0));
samples_per_pixel = 400;
from = Point3::new(26.0, 3.0, 6.0);
at = Point3::new(0.0, 2.0, 0.0);
vfov = 20.0;
}
6 => {
world = cornell_box::build();
background = Some(Color::new(0.0, 0.0, 0.0));
aspect_ratio = 1.0;
image_width = 600;
samples_per_pixel = 200;
from = Point3::new(278.0, 278.0, -800.0);
at = Point3::new(278.0, 278.0, 0.0);
vfov = 40.0;
}
7 => {
world = cornell_smoke::build();
background = Some(Color::new(0.0, 0.0, 0.0));
aspect_ratio = 1.0;
image_width = 600;
samples_per_pixel = 200;
from = Point3::new(278.0, 278.0, -800.0);
at = Point3::new(278.0, 278.0, 0.0);
vfov = 40.0;
}
_ => {
world = last::build(&mut rng);
background = Some(Color::new(0.0, 0.0, 0.0));
aspect_ratio = 1.0;
image_width = 800;
samples_per_pixel = 200;
from = Point3::new(478.0, 278.0, -600.0);
at = Point3::new(278.0, 278.0, 0.0);
vfov = 40.0;
}
}
let image_height: u32 = (image_width as f64 / aspect_ratio) as u32;
// Camera
let camera = Camera::new(CameraConfig {
from,
at,
vfov,
aperture,
focus: 10.0,
aspect_ratio,
..CameraConfig::default()
});
// Render
println!("P3");
println!("{} {}", image_width, image_height);
println!("255");
for j in (0..image_height).rev() {
eprint!("\rScanlines remaining: {} ", j);
for i in 0..image_width {
let mut color = Color::new(0.0, 0.0, 0.0);
for _ in 0..samples_per_pixel {
let u = i as f64 / (image_width - 1) as f64;
let v = j as f64 / (image_height - 1) as f64;
let ray = camera.get_ray(u, v, &mut rng);
color += ray_color(&ray, background, &world, MAX_DEPTH, &mut rng);
}
println!("{}", Color::format_color(color, samples_per_pixel));
}
}
eprintln!("\nDone.\n");
}
|
//#![allow(bad_style)] // Stops rust from complaining about non-camelCased structs (ATAG makes camelCase awkward)
// Note: the bootloader sets up the atags. Won't work within QEMU
use core::intrinsics::volatile_load;
//use uart; //for debug
// ATAG IDs
const NONE_ID: u32 = 0x00000000;
const CORE_ID: u32 = 0x54410001;
const MEM_ID: u32 = 0x54410002;
const VIDEOTEXT_ID: u32 = 0x54410003;
const RAMDISK_ID: u32 = 0x54410004;
const INITRD2_ID: u32 = 0x54410005;
const SERIAL_ID: u32 = 0x54410006;
const REVISION_ID: u32 = 0x54410007;
const VIDEOLFB_ID: u32 = 0x54410008;
const CMDLINE_ID: u32 = 0x54410009;
struct AtagHeader {
size: u32, // length of tag in words, including header
id: u32,
}
pub struct AtagCore {
pub flags: u32,
pub page_size: u32,
pub root_dev: u32,
}
pub struct AtagMem {
pub size: u32,
pub start: u32,
}
pub struct AtagVideotext {
pub x: u8,
pub y: u8,
pub video_page: u16,
pub video_mode: u8,
pub video_cols: u8,
pub video_ega_bx: u16,
pub video_lines: u8,
pub video_isvga: u8,
pub video_points: u16,
}
pub struct AtagRamdisk {
pub flags: u32,
pub size: u32,
pub start: u32,
}
pub struct AtagInitrd2 {
pub start: u32,
pub size: u32,
}
pub struct AtagSerial {
pub low: u32,
pub high: u32,
}
pub struct AtagRevision {
pub rev: u32,
}
pub struct AtagVideolfb {
pub lfb_width: u16,
pub lfb_height: u16,
pub lfb_depth: u16,
pub lfb_linelength: u16,
pub lfb_base: u32,
pub lfb_size: u32,
pub red_size: u8,
pub red_pos: u8,
pub green_size: u8,
pub green_pos: u8,
pub blue_size: u8,
pub blue_pos: u8,
pub rsvd_size: u8,
pub rsvd_pos: u8,
}
pub struct AtagCmdline {
pub cmdline: [u8; 1], //minimum size: array of u8, size 1
}
pub struct Atags {
pub core: Option<AtagCore>,
pub mem: Option<AtagMem>,
pub videotext: Option<AtagVideotext>,
pub ramdisk: Option<AtagRamdisk>,
pub initrd2: Option<AtagInitrd2>,
pub serial: Option<AtagSerial>,
pub revision: Option<AtagRevision>,
pub videolfb: Option<AtagVideolfb>,
pub cmdline: Option<AtagCmdline>,
}
impl Atags {
fn new() -> Atags {
Atags {
core: None,
mem: None,
videotext: None,
ramdisk: None,
initrd2: None,
serial: None,
revision: None,
videolfb: None,
cmdline: None,
}
}
}
// Assumes no more than one of each type of atag
// addr represents starting address of atags
pub fn parse_atags (mut addr: u32) -> Atags {
let mut atags = Atags::new();
loop {
let atag = unsafe { volatile_load(addr as *const AtagHeader) };
if atag.id == CORE_ID {
atags.core = unsafe { Some(volatile_load((addr+2) as *const AtagCore)) }; //2 = sizeof the header
} else if atag.id == MEM_ID {
atags.mem = unsafe { Some(volatile_load((addr+2) as *const AtagMem)) };
} else if atag.id == VIDEOTEXT_ID {
atags.videotext = unsafe { Some(volatile_load((addr+2) as *const AtagVideotext)) };
} else if atag.id == RAMDISK_ID {
atags.ramdisk = unsafe { Some(volatile_load((addr+2) as *const AtagRamdisk)) };
} else if atag.id == INITRD2_ID {
atags.initrd2 = unsafe { Some(volatile_load((addr+2) as *const AtagInitrd2)) };
} else if atag.id == SERIAL_ID {
atags.serial = unsafe { Some(volatile_load((addr+2) as *const AtagSerial)) };
} else if atag.id == REVISION_ID {
atags.revision = unsafe { Some(volatile_load((addr+2) as *const AtagRevision)) };
} else if atag.id == VIDEOLFB_ID {
atags.videolfb = unsafe { Some(volatile_load((addr+2) as *const AtagVideolfb)) };
} else if atag.id == CMDLINE_ID {
atags.cmdline = unsafe { Some(volatile_load((addr+2) as *const AtagCmdline)) };
} else if atag.id == NONE_ID {
break;
}
addr += atag.size;
}
atags
}
// Deprecated: use parse_atags
pub fn get_mem_tag (mut addr: u32) -> Option<AtagMem> {
loop {
let atag = unsafe { volatile_load(addr as *const AtagHeader) };
if atag.id == MEM_ID {
return unsafe { Some(volatile_load((addr+2) as *const AtagMem)) }; //2 = sizeof the header
}
else if atag.id == NONE_ID {
return None;
}
addr += atag.size;
}
}
|
use std::collections::HashMap;
pub fn solve3a(input: Vec<&str>) -> (u32, Vec<bool>) {
let mut overlapped_ids: Vec<bool> = vec![false; input.len()];
let mut count: u32 = 0;
let mut fabric_area: HashMap<(u32, u32), u32> = HashMap::new();
let mut fabric_counted: HashMap<(u32, u32), bool> = HashMap::new();
for i in 0..input.len() {
let v: Vec<&str> = input[i].split(" ").collect();
let p: Vec<&str> = v[2]
.split(":")
.nth(0)
.expect("invalid idx")
.split(",")
.collect();
let rect_point: (u32, u32) = (p[0].parse::<u32>().unwrap(), p[1].parse::<u32>().unwrap());
let s: Vec<&str> = v[3].split("x").collect();
let rect_size: (u32, u32) = (s[0].parse::<u32>().unwrap(), s[1].parse::<u32>().unwrap());
for x in (rect_point.0)..(rect_size.0 + rect_point.0) {
for y in (rect_point.1)..(rect_size.1 + rect_point.1) {
let pixel: (u32, u32) = (x, y);
if !fabric_counted.contains_key(&pixel) {
if fabric_area.contains_key(&pixel) {
count += 1;
fabric_counted.insert(pixel, true);
overlapped_ids[i] = true;
*overlapped_ids
.get_mut(*fabric_area.get(&pixel).expect("unable to get index") as usize)
.unwrap() = true;
} else {
fabric_area.insert(pixel, i as u32);
}
} else {
overlapped_ids[i] = true;
*overlapped_ids
.get_mut(*fabric_area.get(&pixel).expect("unable to get index") as usize)
.unwrap() = true;
}
}
}
}
return (count, overlapped_ids);
}
pub fn solve3b(overlapped_ids: Vec<bool>) -> Option<usize> {
for i in 0..overlapped_ids.len() {
if !overlapped_ids[i] {
return Some(i + 1);
}
}
None
}
|
use std::iter::FromIterator;
use iron;
use r2d2;
use r2d2_redis::RedisConnectionManager;
use rand;
use rand::Rng;
use redis;
use redis::Commands;
use get_default_cookie;
use RawSession;
use SessionBackend;
use cookie;
use errors::*;
use iron::prelude::*;
const COOKIE_NAME: &'static str = "iron_session_id";
type RedisPool = r2d2::Pool<RedisConnectionManager>;
pub struct RedisSession {
session_id: String,
pool: RedisPool,
}
impl RawSession for RedisSession {
fn get_raw(&self, key: &str) -> IronResult<Option<String>> {
let conn = itry!(self.pool.get());
Ok(itry!(conn.hget(&self.session_id, key)))
}
fn set_raw(&mut self, key: &str, value: String) -> IronResult<()> {
let conn = itry!(self.pool.get());
itry!(conn.hset::<&str, &str, String, ()>(&self.session_id, key, value));
Ok(())
}
fn clear(&mut self) -> IronResult<()> {
let conn = itry!(self.pool.get());
itry!(conn.del::<&str, ()>(&self.session_id));
self.session_id = "".to_owned();
Ok(())
}
fn write(&self, res: &mut Response) -> IronResult<()> {
let cookie = get_default_cookie(COOKIE_NAME.to_owned(), self.session_id.clone());
if let Some(cookies) = res.headers.get_mut::<iron::headers::SetCookie>() {
debug_assert!(cookies.iter().all(|cookie| cookie != COOKIE_NAME));
cookies.push(format!("{}", cookie.pair()));
return Ok(());
}
res.headers
.set(iron::headers::SetCookie(vec![format!("{}", cookie.pair())]));
Ok(())
}
}
pub struct RedisBackend {
pool: RedisPool,
}
impl RedisBackend {
pub fn new<T: redis::IntoConnectionInfo>(params: T) -> Result<Self> {
let manager = try!(
RedisConnectionManager::new(params)
.chain_err(|| "Couldn't create redis connection manager")
);
let pool = try!(
r2d2::Pool::builder()
.build(manager)
.chain_err(|| "Couldn't create redis connection pool")
);
Ok(RedisBackend { pool: pool })
}
}
impl SessionBackend for RedisBackend {
type S = RedisSession;
fn from_request(&self, req: &mut Request) -> Self::S {
let session_id = req.headers
.get::<iron::headers::Cookie>()
.map(|cookies| {
// FIXME: Our cookies are unsigned. Why do I need to specify a key?
let mut jar = cookie::CookieJar::new(b"");
for cookie in cookies.iter() {
if let Ok(cookie) = cookie::Cookie::parse(&cookie) {
jar.add_original(cookie);
}
}
jar
})
.and_then(|jar| jar.find(COOKIE_NAME))
.map(|cookie| cookie.value)
.unwrap_or_else(|| {
let mut rng = rand::OsRng::new().unwrap();
String::from_iter(rng.gen_ascii_chars().take(40))
});
RedisSession {
session_id: session_id,
pool: self.pool.clone(),
}
}
}
|
use crate::assembler::Mem;
use crate::assembler::{Assembler, Label};
use crate::assembler_x64 as buf;
use crate::constants_x64::*;
use crate::dseg::f32x4;
use crate::CondCode;
use crate::MachineMode;
#[no_mangle]
pub extern "C" fn fits_i32(n: i64) -> bool { n == (n as i32) as i64 }
#[no_mangle]
pub extern "C" fn new_f32x4(v1: f32, v2: f32, v3: f32, v4: f32) -> f32x4 {
//println!("{} {} {} {}", v1, v2, v3, v4);
return f32x4(v1, v2, v3, v4);
}
impl Assembler {
pub extern "C" fn load_int_const(&mut self, mode: MachineMode, dest: Register, imm: i64) {
match mode {
MachineMode::Int8 | MachineMode::Int32 => {
buf::emit_movl_imm_reg(self, imm as i32, dest)
}
MachineMode::Int64 | MachineMode::Ptr => {
buf::emit_movq_imm64_reg(self, imm, dest);
}
MachineMode::Float32 | MachineMode::Float64 => unreachable!(),
}
}
pub extern "C" fn load_float4_const(&mut self, dest: XMMRegister, val: f32x4) {
let pos = self.pos() as i32;
let off = self.dseg.add_f32x4(val);
movups_load(self, dest, Mem::Base(RIP, -(off + pos + 8)));
}
pub extern "C" fn load_float_const(&mut self, mode: MachineMode, dest: XMMRegister, imm: f64) {
let pos = self.pos() as i32;
match mode {
MachineMode::Float32 => {
let off = self.dseg.add_float(imm as f32);
buf::movss_load(self, dest, Mem::Base(RIP, -(off + pos + 8)));
}
MachineMode::Float64 => {
let off = self.dseg.add_double(imm);
buf::movsd_load(self, dest, Mem::Base(RIP, -(off + pos + 8)));
}
_ => unreachable!(),
}
}
pub extern "C" fn load_true(&mut self, dest: Register) {
buf::emit_movl_imm_reg(self, 1, dest);
}
pub extern "C" fn load_false(&mut self, dest: Register) {
buf::emit_movl_imm_reg(self, 0, dest);
}
pub extern "C" fn int_neg(&mut self, mode: MachineMode, dest: Register, src: Register) {
let x64 = match mode {
MachineMode::Int32 => 0,
MachineMode::Int64 => 1,
_ => unimplemented!(),
};
buf::emit_neg_reg(self, x64, src);
if dest != src {
buf::emit_mov_reg_reg(self, x64, src, dest);
}
}
pub extern "C" fn int_not(&mut self, mode: MachineMode, dest: Register, src: Register) {
let x64 = match mode {
MachineMode::Int8 => {
buf::emit_not_reg_byte(self, src);
0
}
MachineMode::Int32 => {
buf::emit_not_reg(self, 0, src);
0
}
MachineMode::Int64 => {
buf::emit_not_reg(self, 1, src);
1
}
_ => unimplemented!(),
};
if dest != src {
buf::emit_mov_reg_reg(self, x64, src, dest);
}
}
pub extern "C" fn bool_not(&mut self, dest: Register, src: Register) {
buf::emit_xorb_imm_reg(self, 1, src);
buf::emit_andb_imm_reg(self, 1, src);
if dest != src {
buf::emit_mov_reg_reg(self, 0, src, dest);
}
}
pub extern "C" fn float_add(&mut self,
mode: MachineMode,
dest: XMMRegister,
lhs: XMMRegister,
rhs: XMMRegister) {
match mode {
MachineMode::Float32 => buf::addss(self, lhs, rhs),
MachineMode::Float64 => buf::addsd(self, lhs, rhs),
_ => unimplemented!(),
}
if dest != lhs {
self.copy_freg(mode, dest, lhs);
}
}
pub extern "C" fn float_sub(&mut self,
mode: MachineMode,
dest: XMMRegister,
lhs: XMMRegister,
rhs: XMMRegister) {
match mode {
MachineMode::Float32 => buf::subss(self, lhs, rhs),
MachineMode::Float64 => buf::subsd(self, lhs, rhs),
_ => unimplemented!(),
}
if dest != lhs {
self.copy_freg(mode, dest, lhs);
}
}
pub extern "C" fn float_mul(&mut self,
mode: MachineMode,
dest: XMMRegister,
lhs: XMMRegister,
rhs: XMMRegister) {
match mode {
MachineMode::Float32 => buf::mulss(self, lhs, rhs),
MachineMode::Float64 => buf::mulsd(self, lhs, rhs),
_ => unimplemented!(),
}
if dest != lhs {
self.copy_freg(mode, dest, lhs);
}
}
pub extern "C" fn float_div(&mut self,
mode: MachineMode,
dest: XMMRegister,
lhs: XMMRegister,
rhs: XMMRegister) {
match mode {
MachineMode::Float32 => buf::divss(self, lhs, rhs),
MachineMode::Float64 => buf::divsd(self, lhs, rhs),
_ => unimplemented!(),
}
if dest != lhs {
self.copy_freg(mode, dest, lhs);
}
}
pub extern "C" fn float_neg(&mut self, mode: MachineMode, dest: XMMRegister, src: XMMRegister) {
let (fst, snd) = if mode == MachineMode::Float32 {
(1i32 << 31, 0)
} else {
(0, 1i32 << 31)
};
// align MMX data to 16 bytes
self.dseg.align(16);
self.dseg.add_int(0);
self.dseg.add_int(0);
self.dseg.add_int(snd);
let disp = self.dseg.add_int(fst);
let pos = self.pos() as i32;
let mem = Mem::Base(RIP, 0);
match mode {
MachineMode::Float32 => buf::xorps(self, src, mem),
MachineMode::Float64 => buf::xorpd(self, src, mem),
_ => unimplemented!(),
}
let after = self.pos() as i32;
let len = after - pos;
let offset = -(disp + pos + len);
self.emit_u32_at(after - 4, offset as u32);
if dest != src {
self.copy_freg(mode, dest, src);
}
}
pub extern "C" fn load_mem(&mut self, mode: MachineMode, dest: Reg, mem: Mem) {
match mem {
Mem::Local(offset) => match mode {
MachineMode::Int8 => buf::emit_movzbl_memq_reg(self, RBP, offset, dest.reg()),
MachineMode::Int32 => buf::emit_movl_memq_reg(self, RBP, offset, dest.reg()),
MachineMode::Int64 | MachineMode::Ptr => {
buf::emit_movq_memq_reg(self, RBP, offset, dest.reg())
}
MachineMode::Float32 => buf::movss_load(self, dest.freg(), mem),
MachineMode::Float64 => buf::movsd_load(self, dest.freg(), mem),
},
Mem::Base(base, disp) => match mode {
MachineMode::Int8 => buf::emit_movzbl_memq_reg(self, base, disp, dest.reg()),
MachineMode::Int32 => buf::emit_movl_memq_reg(self, base, disp, dest.reg()),
MachineMode::Int64 | MachineMode::Ptr => {
buf::emit_movq_memq_reg(self, base, disp, dest.reg())
}
MachineMode::Float32 => buf::movss_load(self, dest.freg(), mem),
MachineMode::Float64 => buf::movsd_load(self, dest.freg(), mem),
},
Mem::Index(base, index, scale, disp) => match mode {
MachineMode::Int8 => {
assert!(scale == 1);
buf::emit_movzx_memindex_byte_reg(self, 0, base, index, disp, dest.reg())
}
MachineMode::Int32 | MachineMode::Int64 | MachineMode::Ptr => {
buf::emit_mov_memindex_reg(self, mode, base, index, scale, disp, dest.reg())
}
MachineMode::Float32 => buf::movss_load(self, dest.freg(), mem),
MachineMode::Float64 => buf::movsd_load(self, dest.freg(), mem),
},
Mem::Offset(_, _, _) => unimplemented!(),
}
}
pub extern "C" fn float_sqrt(&mut self,
mode: MachineMode,
dest: XMMRegister,
src: XMMRegister) {
match mode {
MachineMode::Float32 => buf::sqrtss(self, dest, src),
MachineMode::Float64 => buf::sqrtsd(self, dest, src),
_ => unreachable!(),
}
}
pub extern "C" fn copy_reg(&mut self, mode: MachineMode, dest: Register, src: Register) {
let x64 = match mode {
MachineMode::Int8 | MachineMode::Int32 => 0,
MachineMode::Int64 | MachineMode::Ptr => 1,
MachineMode::Float32 | MachineMode::Float64 => unreachable!(),
};
buf::emit_mov_reg_reg(self, x64, src, dest);
}
pub extern "C" fn copy_pc(&mut self, dest: Register) {
buf::lea(self, dest, Mem::Base(RIP, 0));
}
pub extern "C" fn copy_ra(&mut self, dest: Register) {
self.load_mem(MachineMode::Ptr, Reg::Gpr(dest), Mem::Base(RSP, 0));
}
fn emit_barrier(&mut self, src: Register, card_table_offset: usize) {
buf::emit_shr_reg_imm(self, 1, src, 9);
// test if card table offset fits into displacement of memory store
if card_table_offset <= 0x7FFF_FFFF {
// emit mov [card_table_offset + base], 0
buf::emit_movb_imm_memq(self, 0, src, card_table_offset as i32);
} else {
let scratch = R11;
self.load_int_const(MachineMode::Ptr, scratch, card_table_offset as i64);
buf::emit_movb_imm_memscaleq(self, 0, src, scratch, 0);
}
}
pub extern "C" fn store_mem(&mut self, mode: MachineMode, mem: Mem, src: Reg) {
match mem {
Mem::Local(offset) => match mode {
MachineMode::Int8 => buf::emit_movb_reg_memq(self, src.reg(), RBP, offset),
MachineMode::Int32 => buf::emit_movl_reg_memq(self, src.reg(), RBP, offset),
MachineMode::Int64 | MachineMode::Ptr => {
buf::emit_movq_reg_memq(self, src.reg(), RBP, offset)
}
MachineMode::Float32 => buf::movss_store(self, mem, src.freg()),
MachineMode::Float64 => buf::movsd_store(self, mem, src.freg()),
},
Mem::Base(base, disp) => match mode {
MachineMode::Int8 => buf::emit_movb_reg_memq(self, src.reg(), base, disp),
MachineMode::Int32 => buf::emit_movl_reg_memq(self, src.reg(), base, disp),
MachineMode::Int64 | MachineMode::Ptr => {
buf::emit_movq_reg_memq(self, src.reg(), base, disp)
}
MachineMode::Float32 => buf::movss_store(self, mem, src.freg()),
MachineMode::Float64 => buf::movsd_store(self, mem, src.freg()),
},
Mem::Index(base, index, scale, disp) => match mode {
MachineMode::Int8 | MachineMode::Int32 | MachineMode::Int64 | MachineMode::Ptr => {
buf::emit_mov_reg_memindex(self, mode, src.reg(), base, index, scale, disp)
}
MachineMode::Float32 => buf::movss_store(self, mem, src.freg()),
MachineMode::Float64 => buf::movsd_store(self, mem, src.freg()),
},
Mem::Offset(_, _, _) => unimplemented!(),
}
}
pub extern "C" fn copy_sp(&mut self, dest: Register) {
self.copy_reg(MachineMode::Ptr, dest, RSP);
}
pub extern "C" fn set_sp(&mut self, src: Register) {
self.copy_reg(MachineMode::Ptr, RSP, src);
}
pub extern "C" fn copy_freg(&mut self, mode: MachineMode, dest: XMMRegister, src: XMMRegister) {
match mode {
MachineMode::Float32 => buf::movss(self, dest, src),
MachineMode::Float64 => buf::movsd(self, dest, src),
_ => unreachable!(),
}
}
pub extern "C" fn extend_int_long(&mut self, dest: Register, src: Register) {
buf::emit_movsx(self, src, dest);
}
pub extern "C" fn extend_byte(&mut self, mode: MachineMode, dest: Register, src: Register) {
let x64 = match mode {
MachineMode::Int32 => 0,
MachineMode::Int64 => 1,
_ => unimplemented!(),
};
buf::emit_movzx_byte(self, x64, src, dest);
}
pub extern "C" fn set(&mut self, dest: Register, op: CondCode) {
buf::emit_setb_reg(self, op, dest);
buf::emit_movzbl_reg_reg(self, dest, dest);
}
pub extern "C" fn cmp_mem(&mut self, mode: MachineMode, mem: Mem, rhs: Register) {
match mem {
Mem::Local(offset) => buf::emit_cmp_mem_reg(self, mode, RBP, offset, rhs),
Mem::Base(base, disp) => buf::emit_cmp_mem_reg(self, mode, base, disp, rhs),
Mem::Index(base, index, scale, disp) => {
buf::emit_cmp_memindex_reg(self, mode, base, index, scale, disp, rhs)
}
Mem::Offset(_, _, _) => unimplemented!(),
}
}
pub extern "C" fn cmp_mem_imm(&mut self, mode: MachineMode, mem: Mem, imm: i32) {
match mem {
Mem::Local(_) => unimplemented!(),
Mem::Base(base, disp) => buf::emit_cmp_mem_imm(self, mode, base, disp, imm),
Mem::Index(_, _, _, _) => unimplemented!(),
Mem::Offset(_, _, _) => unimplemented!(),
}
}
pub extern "C" fn cmp_reg(&mut self, mode: MachineMode, lhs: Register, rhs: Register) {
let x64 = match mode {
MachineMode::Int8 | MachineMode::Int32 => 0,
MachineMode::Int64 | MachineMode::Ptr => 1,
MachineMode::Float32 | MachineMode::Float64 => unreachable!(),
};
buf::emit_cmp_reg_reg(self, x64, rhs, lhs);
}
pub extern "C" fn cmp_reg_imm(&mut self, mode: MachineMode, lhs: Register, imm: i32) {
buf::emit_cmp_imm_reg(self, mode, imm, lhs);
}
pub extern "C" fn float_cmp(&mut self,
mode: MachineMode,
dest: Register,
lhs: XMMRegister,
rhs: XMMRegister,
cond: CondCode) {
let scratch = &R11;
match cond {
CondCode::Equal | CondCode::NotEqual => {
let init = if cond == CondCode::Equal { 0 } else { 1 };
self.load_int_const(MachineMode::Int32, *scratch, init);
self.load_int_const(MachineMode::Int32, dest, 0);
match mode {
MachineMode::Float32 => buf::ucomiss(self, lhs, rhs),
MachineMode::Float64 => buf::ucomisd(self, lhs, rhs),
_ => unreachable!(),
}
let parity = if cond == CondCode::Equal { false } else { true };
buf::emit_setb_reg_parity(self, dest, parity);
buf::cmov(self, 0, dest, *scratch, CondCode::NotEqual);
}
CondCode::Greater | CondCode::GreaterEq => {
self.load_int_const(MachineMode::Int32, dest, 0);
match mode {
MachineMode::Float32 => buf::ucomiss(self, lhs, rhs),
MachineMode::Float64 => buf::ucomisd(self, lhs, rhs),
_ => unreachable!(),
}
let cond = match cond {
CondCode::Greater => CondCode::UnsignedGreater,
CondCode::GreaterEq => CondCode::UnsignedGreaterEq,
_ => unreachable!(),
};
buf::emit_setb_reg(self, cond, dest);
}
CondCode::Less | CondCode::LessEq => {
self.load_int_const(MachineMode::Int32, dest, 0);
match mode {
MachineMode::Float32 => buf::ucomiss(self, rhs, lhs),
MachineMode::Float64 => buf::ucomisd(self, rhs, lhs),
_ => unreachable!(),
}
let cond = match cond {
CondCode::Less => CondCode::UnsignedGreater,
CondCode::LessEq => CondCode::UnsignedGreaterEq,
_ => unreachable!(),
};
buf::emit_setb_reg(self, cond, dest);
}
_ => unreachable!(),
}
}
pub extern "C" fn float_cmp_nan(&mut self,
mode: MachineMode,
dest: Register,
src: XMMRegister) {
self.load_int_const(MachineMode::Int32, dest, 0);
match mode {
MachineMode::Float32 => buf::ucomiss(self, src, src),
MachineMode::Float64 => buf::ucomisd(self, src, src),
_ => unreachable!(),
}
buf::emit_setb_reg_parity(self, dest, true);
}
pub extern "C" fn cmp_zero(&mut self, mode: MachineMode, lhs: Register) {
buf::emit_cmp_imm_reg(self, mode, 0, lhs);
}
pub extern "C" fn test_and_jump_if(&mut self, cond: CondCode, reg: Register, lbl: Label) {
assert!(cond == CondCode::Zero || cond == CondCode::NonZero);
buf::emit_testl_reg_reg(self, reg, reg);
self.jump_if(cond, lbl);
}
pub extern "C" fn jump_if(&mut self, cond: CondCode, lbl: Label) {
buf::emit_jcc(self, cond, lbl);
}
pub extern "C" fn jump(&mut self, lbl: Label) { buf::emit_jmp(self, lbl); }
pub extern "C" fn jump_reg(&mut self, reg: Register) { buf::emit_jmp_reg(self, reg); }
pub extern "C" fn int_div(&mut self,
mode: MachineMode,
dest: Register,
lhs: Register,
rhs: Register) {
self.div_common(mode, dest, lhs, rhs, RAX);
}
pub extern "C" fn int_mod(&mut self,
mode: MachineMode,
dest: Register,
lhs: Register,
rhs: Register) {
self.div_common(mode, dest, lhs, rhs, RDX);
}
fn div_common(&mut self,
mode: MachineMode,
dest: Register,
lhs: Register,
rhs: Register,
result: Register) {
let x64 = match mode {
MachineMode::Int32 => 0,
MachineMode::Int64 => 1,
_ => unimplemented!(),
};
if lhs != RAX {
assert!(rhs != RAX);
buf::emit_mov_reg_reg(self, x64, lhs, RAX);
}
if x64 != 0 {
buf::emit_cqo(self);
} else {
buf::emit_cdq(self);
}
buf::emit_idiv_reg_reg(self, x64, rhs);
if dest != result {
buf::emit_mov_reg_reg(self, x64, result, dest);
}
}
pub extern "C" fn int_mul(&mut self,
mode: MachineMode,
dest: Register,
lhs: Register,
rhs: Register) {
let x64 = match mode {
MachineMode::Int32 => 0,
MachineMode::Int64 => 1,
_ => unimplemented!(),
};
buf::emit_imul_reg_reg(self, x64, rhs, lhs);
if dest != lhs {
buf::emit_mov_reg_reg(self, x64, lhs, dest);
}
}
pub extern "C" fn int_add(&mut self,
mode: MachineMode,
dest: Register,
lhs: Register,
rhs: Register) {
let x64 = match mode {
MachineMode::Int32 => 0,
MachineMode::Int64 | MachineMode::Ptr => 1,
_ => unimplemented!(),
};
buf::emit_add_reg_reg(self, x64, rhs, lhs);
if dest != lhs {
buf::emit_mov_reg_reg(self, x64, lhs, dest);
}
}
pub extern "C" fn int_add_imm(&mut self,
mode: MachineMode,
dest: Register,
lhs: Register,
value: i64) {
if !fits_i32(value) {
assert!(mode == MachineMode::Int64 || mode == MachineMode::Ptr);
let reg_size = R11;
self.load_int_const(MachineMode::Ptr, reg_size, value);
self.int_add(mode, dest, lhs, reg_size);
return;
}
let x64 = match mode {
MachineMode::Int64 | MachineMode::Ptr => 1,
_ => unimplemented!(),
};
buf::emit_addq_imm_reg(self, value as i32, lhs);
if dest != lhs {
buf::emit_mov_reg_reg(self, x64, lhs, dest);
}
}
pub extern "C" fn int_sub(&mut self,
mode: MachineMode,
dest: Register,
lhs: Register,
rhs: Register) {
let x64 = match mode {
MachineMode::Int32 => 0,
MachineMode::Int64 => 1,
_ => unimplemented!(),
};
buf::emit_sub_reg_reg(self, x64, rhs, lhs);
if dest != lhs {
buf::emit_mov_reg_reg(self, x64, lhs, dest);
}
}
pub extern "C" fn int_shl(&mut self,
mode: MachineMode,
dest: Register,
lhs: Register,
rhs: Register) {
let x64 = match mode {
MachineMode::Int32 => 0,
MachineMode::Int64 => 1,
_ => unimplemented!(),
};
if rhs != RCX {
assert!(lhs != RCX);
buf::emit_mov_reg_reg(self, x64, rhs, RCX);
}
buf::emit_shl_reg_cl(self, x64, lhs);
if dest != lhs {
buf::emit_mov_reg_reg(self, x64, lhs, dest);
}
}
pub extern "C" fn int_shr(&mut self,
mode: MachineMode,
dest: Register,
lhs: Register,
rhs: Register) {
let x64 = match mode {
MachineMode::Int32 => 0,
MachineMode::Int64 => 1,
_ => unimplemented!(),
};
if rhs != RCX {
assert!(lhs != RCX);
buf::emit_mov_reg_reg(self, x64, rhs, RCX);
}
buf::emit_shr_reg_cl(self, x64, lhs);
if dest != lhs {
buf::emit_mov_reg_reg(self, x64, lhs, dest);
}
}
pub extern "C" fn int_sar(&mut self,
mode: MachineMode,
dest: Register,
lhs: Register,
rhs: Register) {
let x64 = match mode {
MachineMode::Int32 => 0,
MachineMode::Int64 => 1,
_ => unimplemented!(),
};
if rhs != RCX {
assert!(lhs != RCX);
buf::emit_mov_reg_reg(self, x64, rhs, RCX);
}
buf::emit_sar_reg_cl(self, x64, lhs);
if dest != lhs {
buf::emit_mov_reg_reg(self, x64, lhs, dest);
}
}
pub extern "C" fn int_or(&mut self,
mode: MachineMode,
dest: Register,
lhs: Register,
rhs: Register) {
let x64 = match mode {
MachineMode::Int32 => 0,
MachineMode::Int64 => 1,
_ => unimplemented!(),
};
buf::emit_or_reg_reg(self, x64, rhs, lhs);
if dest != lhs {
buf::emit_mov_reg_reg(self, x64, lhs, dest);
}
}
pub extern "C" fn int_and(&mut self,
mode: MachineMode,
dest: Register,
lhs: Register,
rhs: Register) {
let x64 = match mode {
MachineMode::Int32 => 0,
MachineMode::Int64 => 1,
_ => unimplemented!(),
};
buf::emit_and_reg_reg(self, x64, rhs, lhs);
if dest != lhs {
buf::emit_mov_reg_reg(self, x64, lhs, dest);
}
}
pub extern "C" fn int_xor(&mut self,
mode: MachineMode,
dest: Register,
lhs: Register,
rhs: Register) {
let x64 = match mode {
MachineMode::Int32 => 0,
MachineMode::Int64 => 1,
_ => unimplemented!(),
};
buf::emit_xor_reg_reg(self, x64, rhs, lhs);
if dest != lhs {
buf::emit_mov_reg_reg(self, x64, lhs, dest);
}
}
pub extern "C" fn int_to_float(&mut self,
dest_mode: MachineMode,
dest: XMMRegister,
src_mode: MachineMode,
src: Register) {
buf::pxor(self, dest, dest);
let x64 = match src_mode {
MachineMode::Int32 => 0,
MachineMode::Int64 => 1,
_ => unreachable!(),
};
match dest_mode {
MachineMode::Float32 => buf::cvtsi2ss(self, dest, x64, src),
MachineMode::Float64 => buf::cvtsi2sd(self, dest, x64, src),
_ => unreachable!(),
}
}
pub extern "C" fn float_to_int(&mut self,
dest_mode: MachineMode,
dest: Register,
src_mode: MachineMode,
src: XMMRegister) {
let x64 = match dest_mode {
MachineMode::Int32 => 0,
MachineMode::Int64 => 1,
_ => unreachable!(),
};
match src_mode {
MachineMode::Float32 => buf::cvttss2si(self, x64, dest, src),
MachineMode::Float64 => buf::cvttsd2si(self, x64, dest, src),
_ => unreachable!(),
}
}
pub extern "C" fn float_to_double(&mut self, dest: XMMRegister, src: XMMRegister) {
buf::cvtss2sd(self, dest, src);
}
pub extern "C" fn double_to_float(&mut self, dest: XMMRegister, src: XMMRegister) {
buf::cvtsd2ss(self, dest, src);
}
}
#[no_mangle]
pub extern "C" fn emit_or_reg_reg(buf: &mut Assembler, x64: u8, src: Register, dest: Register) {
emit_alu_reg_reg(buf, x64, 0x09, src, dest);
}
#[no_mangle]
pub extern "C" fn emit_and_reg_reg(buf: &mut Assembler, x64: u8, src: Register, dest: Register) {
emit_alu_reg_reg(buf, x64, 0x21, src, dest);
}
#[no_mangle]
pub extern "C" fn emit_xor_reg_reg(buf: &mut Assembler, x64: u8, src: Register, dest: Register) {
emit_alu_reg_reg(buf, x64, 0x31, src, dest);
}
#[no_mangle]
fn emit_alu_reg_reg(buf: &mut Assembler, x64: u8, opcode: u8, src: Register, dest: Register) {
if x64 != 0 || src.msb() != 0 || dest.msb() != 0 {
emit_rex(buf, x64, src.msb(), 0, dest.msb());
}
emit_op(buf, opcode);
emit_modrm(buf, 0b11, src.and7(), dest.and7());
}
#[no_mangle]
pub extern "C" fn emit_movl_imm_reg(buf: &mut Assembler, imm: i32, reg: Register) {
if reg.msb() != 0 {
emit_rex(buf, 0, 0, 0, 1);
}
emit_op(buf, (0xB8 as u8) + reg.and7());
emit32(buf, imm as u32);
}
#[no_mangle]
// mov 32bit immediate and sign-extend into 64bit-register
pub extern "C" fn emit_movq_imm_reg(buf: &mut Assembler, imm: i32, reg: Register) {
emit_rex(buf, 1, 0, 0, reg.msb());
emit_op(buf, 0xc7);
emit_modrm(buf, 0b11, 0, reg.and7());
emit32(buf, imm as u32);
}
#[no_mangle]
pub extern "C" fn emit_movq_imm64_reg(buf: &mut Assembler, imm: i64, reg: Register) {
emit_rex(buf, 1, 0, 0, reg.msb());
emit_op(buf, 0xb8 + reg.and7());
emit64(buf, imm as u64);
}
#[no_mangle]
pub extern "C" fn emit_movb_memq_reg(buf: &mut Assembler,
src: Register,
disp: i32,
dest: Register) {
let rex_prefix = if dest != RAX && dest != RBX && dest != RCX && dest != RDX {
1
} else {
0
};
emit_mov_memq_reg(buf, rex_prefix, 0, 0x8a, src, disp, dest);
}
#[no_mangle]
pub extern "C" fn emit_movl_memq_reg(buf: &mut Assembler,
src: Register,
disp: i32,
dest: Register) {
emit_mov_memq_reg(buf, 0, 0, 0x8b, src, disp, dest);
}
#[no_mangle]
pub extern "C" fn emit_movzbl_memq_reg(buf: &mut Assembler,
src: Register,
disp: i32,
dest: Register) {
let src_msb = if src == RIP { 0 } else { src.msb() };
if dest.msb() != 0 || src_msb != 0 {
emit_rex(buf, 0, dest.msb(), 0, src_msb);
}
emit_op(buf, 0x0F);
emit_op(buf, 0xB6);
emit_membase(buf, src, disp, dest);
}
#[no_mangle]
pub extern "C" fn emit_movq_memq_reg(buf: &mut Assembler,
src: Register,
disp: i32,
dest: Register) {
emit_mov_memq_reg(buf, 0, 1, 0x8b, src, disp, dest);
}
fn emit_mov_memq_reg(buf: &mut Assembler,
rex_prefix: u8,
x64: u8,
opcode: u8,
src: Register,
disp: i32,
dest: Register) {
let src_msb = if src == RIP { 0 } else { src.msb() };
if src_msb != 0 || dest.msb() != 0 || x64 != 0 || rex_prefix != 0 {
emit_rex(buf, x64, dest.msb(), 0, src_msb);
}
emit_op(buf, opcode);
emit_membase(buf, src, disp, dest);
}
#[no_mangle]
pub extern "C" fn emit_movq_reg_memq(buf: &mut Assembler,
src: Register,
dest: Register,
disp: i32) {
emit_mov_reg_memq(buf, 0x89, 1, src, dest, disp);
}
#[no_mangle]
pub extern "C" fn emit_movl_reg_memq(buf: &mut Assembler,
src: Register,
dest: Register,
disp: i32) {
emit_mov_reg_memq(buf, 0x89, 0, src, dest, disp);
}
#[no_mangle]
pub extern "C" fn emit_movb_reg_memq(buf: &mut Assembler,
src: Register,
dest: Register,
disp: i32) {
let dest_msb = if dest == RIP { 0 } else { dest.msb() };
if dest_msb != 0 || src.msb() != 0 || (src != RAX && src != RBX && src != RCX && src != RDX) {
emit_rex(buf, 0, src.msb(), 0, dest.msb());
}
emit_op(buf, 0x88);
emit_membase(buf, dest, disp, src);
}
#[no_mangle]
pub extern "C" fn emit_movb_imm_memq(buf: &mut Assembler, imm: u8, dest: Register, disp: i32) {
let dest_msb = if dest == RIP { 0 } else { dest.msb() };
if dest_msb != 0 {
emit_rex(buf, 0, 0, 0, dest.msb());
}
emit_op(buf, 0xC6);
emit_membase(buf, dest, disp, RAX);
emit(buf, imm);
}
#[no_mangle]
pub extern "C" fn emit_movb_imm_memscaleq(buf: &mut Assembler,
imm: u8,
base: Register,
index: Register,
scale: u8) {
if index.msb() != 0 || base.msb() != 0 {
emit_rex(buf, 0, 0, index.msb(), base.msb());
}
emit_op(buf, 0xC6);
emit_modrm(buf, 0b00, 0b000, 0b100);
emit_sib(buf, scale, index.and7(), base.and7());
emit(buf, imm);
}
#[no_mangle]
pub extern "C" fn emit_movq_ar(buf: &mut Assembler,
base: Register,
index: Register,
scale: u8,
dest: Register) {
emit_mov_ar(buf, 1, 0x8b, base, index, scale, dest);
}
#[no_mangle]
pub extern "C" fn emit_movl_ar(buf: &mut Assembler,
base: Register,
index: Register,
scale: u8,
dest: Register) {
emit_mov_ar(buf, 0, 0x8b, base, index, scale, dest);
}
#[no_mangle]
pub extern "C" fn emit_movq_ra(buf: &mut Assembler,
src: Register,
base: Register,
index: Register,
scale: u8) {
emit_mov_ar(buf, 1, 0x89, base, index, scale, src);
}
#[no_mangle]
pub extern "C" fn emit_movl_ra(buf: &mut Assembler,
src: Register,
base: Register,
index: Register,
scale: u8) {
emit_mov_ar(buf, 0, 0x89, base, index, scale, src);
}
fn emit_mov_ar(buf: &mut Assembler,
x64: u8,
opcode: u8,
base: Register,
index: Register,
scale: u8,
dest: Register) {
assert!(scale == 8 || scale == 4 || scale == 2 || scale == 1);
if x64 != 0 || dest.msb() != 0 || index.msb() != 0 || base.msb() != 0 {
emit_rex(buf, x64, dest.msb(), index.msb(), base.msb());
}
let scale = match scale {
8 => 3,
4 => 2,
2 => 1,
_ => 0,
};
emit_op(buf, opcode);
emit_modrm(buf, 0b00, dest.and7(), 0b100);
emit_sib(buf, scale, index.and7(), base.and7());
}
fn emit_mov_reg_memq(buf: &mut Assembler,
opcode: u8,
x64: u8,
src: Register,
dest: Register,
disp: i32) {
let dest_msb = if dest == RIP { 0 } else { dest.msb() };
if dest_msb != 0 || src.msb() != 0 || x64 != 0 {
emit_rex(buf, x64, src.msb(), 0, dest_msb);
}
emit_op(buf, opcode);
emit_membase(buf, dest, disp, src);
}
fn emit_membase(buf: &mut Assembler, base: Register, disp: i32, dest: Register) {
if base == RSP || base == R12 {
if disp == 0 {
emit_modrm(buf, 0, dest.and7(), RSP.and7());
emit_sib(buf, 0, RSP.and7(), RSP.and7());
} else if fits_i8(disp) {
emit_modrm(buf, 1, dest.and7(), RSP.and7());
emit_sib(buf, 0, RSP.and7(), RSP.and7());
emit(buf, disp as u8);
} else {
emit_modrm(buf, 2, dest.and7(), RSP.and7());
emit_sib(buf, 0, RSP.and7(), RSP.and7());
emit32(buf, disp as u32);
}
} else if disp == 0 && base != RBP && base != R13 && base != RIP {
emit_modrm(buf, 0, dest.and7(), base.and7());
} else if base == RIP {
emit_modrm(buf, 0, dest.and7(), RBP.and7());
emit32(buf, disp as u32);
} else if fits_i8(disp) {
emit_modrm(buf, 1, dest.and7(), base.and7());
emit(buf, disp as u8);
} else {
emit_modrm(buf, 2, dest.and7(), base.and7());
emit32(buf, disp as u32);
}
}
#[no_mangle]
pub extern "C" fn emit_cmp_imm_reg(buf: &mut Assembler,
mode: MachineMode,
imm: i32,
reg: Register) {
let x64 = match mode {
MachineMode::Int8 | MachineMode::Int32 => 0,
MachineMode::Int64 => unimplemented!(),
MachineMode::Float32 | MachineMode::Float64 => unreachable!(),
MachineMode::Ptr => 1,
};
emit_aluq_imm_reg(buf, x64, imm, reg, 0x3d, 0b111);
}
#[no_mangle]
pub extern "C" fn emit_subq_imm_reg(buf: &mut Assembler, imm: i32, reg: Register) {
emit_aluq_imm_reg(buf, 1, imm, reg, 0x2d, 0b101);
}
#[no_mangle]
pub extern "C" fn emit_addq_imm_reg(buf: &mut Assembler, imm: i32, reg: Register) {
emit_aluq_imm_reg(buf, 1, imm, reg, 0x05, 0);
}
#[no_mangle]
pub extern "C" fn emit_andq_imm_reg(buf: &mut Assembler, imm: i32, reg: Register) {
emit_aluq_imm_reg(buf, 1, imm, reg, 0x25, 4);
}
fn emit_aluq_imm_reg(buf: &mut Assembler,
x64: u8,
imm: i32,
reg: Register,
rax_opcode: u8,
modrm_reg: u8) {
assert!(x64 == 0 || x64 == 1);
if x64 != 0 || reg.msb() != 0 {
emit_rex(buf, x64, 0, 0, reg.msb());
}
if fits_i8(imm) {
emit_op(buf, 0x83);
emit_modrm(buf, 0b11, modrm_reg, reg.and7());
emit(buf, imm as u8);
} else if reg == RAX {
emit_op(buf, rax_opcode);
emit32(buf, imm as u32);
} else {
emit_op(buf, 0x81);
emit_modrm(buf, 0b11, modrm_reg, reg.and7());
emit32(buf, imm as u32);
}
}
#[no_mangle]
pub extern "C" fn emit_mov_reg_reg(buf: &mut Assembler, x64: u8, src: Register, dest: Register) {
if x64 != 0 || src.msb() != 0 || dest.msb() != 0 {
emit_rex(buf, x64, src.msb(), 0, dest.msb());
}
emit_op(buf, 0x89);
emit_modrm(buf, 0b11, src.and7(), dest.and7());
}
#[no_mangle]
pub extern "C" fn emit_neg_reg(buf: &mut Assembler, x64: u8, reg: Register) {
emit_alul_reg(buf, 0xf7, 0b11, x64, reg);
}
#[no_mangle]
pub extern "C" fn emit_not_reg(buf: &mut Assembler, x64: u8, reg: Register) {
emit_alul_reg(buf, 0xf7, 0b10, x64, reg);
}
#[no_mangle]
pub extern "C" fn emit_not_reg_byte(buf: &mut Assembler, reg: Register) {
emit_alul_reg(buf, 0xf6, 0b10, 0, reg);
}
fn emit_alul_reg(buf: &mut Assembler, opcode: u8, modrm_reg: u8, x64: u8, reg: Register) {
if reg.msb() != 0 || x64 != 0 {
emit_rex(buf, x64, 0, 0, reg.msb());
}
emit_op(buf, opcode);
emit_modrm(buf, 0b11, modrm_reg, reg.and7());
}
#[no_mangle]
pub extern "C" fn emit_xorb_imm_reg(buf: &mut Assembler, imm: u8, dest: Register) {
emit_alub_imm_reg(buf, 0x80, 0x34, 0b110, imm, dest);
}
#[no_mangle]
pub extern "C" fn emit_andb_imm_reg(buf: &mut Assembler, imm: u8, dest: Register) {
emit_alub_imm_reg(buf, 0x80, 0x24, 0b100, imm, dest);
}
fn emit_alub_imm_reg(buf: &mut Assembler,
opcode: u8,
rax_opcode: u8,
modrm_reg: u8,
imm: u8,
dest: Register) {
if dest == RAX {
emit_op(buf, rax_opcode);
emit(buf, imm);
} else {
if dest.msb() != 0 || !dest.is_basic_reg() {
emit_rex(buf, 0, 0, 0, dest.msb());
}
emit_op(buf, opcode);
emit_modrm(buf, 0b11, modrm_reg, dest.and7());
emit(buf, imm);
}
}
#[no_mangle]
pub extern "C" fn emit_sub_imm_mem(buf: &mut Assembler,
mode: MachineMode,
base: Register,
imm: u8) {
let (x64, opcode) = match mode {
MachineMode::Ptr => (1, 0x83),
MachineMode::Int32 => (0, 0x83),
MachineMode::Int64 => unimplemented!(),
MachineMode::Float32 | MachineMode::Float64 => unreachable!(),
MachineMode::Int8 => (0, 0x80),
};
if x64 != 0 || base.msb() != 0 {
emit_rex(buf, x64, 0, 0, base.msb());
}
emit_op(buf, opcode);
emit_modrm(buf, 0b00, 0b101, base.and7());
emit(buf, imm);
}
#[no_mangle]
pub extern "C" fn emit_pushq_reg(buf: &mut Assembler, reg: Register) {
if reg.msb() != 0 {
emit_rex(buf, 0, 0, 0, 1);
}
emit_op(buf, 0x50 + reg.and7());
}
#[no_mangle]
pub extern "C" fn emit_popq_reg(buf: &mut Assembler, reg: Register) {
if reg.msb() != 0 {
emit_rex(buf, 0, 0, 0, 1);
}
emit_op(buf, 0x58 + reg.and7());
}
#[no_mangle]
pub extern "C" fn emit_retq(buf: &mut Assembler) { emit_op(buf, 0xC3); }
#[no_mangle]
pub extern "C" fn emit_nop(buf: &mut Assembler) { emit_op(buf, 0x90); }
#[no_mangle]
pub extern "C" fn emit64(buf: &mut Assembler, val: u64) { buf.emit64(val) }
#[no_mangle]
pub extern "C" fn emit32(buf: &mut Assembler, val: u32) { buf.emit32(val) }
#[no_mangle]
pub extern "C" fn emit(buf: &mut Assembler, val: u8) { buf.emit(val) }
#[no_mangle]
pub extern "C" fn emit_op(buf: &mut Assembler, opcode: u8) { buf.emit(opcode); }
#[no_mangle]
pub extern "C" fn emit_rex(buf: &mut Assembler, w: u8, r: u8, x: u8, b: u8) {
assert!(w == 0 || w == 1);
assert!(r == 0 || r == 1);
assert!(x == 0 || x == 1);
assert!(b == 0 || b == 1);
buf.emit(0x4 << 4 | w << 3 | r << 2 | x << 1 | b);
}
#[no_mangle]
pub extern "C" fn emit_modrm(buf: &mut Assembler, mode: u8, reg: u8, rm: u8) {
assert!(mode < 4);
assert!(reg < 8);
assert!(rm < 8);
buf.emit(mode << 6 | reg << 3 | rm);
}
#[no_mangle]
pub extern "C" fn emit_sib(buf: &mut Assembler, scale: u8, index: u8, base: u8) {
assert!(scale < 4);
assert!(index < 8);
assert!(base < 8);
buf.emit(scale << 6 | index << 3 | base);
}
#[no_mangle]
pub extern "C" fn fits_i8(imm: i32) -> bool { imm == (imm as i8) as i32 }
#[no_mangle]
pub extern "C" fn emit_jcc(buf: &mut Assembler, cond: CondCode, lbl: Label) {
let opcode = match cond {
CondCode::Zero | CondCode::Equal => 0x84,
CondCode::NonZero | CondCode::NotEqual => 0x85,
CondCode::Greater => 0x8F,
CondCode::GreaterEq => 0x8D,
CondCode::Less => 0x8C,
CondCode::LessEq => 0x8E,
CondCode::UnsignedGreater => 0x87, // above
CondCode::UnsignedGreaterEq => 0x83, // above or equal
CondCode::UnsignedLess => 0x82, // below
CondCode::UnsignedLessEq => 0x86, // below or equal
};
emit_op(buf, 0x0f);
emit_op(buf, opcode);
buf.emit_label(lbl);
}
#[no_mangle]
pub extern "C" fn emit_movsx(buf: &mut Assembler, src: Register, dest: Register) {
emit_rex(buf, 1, dest.msb(), 0, src.msb());
emit_op(buf, 0x63);
emit_modrm(buf, 0b11, dest.and7(), src.and7());
}
#[no_mangle]
pub extern "C" fn emit_jmp(buf: &mut Assembler, lbl: Label) {
emit_op(buf, 0xe9);
buf.emit_label(lbl);
}
#[no_mangle]
pub extern "C" fn emit_jmp_reg(buf: &mut Assembler, reg: Register) {
if reg.msb() != 0 {
emit_rex(buf, 0, 0, 0, reg.msb());
}
emit_op(buf, 0xFF);
emit_modrm(buf, 0b11, 0b100, reg.and7());
}
#[no_mangle]
pub extern "C" fn emit_testl_reg_reg(buf: &mut Assembler, op1: Register, op2: Register) {
if op1.msb() != 0 || op2.msb() != 0 {
emit_rex(buf, 0, op1.msb(), 0, op2.msb());
}
emit_op(buf, 0x85);
emit_modrm(buf, 0b11, op1.and7(), op2.and7());
}
#[no_mangle]
pub extern "C" fn testl_reg_mem(buf: &mut Assembler, dest: Register, src: Mem) {
emit_rex_mem(buf, 0, dest, &src);
emit_op(buf, 0x85);
emit_mem(buf, dest, &src);
}
#[no_mangle]
pub extern "C" fn lea(buf: &mut Assembler, dest: Register, src: Mem) {
emit_rex_mem(buf, 1, dest, &src);
emit_op(buf, 0x8D);
emit_mem(buf, dest, &src);
}
#[no_mangle]
pub extern "C" fn emit_rex_mem(buf: &mut Assembler, x64: u8, dest: Register, src: &Mem) {
assert!(x64 == 0 || x64 == 1);
let (base_msb, index_msb) = match src {
&Mem::Local(_) => (RBP.msb(), 0),
&Mem::Base(base, _) => {
let base_msb = if base == RIP { 0 } else { base.msb() };
(base_msb, 0)
}
&Mem::Index(base, index, _, _) => (base.msb(), index.msb()),
&Mem::Offset(index, _, _) => (0, index.msb()),
};
if dest.msb() != 0 || index_msb != 0 || base_msb != 0 || x64 != 0 {
emit_rex(buf, x64, dest.msb(), index_msb, base_msb);
}
}
#[no_mangle]
pub extern "C" fn emit_mem(buf: &mut Assembler, dest: Register, src: &Mem) {
match src {
&Mem::Local(offset) => {
emit_membase(buf, RBP, offset, dest);
}
&Mem::Base(base, disp) => {
emit_membase(buf, base, disp, dest);
}
&Mem::Index(base, index, scale, disp) => {
emit_membase_with_index_and_scale(buf, base, index, scale, disp, dest);
}
&Mem::Offset(index, scale, disp) => {
emit_membase_without_base(buf, index, scale, disp, dest);
}
}
}
#[no_mangle]
pub extern "C" fn emit_testq_reg_reg(buf: &mut Assembler, op1: Register, op2: Register) {
emit_rex(buf, 1, op1.msb(), 0, op2.msb());
emit_op(buf, 0x85);
emit_modrm(buf, 0b11, op1.and7(), op2.and7());
}
#[no_mangle]
pub extern "C" fn emit_add_reg_reg(buf: &mut Assembler, x64: u8, src: Register, dest: Register) {
if src.msb() != 0 || dest.msb() != 0 || x64 != 0 {
emit_rex(buf, x64, src.msb(), 0, dest.msb());
}
emit_op(buf, 0x01);
emit_modrm(buf, 0b11, src.and7(), dest.and7());
}
#[no_mangle]
pub extern "C" fn emit_sub_reg_reg(buf: &mut Assembler, x64: u8, src: Register, dest: Register) {
if src.msb() != 0 || dest.msb() != 0 || x64 != 0 {
emit_rex(buf, x64, src.msb(), 0, dest.msb());
}
emit_op(buf, 0x29);
emit_modrm(buf, 0b11, src.and7(), dest.and7());
}
#[no_mangle]
pub extern "C" fn emit_imul_reg_reg(buf: &mut Assembler, x64: u8, src: Register, dest: Register) {
if src.msb() != 0 || dest.msb() != 0 || x64 != 0 {
emit_rex(buf, x64, dest.msb(), 0, src.msb());
}
emit_op(buf, 0x0f);
emit_op(buf, 0xaf);
emit_modrm(buf, 0b11, dest.and7(), src.and7());
}
#[no_mangle]
pub extern "C" fn emit_idiv_reg_reg(buf: &mut Assembler, x64: u8, reg: Register) {
if reg.msb() != 0 || x64 != 0 {
emit_rex(buf, x64, 0, 0, reg.msb());
}
emit_op(buf, 0xf7);
emit_modrm(buf, 0b11, 0b111, reg.and7());
}
#[no_mangle]
pub extern "C" fn emit_cmp_reg_reg(buf: &mut Assembler, x64: u8, src: Register, dest: Register) {
emit_alu_reg_reg(buf, x64, 0x39, src, dest);
}
#[no_mangle]
pub extern "C" fn emit_cmp_mem_reg(buf: &mut Assembler,
mode: MachineMode,
base: Register,
disp: i32,
dest: Register) {
let base_msb = if base == RIP { 0 } else { base.msb() };
let (x64, opcode) = match mode {
MachineMode::Int8 => (0, 0x38),
MachineMode::Int32 => (0, 0x39),
MachineMode::Int64 => unimplemented!(),
MachineMode::Float32 | MachineMode::Float64 => unreachable!(),
MachineMode::Ptr => (1, 0x39),
};
if x64 != 0 || dest.msb() != 0 || base_msb != 0 {
emit_rex(buf, x64, dest.msb(), 0, base_msb);
}
emit_op(buf, opcode);
emit_membase(buf, base, disp, dest);
}
#[no_mangle]
pub extern "C" fn emit_mov_memindex_reg(buf: &mut Assembler,
mode: MachineMode,
base: Register,
index: Register,
scale: i32,
disp: i32,
dest: Register) {
assert!(scale == 8 || scale == 4 || scale == 2 || scale == 1);
assert!(mode.size() as i32 == scale);
let (x64, opcode) = match mode {
MachineMode::Int8 => (0, 0x8a),
MachineMode::Int32 => (0, 0x8b),
MachineMode::Int64 | MachineMode::Ptr => (1, 0x8b),
MachineMode::Float32 | MachineMode::Float64 => unreachable!(),
};
if x64 != 0 || dest.msb() != 0 || index.msb() != 0 || base.msb() != 0 {
emit_rex(buf, x64, dest.msb(), index.msb(), base.msb());
}
emit_op(buf, opcode);
emit_membase_with_index_and_scale(buf, base, index, scale, disp, dest);
}
#[no_mangle]
pub extern "C" fn emit_movzx_memindex_byte_reg(buf: &mut Assembler,
x64: u8,
base: Register,
index: Register,
disp: i32,
dest: Register) {
if x64 != 0 || dest.msb() != 0 || index.msb() != 0 || base.msb() != 0 {
emit_rex(buf, x64, dest.msb(), index.msb(), base.msb());
}
emit_op(buf, 0x0f);
emit_op(buf, 0xb6);
emit_membase_with_index_and_scale(buf, base, index, 1, disp, dest);
}
#[no_mangle]
pub extern "C" fn emit_mov_reg_memindex(buf: &mut Assembler,
mode: MachineMode,
src: Register,
base: Register,
index: Register,
scale: i32,
disp: i32) {
assert!(scale == 8 || scale == 4 || scale == 2 || scale == 1);
let (x64, opcode) = match mode {
MachineMode::Int8 => (0, 0x88),
MachineMode::Int32 => (0, 0x89),
MachineMode::Int64 | MachineMode::Ptr => (1, 0x89),
MachineMode::Float32 | MachineMode::Float64 => unreachable!(),
};
if x64 != 0 || src.msb() != 0 || index.msb() != 0 || base.msb() != 0 {
emit_rex(buf, x64, src.msb(), index.msb(), base.msb());
}
emit_op(buf, opcode);
emit_membase_with_index_and_scale(buf, base, index, scale, disp, src);
}
#[no_mangle]
pub extern "C" fn emit_cmp_mem_imm(buf: &mut Assembler,
mode: MachineMode,
base: Register,
disp: i32,
imm: i32) {
let base_msb = if base == RIP { 0 } else { base.msb() };
let opcode = if fits_i8(imm) { 0x83 } else { 0x81 };
let (x64, opcode) = match mode {
MachineMode::Int8 => (0, 0x80),
MachineMode::Int32 => (0, opcode),
MachineMode::Int64 => unimplemented!(),
MachineMode::Ptr => (1, opcode),
MachineMode::Float32 | MachineMode::Float64 => unreachable!(),
};
if x64 != 0 || base_msb != 0 {
emit_rex(buf, x64, 0, 0, base_msb);
}
emit_op(buf, opcode);
emit_membase(buf, base, disp, RDI);
if fits_i8(imm) {
emit(buf, imm as u8);
} else {
if mode == MachineMode::Int8 {
panic!("Int8 does not support 32 bit values");
}
emit32(buf, imm as u32);
}
}
#[no_mangle]
pub extern "C" fn emit_cmp_memindex_reg(buf: &mut Assembler,
mode: MachineMode,
base: Register,
index: Register,
scale: i32,
disp: i32,
dest: Register) {
assert!(scale == 8 || scale == 4 || scale == 2 || scale == 1);
let (x64, opcode) = match mode {
MachineMode::Int8 => (0, 0x38),
MachineMode::Int32 => (0, 0x39),
MachineMode::Int64 => unimplemented!(),
MachineMode::Ptr => (1, 0x39),
MachineMode::Float32 | MachineMode::Float64 => unreachable!(),
};
if x64 != 0 || dest.msb() != 0 || index.msb() != 0 || base.msb() != 0 {
emit_rex(buf, x64, dest.msb(), index.msb(), base.msb());
}
emit_op(buf, opcode);
emit_membase_with_index_and_scale(buf, base, index, scale, disp, dest);
}
fn emit_membase_without_base(buf: &mut Assembler,
index: Register,
scale: i32,
disp: i32,
dest: Register) {
assert!(scale == 8 || scale == 4 || scale == 2 || scale == 1);
let scale = match scale {
8 => 3,
4 => 2,
2 => 1,
_ => 0,
};
emit_modrm(buf, 0, dest.and7(), 4);
emit_sib(buf, scale, index.and7(), 5);
emit32(buf, disp as u32);
}
fn emit_membase_with_index_and_scale(buf: &mut Assembler,
base: Register,
index: Register,
scale: i32,
disp: i32,
dest: Register) {
assert!(scale == 8 || scale == 4 || scale == 2 || scale == 1);
let scale = match scale {
8 => 3,
4 => 2,
2 => 1,
_ => 0,
};
if disp == 0 {
emit_modrm(buf, 0, dest.and7(), 4);
emit_sib(buf, scale, index.and7(), base.and7());
} else if fits_i8(disp) {
emit_modrm(buf, 1, dest.and7(), 4);
emit_sib(buf, scale, index.and7(), base.and7());
emit(buf, disp as u8);
} else {
emit_modrm(buf, 2, dest.and7(), 4);
emit_sib(buf, scale, index.and7(), base.and7());
emit32(buf, disp as u32);
}
}
#[no_mangle]
pub extern "C" fn emit_cdq(buf: &mut Assembler) { emit_op(buf, 0x99); }
#[no_mangle]
pub extern "C" fn emit_cqo(buf: &mut Assembler) {
emit_rex(buf, 1, 0, 0, 0);
emit_op(buf, 0x99);
}
#[no_mangle]
pub extern "C" fn emit_setb_reg(buf: &mut Assembler, op: CondCode, reg: Register) {
if reg.msb() != 0 || !reg.is_basic_reg() {
emit_rex(buf, 0, 0, 0, reg.msb());
}
let op = match op {
CondCode::Less => 0x9c,
CondCode::LessEq => 0x9e,
CondCode::Greater => 0x9f,
CondCode::GreaterEq => 0x9d,
CondCode::UnsignedGreater => 0x97, // above
CondCode::UnsignedGreaterEq => 0x93, // above or equal
CondCode::UnsignedLess => 0x92, // below
CondCode::UnsignedLessEq => 0x96, // below or equal
CondCode::Zero | CondCode::Equal => 0x94,
CondCode::NonZero | CondCode::NotEqual => 0x95,
};
emit_op(buf, 0x0f);
emit_op(buf, op);
emit_modrm(buf, 0b11, 0, reg.and7());
}
#[no_mangle]
pub extern "C" fn emit_setb_reg_parity(buf: &mut Assembler, reg: Register, parity: bool) {
if reg.msb() != 0 || !reg.is_basic_reg() {
emit_rex(buf, 0, 0, 0, reg.msb());
}
let opcode = if parity { 0x9a } else { 0x9b };
emit_op(buf, 0x0f);
emit_op(buf, opcode);
emit_modrm(buf, 0b11, 0, reg.and7());
}
#[no_mangle]
pub extern "C" fn emit_movb_reg_reg(buf: &mut Assembler, src: Register, dest: Register) {
if src.msb() != 0 || dest.msb() != 0 || !src.is_basic_reg() {
emit_rex(buf, 0, dest.msb(), 0, src.msb());
}
emit_op(buf, 0x88);
emit_modrm(buf, 0b11, src.and7(), dest.and7());
}
#[no_mangle]
pub extern "C" fn emit_movzbl_reg_reg(buf: &mut Assembler, src: Register, dest: Register) {
if src.msb() != 0 || dest.msb() != 0 || !src.is_basic_reg() {
emit_rex(buf, 0, dest.msb(), 0, src.msb());
}
emit_op(buf, 0x0f);
emit_op(buf, 0xb6);
emit_modrm(buf, 0b11, dest.and7(), src.and7());
}
#[no_mangle]
pub extern "C" fn emit_cmpb_imm_reg(buf: &mut Assembler, imm: u8, dest: Register) {
if dest == RAX {
emit_op(buf, 0x3c);
emit(buf, imm);
return;
}
if dest.msb() != 0 || !dest.is_basic_reg() {
emit_rex(buf, 0, 0, 0, dest.msb());
}
emit_op(buf, 0x80);
emit_modrm(buf, 0b11, 0b111, dest.and7());
emit(buf, imm);
}
#[no_mangle]
pub extern "C" fn cmov(buf: &mut Assembler,
x64: u8,
dest: Register,
src: Register,
cond: CondCode) {
let opcode = match cond {
CondCode::Zero | CondCode::Equal => 0x44,
CondCode::NonZero | CondCode::NotEqual => 0x45,
CondCode::Greater => 0x4F,
CondCode::GreaterEq => 0x4D,
CondCode::Less => 0x4C,
CondCode::LessEq => 0x4E,
CondCode::UnsignedGreater => 0x47, // above
CondCode::UnsignedGreaterEq => 0x43, // above or equal
CondCode::UnsignedLess => 0x42, // below
CondCode::UnsignedLessEq => 0x46, // below or equal
};
if src.msb() != 0 || dest.msb() != 0 || x64 != 0 {
emit_rex(buf, x64, dest.msb(), 0, src.msb());
}
emit_op(buf, 0x0f);
emit_op(buf, opcode);
emit_modrm(buf, 0b11, dest.and7(), src.and7());
}
#[no_mangle]
pub extern "C" fn emit_callq_reg(buf: &mut Assembler, dest: Register) {
if dest.msb() != 0 {
emit_rex(buf, 0, 0, 0, dest.msb());
}
emit_op(buf, 0xff);
emit_modrm(buf, 0b11, 0b10, dest.and7());
}
#[no_mangle]
pub extern "C" fn emit_shlq_reg(buf: &mut Assembler, imm: u8, dest: Register) {
emit_rex(buf, 1, 0, 0, dest.msb());
emit_op(buf, 0xC1);
emit_modrm(buf, 0b11, 0b100, dest.and7());
emit(buf, imm);
}
#[no_mangle]
pub extern "C" fn emit_shll_reg(buf: &mut Assembler, imm: u8, dest: Register) {
if dest.msb() != 0 {
emit_rex(buf, 0, 0, 0, dest.msb());
}
emit_op(buf, 0xC1);
emit_modrm(buf, 0b11, 0b100, dest.and7());
emit(buf, imm);
}
#[no_mangle]
pub extern "C" fn emit_shl_reg_cl(buf: &mut Assembler, x64: u8, dest: Register) {
if dest.msb() != 0 || x64 != 0 {
emit_rex(buf, x64, 0, 0, dest.msb());
}
emit_op(buf, 0xD3);
emit_modrm(buf, 0b11, 0b100, dest.and7());
}
#[no_mangle]
pub extern "C" fn emit_shr_reg_cl(buf: &mut Assembler, x64: u8, dest: Register) {
if dest.msb() != 0 || x64 != 0 {
emit_rex(buf, x64, 0, 0, dest.msb());
}
emit_op(buf, 0xD3);
emit_modrm(buf, 0b11, 0b101, dest.and7());
}
pub extern "C" fn emit_shr_reg_imm(buf: &mut Assembler, x64: u8, dest: Register, imm: u8) {
if dest.msb() != 0 || x64 != 0 {
emit_rex(buf, x64, 0, 0, dest.msb());
}
emit_op(buf, if imm == 1 { 0xD1 } else { 0xC1 });
emit_modrm(buf, 0b11, 0b101, dest.and7());
if imm != 1 {
emit(buf, imm);
}
}
pub extern "C" fn emit_sar_reg_cl(buf: &mut Assembler, x64: u8, dest: Register) {
if dest.msb() != 0 || x64 != 0 {
emit_rex(buf, x64, 0, 0, dest.msb());
}
emit_op(buf, 0xD3);
emit_modrm(buf, 0b11, 0b111, dest.and7());
}
pub extern "C" fn emit_movzx_byte(buf: &mut Assembler, x64: u8, src: Register, dest: Register) {
if src.msb() != 0 || dest.msb() != 0 || x64 != 0 {
emit_rex(buf, x64, dest.msb(), 0, src.msb());
}
emit_op(buf, 0x0f);
emit_op(buf, 0xb6);
emit_modrm(buf, 0b11, dest.and7(), src.and7());
}
#[no_mangle]
pub extern "C" fn addss(buf: &mut Assembler, dest: XMMRegister, src: XMMRegister) {
sse_float_freg_freg(buf, false, 0x58, dest, src);
}
#[no_mangle]
pub extern "C" fn addsd(buf: &mut Assembler, dest: XMMRegister, src: XMMRegister) {
sse_float_freg_freg(buf, true, 0x58, dest, src);
}
#[no_mangle]
pub extern "C" fn subss(buf: &mut Assembler, dest: XMMRegister, src: XMMRegister) {
sse_float_freg_freg(buf, false, 0x5c, dest, src);
}
#[no_mangle]
pub extern "C" fn subsd(buf: &mut Assembler, dest: XMMRegister, src: XMMRegister) {
sse_float_freg_freg(buf, true, 0x5c, dest, src);
}
#[no_mangle]
pub extern "C" fn mulss(buf: &mut Assembler, dest: XMMRegister, src: XMMRegister) {
sse_float_freg_freg(buf, false, 0x59, dest, src);
}
#[no_mangle]
pub extern "C" fn mulsd(buf: &mut Assembler, dest: XMMRegister, src: XMMRegister) {
sse_float_freg_freg(buf, true, 0x59, dest, src);
}
#[no_mangle]
pub extern "C" fn divss(buf: &mut Assembler, dest: XMMRegister, src: XMMRegister) {
sse_float_freg_freg(buf, false, 0x5e, dest, src);
}
#[no_mangle]
pub extern "C" fn divsd(buf: &mut Assembler, dest: XMMRegister, src: XMMRegister) {
sse_float_freg_freg(buf, true, 0x5e, dest, src);
}
#[no_mangle]
pub extern "C" fn sqrtss(buf: &mut Assembler, dest: XMMRegister, src: XMMRegister) {
sse_float_freg_freg(buf, false, 0x51, dest, src);
}
#[no_mangle]
pub extern "C" fn sqrtsd(buf: &mut Assembler, dest: XMMRegister, src: XMMRegister) {
sse_float_freg_freg(buf, true, 0x51, dest, src);
}
#[no_mangle]
pub extern "C" fn movaps(buf: &mut Assembler, dest: XMMRegister, src: XMMRegister) {
sse_packed_freg_freg(buf, 0x28, dest, src);
}
#[no_mangle]
pub extern "C" fn movups(buf: &mut Assembler, dest: XMMRegister, src: XMMRegister) {
sse_packed_freg_freg(buf, 0x10, dest, src);
}
#[no_mangle]
pub extern "C" fn movups_load(buf: &mut Assembler, dest: XMMRegister, src: Mem) {
sse_packed_freg_mem(buf, 0x10, dest, src)
}
#[no_mangle]
pub extern "C" fn movups_store(buf: &mut Assembler, dest: Mem, src: XMMRegister) {
sse_packed_freg_mem(buf, 0x11, src, dest);
}
#[no_mangle]
pub extern "C" fn movaps_load(buf: &mut Assembler, dest: XMMRegister, src: Mem) {
sse_packed_freg_mem(buf, 0x28, dest, src)
}
#[no_mangle]
pub extern "C" fn movaps_store(buf: &mut Assembler, dest: Mem, src: XMMRegister) {
sse_packed_freg_mem(buf, 0x29, src, dest);
}
#[no_mangle]
pub extern "C" fn addps(buf: &mut Assembler, dest: XMMRegister, src: XMMRegister) {
sse_packed_freg_freg(buf, 0x58, dest, src);
}
#[no_mangle]
pub extern "C" fn subps(buf: &mut Assembler, dest: XMMRegister, src: XMMRegister) {
sse_packed_freg_freg(buf, 0x5c, dest, src);
}
#[no_mangle]
pub extern "C" fn mulps(buf: &mut Assembler, dest: XMMRegister, src: XMMRegister) {
sse_packed_freg_freg(buf, 0x59, dest, src);
}
#[no_mangle]
pub extern "C" fn divps(buf: &mut Assembler, dest: XMMRegister, src: XMMRegister) {
sse_packed_freg_freg(buf, 0x5e, dest, src);
}
#[no_mangle]
pub extern "C" fn sqrtps(buf: &mut Assembler, dest: XMMRegister, src: XMMRegister) {
sse_packed_freg_freg(buf, 0x51, dest, src);
}
#[no_mangle]
pub extern "C" fn movlps(buf: &mut Assembler, dest: XMMRegister, src: XMMRegister) {
sse_packed_freg_freg(buf, 0x45, dest, src);
}
#[no_mangle]
pub extern "C" fn movss(buf: &mut Assembler, dest: XMMRegister, src: XMMRegister) {
sse_float_freg_freg(buf, false, 0x10, dest, src);
}
#[no_mangle]
pub extern "C" fn movss_load(buf: &mut Assembler, dest: XMMRegister, mem: Mem) {
sse_float_freg_mem(buf, false, 0x10, dest, mem);
}
#[no_mangle]
pub extern "C" fn movss_store(buf: &mut Assembler, mem: Mem, src: XMMRegister) {
sse_float_freg_mem(buf, false, 0x11, src, mem);
}
#[no_mangle]
pub extern "C" fn movsd(buf: &mut Assembler, dest: XMMRegister, src: XMMRegister) {
sse_float_freg_freg(buf, true, 0x10, dest, src);
}
#[no_mangle]
pub extern "C" fn movsd_load(buf: &mut Assembler, dest: XMMRegister, mem: Mem) {
sse_float_freg_mem(buf, true, 0x10, dest, mem);
}
#[no_mangle]
pub extern "C" fn movsd_store(buf: &mut Assembler, mem: Mem, src: XMMRegister) {
sse_float_freg_mem(buf, true, 0x11, src, mem);
}
#[no_mangle]
pub extern "C" fn cvtsd2ss(buf: &mut Assembler, dest: XMMRegister, src: XMMRegister) {
sse_float_freg_freg(buf, true, 0x5a, dest, src);
}
#[no_mangle]
pub extern "C" fn cvtss2sd(buf: &mut Assembler, dest: XMMRegister, src: XMMRegister) {
sse_float_freg_freg(buf, false, 0x5a, dest, src);
}
#[no_mangle]
pub extern "C" fn cvtsi2ss(buf: &mut Assembler, dest: XMMRegister, x64: u8, src: Register) {
sse_float_freg_reg(buf, false, 0x2a, dest, x64, src);
}
#[no_mangle]
pub extern "C" fn cvtsi2sd(buf: &mut Assembler, dest: XMMRegister, x64: u8, src: Register) {
sse_float_freg_reg(buf, true, 0x2a, dest, x64, src);
}
#[no_mangle]
pub extern "C" fn cvttss2si(buf: &mut Assembler, x64: u8, dest: Register, src: XMMRegister) {
sse_float_reg_freg(buf, false, 0x2c, x64, dest, src);
}
#[no_mangle]
pub extern "C" fn movd_reg_freg(buf: &mut Assembler, dest: Register, src: XMMRegister) {
sse_reg_freg(buf, 0x66, 0, dest, src);
}
#[no_mangle]
pub extern "C" fn movq_reg_freg(buf: &mut Assembler, dest: Register, src: XMMRegister) {
sse_reg_freg(buf, 0x66, 1, dest, src);
}
#[no_mangle]
pub extern "C" fn movd_freg_reg(buf: &mut Assembler, dest: XMMRegister, src: Register) {
sse_freg_reg(buf, 0x66, 0, dest, src);
}
#[no_mangle]
pub extern "C" fn movq_freg_reg(buf: &mut Assembler, dest: XMMRegister, src: Register) {
sse_freg_reg(buf, 0x66, 1, dest, src);
}
fn sse_reg_freg(buf: &mut Assembler, op: u8, x64: u8, dest: Register, src: XMMRegister) {
emit_op(buf, op);
if x64 != 0 || dest.msb() != 0 || src.msb() != 0 {
emit_rex(buf, x64, dest.msb(), 0, src.msb());
}
emit_op(buf, 0x0f);
emit_op(buf, 0x7e);
emit_modrm(buf, 0b11, dest.and7(), src.and7());
}
fn sse_freg_reg(buf: &mut Assembler, op: u8, x64: u8, dest: XMMRegister, src: Register) {
emit_op(buf, op);
if x64 != 0 || dest.msb() != 0 || src.msb() != 0 {
emit_rex(buf, x64, dest.msb(), 0, src.msb());
}
emit_op(buf, 0x0f);
emit_op(buf, 0x6e);
emit_modrm(buf, 0b11, dest.and7(), src.and7());
}
#[no_mangle]
pub extern "C" fn cvttsd2si(buf: &mut Assembler, x64: u8, dest: Register, src: XMMRegister) {
sse_float_reg_freg(buf, true, 0x2c, x64, dest, src);
}
#[no_mangle]
pub extern "C" fn xorps(buf: &mut Assembler, dest: XMMRegister, src: Mem) {
sse_float_freg_mem_66(buf, false, 0x57, dest, src);
}
#[no_mangle]
pub extern "C" fn xorpd(buf: &mut Assembler, dest: XMMRegister, src: Mem) {
sse_float_freg_mem_66(buf, true, 0x57, dest, src);
}
#[no_mangle]
pub extern "C" fn sse_packed_freg_freg(buf: &mut Assembler,
op: u8,
dest: XMMRegister,
src: XMMRegister) {
if dest.msb() != 0 || src.msb() != 0 {
emit_rex(buf, 0, dest.msb(), 0, src.msb());
}
emit_op(buf, 0x0f);
emit_op(buf, op);
emit_modrm(buf, 0b11, dest.and7(), src.and7());
}
#[no_mangle]
pub extern "C" fn sse_float_freg_freg(buf: &mut Assembler,
dbl: bool,
op: u8,
dest: XMMRegister,
src: XMMRegister) {
let prefix = if dbl { 0xf2 } else { 0xf3 };
emit_op(buf, prefix);
if dest.msb() != 0 || src.msb() != 0 {
emit_rex(buf, 0, dest.msb(), 0, src.msb());
}
emit_op(buf, 0x0f);
emit_op(buf, op);
emit_modrm(buf, 0b11, dest.and7(), src.and7());
}
#[no_mangle]
pub extern "C" fn sse_float_freg_mem(buf: &mut Assembler,
dbl: bool,
op: u8,
dest: XMMRegister,
src: Mem) {
let prefix = if dbl { 0xf2 } else { 0xf3 };
emit_op(buf, prefix);
emit_rex_mem(buf, 0, unsafe { ::core::mem::transmute(dest) }, &src);
emit_op(buf, 0x0f);
emit_op(buf, op);
emit_mem(buf, unsafe { ::core::mem::transmute(dest) }, &src);
}
#[no_mangle]
pub extern "C" fn sse_packed_freg_mem(buf: &mut Assembler, op: u8, dest: XMMRegister, src: Mem) {
emit_rex_mem(buf, 0, unsafe { ::core::mem::transmute(dest) }, &src);
emit_op(buf, 0x0f);
emit_op(buf, op);
emit_mem(buf, unsafe { ::core::mem::transmute(dest) }, &src);
}
#[no_mangle]
pub extern "C" fn sse_float_freg_mem_66(buf: &mut Assembler,
dbl: bool,
op: u8,
dest: XMMRegister,
src: Mem) {
if dbl {
emit_op(buf, 0x66);
}
emit_rex_mem(buf, 0, unsafe { ::core::mem::transmute(dest) }, &src);
emit_op(buf, 0x0f);
emit_op(buf, op);
emit_mem(buf,
/*Register(dest.0)*/ unsafe { ::core::mem::transmute(dest) },
&src);
}
#[no_mangle]
pub extern "C" fn sse_float_freg_reg(buf: &mut Assembler,
dbl: bool,
op: u8,
dest: XMMRegister,
x64: u8,
src: Register) {
let prefix = if dbl { 0xf2 } else { 0xf3 };
emit_op(buf, prefix);
if x64 != 0 || dest.msb() != 0 || src.msb() != 0 {
emit_rex(buf, x64, dest.msb(), 0, src.msb());
}
emit_op(buf, 0x0f);
emit_op(buf, op);
emit_modrm(buf, 0b11, dest.and7(), src.and7());
}
#[no_mangle]
pub extern "C" fn sse_float_reg_freg(buf: &mut Assembler,
dbl: bool,
op: u8,
x64: u8,
dest: Register,
src: XMMRegister) {
let prefix = if dbl { 0xf2 } else { 0xf3 };
emit_op(buf, prefix);
if x64 != 0 || dest.msb() != 0 || src.msb() != 0 {
emit_rex(buf, x64, dest.msb(), 0, src.msb());
}
emit_op(buf, 0x0f);
emit_op(buf, op);
emit_modrm(buf, 0b11, dest.and7(), src.and7());
}
/*pub extern "C" fn pxor(buf: &mut Assembler, dest: XMMRegister, src: XMMRegister) {
emit_op(buf, 0x66);
if dest.msb() != 0 || src.msb() != 0 {
emit_rex(buf, 0, dest.msb(), 0, src.msb());
}
emit_op(buf, 0x0f);
emit_op(buf, 0xef);
emit_modrm(buf, 0b11, dest.and7(), src.and7());
}*/
#[no_mangle]
pub extern "C" fn ucomiss(buf: &mut Assembler, dest: XMMRegister, src: XMMRegister) {
sse_cmp(buf, false, dest, src);
}
#[no_mangle]
pub extern "C" fn ucomisd(buf: &mut Assembler, dest: XMMRegister, src: XMMRegister) {
sse_cmp(buf, true, dest, src);
}
fn sse_cmp(buf: &mut Assembler, dbl: bool, dest: XMMRegister, src: XMMRegister) {
if dbl {
emit_op(buf, 0x66);
}
if dest.msb() != 0 || src.msb() != 0 {
emit_rex(buf, 0, dest.msb(), 0, src.msb());
}
emit_op(buf, 0x0f);
emit_op(buf, 0x2e);
emit_modrm(buf, 0b11, dest.and7(), src.and7());
}
fn sse_optional_rex_32_ff(buf: &mut Assembler, reg: XMMRegister, base: XMMRegister) {
let rex_bits = (reg as u8 & 0x8) >> 1 | (base as u8 & 0x8) >> 3;
if rex_bits != 0 {
buf.emit(0x40 | rex_bits);
}
}
fn sse_optional_rex32_fm(buf: &mut Assembler, reg: XMMRegister, base: Mem) {
use crate::avx::*;
let rex_bits = emit_rex_memv(buf, 0, unsafe { std::mem::transmute(reg) }, &base);
if rex_bits != 0 {
buf.emit(0x40 | rex_bits);
}
}
fn ssse3_or_4_instr(buf: &mut Assembler,
dst: XMMRegister,
src: XMMRegister,
prefix: u8,
escape1: u8,
escape2: u8,
opcode: u8) {
buf.emit(prefix);
sse_optional_rex_32_ff(buf, dst, src);
buf.emit(escape1);
buf.emit(escape2);
buf.emit(opcode);
emit_sse_ff(buf, dst, src)
}
fn ssse3_or_4_instr_mem(buf: &mut Assembler,
dst: XMMRegister,
src: Mem,
prefix: u8,
escape1: u8,
escape2: u8,
opcode: u8) {
buf.emit(prefix);
sse_optional_rex32_fm(buf, dst, src);
buf.emit(escape1);
buf.emit(escape2);
buf.emit(opcode);
emit_sse_mem_f(buf, dst, src)
}
fn sse2_instr(buf: &mut Assembler,
dst: XMMRegister,
src: XMMRegister,
prefix: u8,
escape: u8,
opcode: u8) {
use crate::avx::emit_sse_ff;
buf.emit(prefix);
sse_optional_rex_32_ff(buf, dst, src);
buf.emit(escape);
buf.emit(opcode);
emit_sse_ff(buf, dst, src);
}
fn sse2_instr_mem(buf: &mut Assembler,
dst: XMMRegister,
src: Mem,
prefix: u8,
escape: u8,
opcode: u8) {
buf.emit(prefix);
sse_optional_rex32_fm(buf, dst, src);
buf.emit(escape);
buf.emit(opcode);
crate::avx::emit_sse_mem_f(buf, dst, src);
}
#[no_mangle]
pub extern "C" fn cvtps2dq(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
sse2_instr(buf, dst, src, 102, 15, 91);
}
#[no_mangle]
pub extern "C" fn punpcklbw(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
sse2_instr(buf, dst, src, 102, 15, 96);
}
#[no_mangle]
pub extern "C" fn punpcklwd(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
sse2_instr(buf, dst, src, 102, 15, 97);
}
#[no_mangle]
pub extern "C" fn punpckldq(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
sse2_instr(buf, dst, src, 102, 15, 98);
}
#[no_mangle]
pub extern "C" fn packsswb(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
sse2_instr(buf, dst, src, 102, 15, 99);
}
#[no_mangle]
pub extern "C" fn packuswb(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
sse2_instr(buf, dst, src, 102, 15, 103);
}
#[no_mangle]
pub extern "C" fn punpckhbw(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
sse2_instr(buf, dst, src, 102, 15, 104);
}
#[no_mangle]
pub extern "C" fn punpckhwd(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
sse2_instr(buf, dst, src, 102, 15, 105);
}
#[no_mangle]
pub extern "C" fn punpckhdq(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
sse2_instr(buf, dst, src, 102, 15, 106);
}
#[no_mangle]
pub extern "C" fn packssdw(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
sse2_instr(buf, dst, src, 102, 15, 107);
}
#[no_mangle]
pub extern "C" fn punpcklqdq(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
sse2_instr(buf, dst, src, 102, 15, 108);
}
#[no_mangle]
pub extern "C" fn punpckhqdq(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
sse2_instr(buf, dst, src, 102, 15, 109);
}
#[no_mangle]
pub extern "C" fn paddb(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
sse2_instr(buf, dst, src, 102, 15, 252);
}
#[no_mangle]
pub extern "C" fn paddw(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
sse2_instr(buf, dst, src, 102, 15, 253);
}
#[no_mangle]
pub extern "C" fn paddd(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
sse2_instr(buf, dst, src, 102, 15, 254);
}
#[no_mangle]
pub extern "C" fn paddsb(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
sse2_instr(buf, dst, src, 102, 15, 236);
}
#[no_mangle]
pub extern "C" fn paddsw(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
sse2_instr(buf, dst, src, 102, 15, 237);
}
#[no_mangle]
pub extern "C" fn paddusb(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
sse2_instr(buf, dst, src, 102, 15, 220);
}
#[no_mangle]
pub extern "C" fn paddusw(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
sse2_instr(buf, dst, src, 102, 15, 221);
}
#[no_mangle]
pub extern "C" fn pcmpeqb(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
sse2_instr(buf, dst, src, 102, 15, 116);
}
#[no_mangle]
pub extern "C" fn pcmpeqw(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
sse2_instr(buf, dst, src, 102, 15, 117);
}
#[no_mangle]
pub extern "C" fn pcmpeqd(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
sse2_instr(buf, dst, src, 102, 15, 118);
}
#[no_mangle]
pub extern "C" fn pcmpgtb(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
sse2_instr(buf, dst, src, 102, 15, 100);
}
#[no_mangle]
pub extern "C" fn pcmpgtw(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
sse2_instr(buf, dst, src, 102, 15, 101);
}
#[no_mangle]
pub extern "C" fn pcmpgtd(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
sse2_instr(buf, dst, src, 102, 15, 102);
}
#[no_mangle]
pub extern "C" fn pmaxsw(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
sse2_instr(buf, dst, src, 102, 15, 238);
}
#[no_mangle]
pub extern "C" fn pmaxub(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
sse2_instr(buf, dst, src, 102, 15, 222);
}
#[no_mangle]
pub extern "C" fn pminsw(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
sse2_instr(buf, dst, src, 102, 15, 234);
}
#[no_mangle]
pub extern "C" fn pminub(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
sse2_instr(buf, dst, src, 102, 15, 218);
}
#[no_mangle]
pub extern "C" fn pmullw(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
sse2_instr(buf, dst, src, 102, 15, 213);
}
#[no_mangle]
pub extern "C" fn pmuludq(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
sse2_instr(buf, dst, src, 102, 15, 244);
}
#[no_mangle]
pub extern "C" fn psllw(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
sse2_instr(buf, dst, src, 102, 15, 241);
}
#[no_mangle]
pub extern "C" fn pslld(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
sse2_instr(buf, dst, src, 102, 15, 242);
}
#[no_mangle]
pub extern "C" fn psraw(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
sse2_instr(buf, dst, src, 102, 15, 225);
}
#[no_mangle]
pub extern "C" fn psrad(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
sse2_instr(buf, dst, src, 102, 15, 226);
}
#[no_mangle]
pub extern "C" fn psrlw(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
sse2_instr(buf, dst, src, 102, 15, 209);
}
#[no_mangle]
pub extern "C" fn psrld(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
sse2_instr(buf, dst, src, 102, 15, 210);
}
#[no_mangle]
pub extern "C" fn psubb(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
sse2_instr(buf, dst, src, 102, 15, 248);
}
#[no_mangle]
pub extern "C" fn psubw(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
sse2_instr(buf, dst, src, 102, 15, 249);
}
#[no_mangle]
pub extern "C" fn psubd(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
sse2_instr(buf, dst, src, 102, 15, 250);
}
#[no_mangle]
pub extern "C" fn psubsb(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
sse2_instr(buf, dst, src, 102, 15, 232);
}
#[no_mangle]
pub extern "C" fn psubsw(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
sse2_instr(buf, dst, src, 102, 15, 233);
}
#[no_mangle]
pub extern "C" fn psubusb(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
sse2_instr(buf, dst, src, 102, 15, 216);
}
#[no_mangle]
pub extern "C" fn psubusw(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
sse2_instr(buf, dst, src, 102, 15, 217);
}
#[no_mangle]
pub extern "C" fn pand(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
sse2_instr(buf, dst, src, 102, 15, 219);
}
#[no_mangle]
pub extern "C" fn por(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
sse2_instr(buf, dst, src, 102, 15, 235);
}
#[no_mangle]
pub extern "C" fn pxor(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
sse2_instr(buf, dst, src, 102, 15, 239);
}
#[no_mangle]
pub extern "C" fn cvtps2dq_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
sse2_instr_mem(buf, dst, src, 102, 15, 91);
}
#[no_mangle]
pub extern "C" fn punpcklbw_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
sse2_instr_mem(buf, dst, src, 102, 15, 96);
}
#[no_mangle]
pub extern "C" fn punpcklwd_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
sse2_instr_mem(buf, dst, src, 102, 15, 97);
}
#[no_mangle]
pub extern "C" fn punpckldq_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
sse2_instr_mem(buf, dst, src, 102, 15, 98);
}
#[no_mangle]
pub extern "C" fn packsswb_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
sse2_instr_mem(buf, dst, src, 102, 15, 99);
}
#[no_mangle]
pub extern "C" fn packuswb_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
sse2_instr_mem(buf, dst, src, 102, 15, 103);
}
#[no_mangle]
pub extern "C" fn punpckhbw_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
sse2_instr_mem(buf, dst, src, 102, 15, 104);
}
#[no_mangle]
pub extern "C" fn punpckhwd_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
sse2_instr_mem(buf, dst, src, 102, 15, 105);
}
#[no_mangle]
pub extern "C" fn punpckhdq_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
sse2_instr_mem(buf, dst, src, 102, 15, 106);
}
#[no_mangle]
pub extern "C" fn packssdw_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
sse2_instr_mem(buf, dst, src, 102, 15, 107);
}
#[no_mangle]
pub extern "C" fn punpcklqdq_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
sse2_instr_mem(buf, dst, src, 102, 15, 108);
}
#[no_mangle]
pub extern "C" fn punpckhqdq_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
sse2_instr_mem(buf, dst, src, 102, 15, 109);
}
#[no_mangle]
pub extern "C" fn paddb_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
sse2_instr_mem(buf, dst, src, 102, 15, 252);
}
#[no_mangle]
pub extern "C" fn paddw_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
sse2_instr_mem(buf, dst, src, 102, 15, 253);
}
#[no_mangle]
pub extern "C" fn paddd_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
sse2_instr_mem(buf, dst, src, 102, 15, 254);
}
#[no_mangle]
pub extern "C" fn paddsb_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
sse2_instr_mem(buf, dst, src, 102, 15, 236);
}
#[no_mangle]
pub extern "C" fn paddsw_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
sse2_instr_mem(buf, dst, src, 102, 15, 237);
}
#[no_mangle]
pub extern "C" fn paddusb_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
sse2_instr_mem(buf, dst, src, 102, 15, 220);
}
#[no_mangle]
pub extern "C" fn paddusw_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
sse2_instr_mem(buf, dst, src, 102, 15, 221);
}
#[no_mangle]
pub extern "C" fn pcmpeqb_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
sse2_instr_mem(buf, dst, src, 102, 15, 116);
}
#[no_mangle]
pub extern "C" fn pcmpeqw_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
sse2_instr_mem(buf, dst, src, 102, 15, 117);
}
#[no_mangle]
pub extern "C" fn pcmpeqd_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
sse2_instr_mem(buf, dst, src, 102, 15, 118);
}
#[no_mangle]
pub extern "C" fn pcmpgtb_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
sse2_instr_mem(buf, dst, src, 102, 15, 100);
}
#[no_mangle]
pub extern "C" fn pcmpgtw_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
sse2_instr_mem(buf, dst, src, 102, 15, 101);
}
#[no_mangle]
pub extern "C" fn pcmpgtd_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
sse2_instr_mem(buf, dst, src, 102, 15, 102);
}
#[no_mangle]
pub extern "C" fn pmaxsw_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
sse2_instr_mem(buf, dst, src, 102, 15, 238);
}
#[no_mangle]
pub extern "C" fn pmaxub_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
sse2_instr_mem(buf, dst, src, 102, 15, 222);
}
#[no_mangle]
pub extern "C" fn pminsw_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
sse2_instr_mem(buf, dst, src, 102, 15, 234);
}
#[no_mangle]
pub extern "C" fn pminub_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
sse2_instr_mem(buf, dst, src, 102, 15, 218);
}
#[no_mangle]
pub extern "C" fn pmullw_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
sse2_instr_mem(buf, dst, src, 102, 15, 213);
}
#[no_mangle]
pub extern "C" fn pmuludq_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
sse2_instr_mem(buf, dst, src, 102, 15, 244);
}
#[no_mangle]
pub extern "C" fn psllw_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
sse2_instr_mem(buf, dst, src, 102, 15, 241);
}
#[no_mangle]
pub extern "C" fn pslld_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
sse2_instr_mem(buf, dst, src, 102, 15, 242);
}
#[no_mangle]
pub extern "C" fn psraw_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
sse2_instr_mem(buf, dst, src, 102, 15, 225);
}
#[no_mangle]
pub extern "C" fn psrad_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
sse2_instr_mem(buf, dst, src, 102, 15, 226);
}
#[no_mangle]
pub extern "C" fn psrlw_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
sse2_instr_mem(buf, dst, src, 102, 15, 209);
}
#[no_mangle]
pub extern "C" fn psrld_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
sse2_instr_mem(buf, dst, src, 102, 15, 210);
}
#[no_mangle]
pub extern "C" fn psubb_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
sse2_instr_mem(buf, dst, src, 102, 15, 248);
}
#[no_mangle]
pub extern "C" fn psubw_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
sse2_instr_mem(buf, dst, src, 102, 15, 249);
}
#[no_mangle]
pub extern "C" fn psubd_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
sse2_instr_mem(buf, dst, src, 102, 15, 250);
}
#[no_mangle]
pub extern "C" fn psubsb_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
sse2_instr_mem(buf, dst, src, 102, 15, 232);
}
#[no_mangle]
pub extern "C" fn psubsw_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
sse2_instr_mem(buf, dst, src, 102, 15, 233);
}
#[no_mangle]
pub extern "C" fn psubusb_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
sse2_instr_mem(buf, dst, src, 102, 15, 216);
}
#[no_mangle]
pub extern "C" fn psubusw_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
sse2_instr_mem(buf, dst, src, 102, 15, 217);
}
#[no_mangle]
pub extern "C" fn pand_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
sse2_instr_mem(buf, dst, src, 102, 15, 219);
}
#[no_mangle]
pub extern "C" fn por_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
sse2_instr_mem(buf, dst, src, 102, 15, 235);
}
#[no_mangle]
pub extern "C" fn pxor_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
sse2_instr_mem(buf, dst, src, 102, 15, 239);
}
#[no_mangle]
use crate::avx::*;
use crate::avx::SIMDPrefix::*;
//sse2_instr_list!(sse2_instr_def);
pub extern "C" fn vcvtps2dq_mem(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: Mem) {
vinstrm(buf,
91,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vcvtps2dq(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: XMMRegister) {
vinstr(buf,
91,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpunpcklbw_mem(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: Mem) {
vinstrm(buf,
96,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpunpcklbw(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: XMMRegister) {
vinstr(buf,
96,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpunpcklwd_mem(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: Mem) {
vinstrm(buf,
97,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpunpcklwd(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: XMMRegister) {
vinstr(buf,
97,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpunpckldq_mem(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: Mem) {
vinstrm(buf,
98,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpunpckldq(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: XMMRegister) {
vinstr(buf,
98,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpacksswb_mem(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: Mem) {
vinstrm(buf,
99,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpacksswb(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: XMMRegister) {
vinstr(buf,
99,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpackuswb_mem(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: Mem) {
vinstrm(buf,
103,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpackuswb(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: XMMRegister) {
vinstr(buf,
103,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpunpckhbw_mem(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: Mem) {
vinstrm(buf,
104,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpunpckhbw(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: XMMRegister) {
vinstr(buf,
104,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpunpckhwd_mem(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: Mem) {
vinstrm(buf,
105,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpunpckhwd(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: XMMRegister) {
vinstr(buf,
105,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpunpckhdq_mem(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: Mem) {
vinstrm(buf,
106,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpunpckhdq(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: XMMRegister) {
vinstr(buf,
106,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpackssdw_mem(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: Mem) {
vinstrm(buf,
107,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpackssdw(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: XMMRegister) {
vinstr(buf,
107,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpunpcklqdq_mem(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: Mem) {
vinstrm(buf,
108,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpunpcklqdq(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: XMMRegister) {
vinstr(buf,
108,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpunpckhqdq_mem(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: Mem) {
vinstrm(buf,
109,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpunpckhqdq(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: XMMRegister) {
vinstr(buf,
109,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpaddb_mem(buf: &mut Assembler, dst: XMMRegister, src1: XMMRegister, src2: Mem) {
vinstrm(buf,
252,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpaddb(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: XMMRegister) {
vinstr(buf,
252,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpaddw_mem(buf: &mut Assembler, dst: XMMRegister, src1: XMMRegister, src2: Mem) {
vinstrm(buf,
253,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpaddw(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: XMMRegister) {
vinstr(buf,
253,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpaddd_mem(buf: &mut Assembler, dst: XMMRegister, src1: XMMRegister, src2: Mem) {
vinstrm(buf,
254,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpaddd(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: XMMRegister) {
vinstr(buf,
254,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpaddsb_mem(buf: &mut Assembler, dst: XMMRegister, src1: XMMRegister, src2: Mem) {
vinstrm(buf,
236,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpaddsb(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: XMMRegister) {
vinstr(buf,
236,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpaddsw_mem(buf: &mut Assembler, dst: XMMRegister, src1: XMMRegister, src2: Mem) {
vinstrm(buf,
237,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpaddsw(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: XMMRegister) {
vinstr(buf,
237,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpaddusb_mem(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: Mem) {
vinstrm(buf,
220,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpaddusb(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: XMMRegister) {
vinstr(buf,
220,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpaddusw_mem(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: Mem) {
vinstrm(buf,
221,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpaddusw(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: XMMRegister) {
vinstr(buf,
221,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpcmpeqb_mem(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: Mem) {
vinstrm(buf,
116,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpcmpeqb(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: XMMRegister) {
vinstr(buf,
116,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpcmpeqw_mem(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: Mem) {
vinstrm(buf,
117,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpcmpeqw(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: XMMRegister) {
vinstr(buf,
117,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpcmpeqd_mem(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: Mem) {
vinstrm(buf,
118,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpcmpeqd(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: XMMRegister) {
vinstr(buf,
118,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpcmpgtb_mem(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: Mem) {
vinstrm(buf,
100,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpcmpgtb(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: XMMRegister) {
vinstr(buf,
100,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpcmpgtw_mem(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: Mem) {
vinstrm(buf,
101,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpcmpgtw(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: XMMRegister) {
vinstr(buf,
101,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpcmpgtd_mem(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: Mem) {
vinstrm(buf,
102,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpcmpgtd(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: XMMRegister) {
vinstr(buf,
102,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpmaxsw_mem(buf: &mut Assembler, dst: XMMRegister, src1: XMMRegister, src2: Mem) {
vinstrm(buf,
238,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpmaxsw(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: XMMRegister) {
vinstr(buf,
238,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpmaxub_mem(buf: &mut Assembler, dst: XMMRegister, src1: XMMRegister, src2: Mem) {
vinstrm(buf,
222,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpmaxub(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: XMMRegister) {
vinstr(buf,
222,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpminsw_mem(buf: &mut Assembler, dst: XMMRegister, src1: XMMRegister, src2: Mem) {
vinstrm(buf,
234,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpminsw(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: XMMRegister) {
vinstr(buf,
234,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpminub_mem(buf: &mut Assembler, dst: XMMRegister, src1: XMMRegister, src2: Mem) {
vinstrm(buf,
218,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpminub(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: XMMRegister) {
vinstr(buf,
218,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpmullw_mem(buf: &mut Assembler, dst: XMMRegister, src1: XMMRegister, src2: Mem) {
vinstrm(buf,
213,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpmullw(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: XMMRegister) {
vinstr(buf,
213,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpmuludq_mem(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: Mem) {
vinstrm(buf,
244,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpmuludq(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: XMMRegister) {
vinstr(buf,
244,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpsllw_mem(buf: &mut Assembler, dst: XMMRegister, src1: XMMRegister, src2: Mem) {
vinstrm(buf,
241,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpsllw(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: XMMRegister) {
vinstr(buf,
241,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpslld_mem(buf: &mut Assembler, dst: XMMRegister, src1: XMMRegister, src2: Mem) {
vinstrm(buf,
242,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpslld(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: XMMRegister) {
vinstr(buf,
242,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpsraw_mem(buf: &mut Assembler, dst: XMMRegister, src1: XMMRegister, src2: Mem) {
vinstrm(buf,
225,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpsraw(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: XMMRegister) {
vinstr(buf,
225,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpsrad_mem(buf: &mut Assembler, dst: XMMRegister, src1: XMMRegister, src2: Mem) {
vinstrm(buf,
226,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpsrad(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: XMMRegister) {
vinstr(buf,
226,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpsrlw_mem(buf: &mut Assembler, dst: XMMRegister, src1: XMMRegister, src2: Mem) {
vinstrm(buf,
209,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpsrlw(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: XMMRegister) {
vinstr(buf,
209,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpsrld_mem(buf: &mut Assembler, dst: XMMRegister, src1: XMMRegister, src2: Mem) {
vinstrm(buf,
210,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpsrld(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: XMMRegister) {
vinstr(buf,
210,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpsubb_mem(buf: &mut Assembler, dst: XMMRegister, src1: XMMRegister, src2: Mem) {
vinstrm(buf,
248,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpsubb(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: XMMRegister) {
vinstr(buf,
248,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpsubw_mem(buf: &mut Assembler, dst: XMMRegister, src1: XMMRegister, src2: Mem) {
vinstrm(buf,
249,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpsubw(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: XMMRegister) {
vinstr(buf,
249,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpsubd_mem(buf: &mut Assembler, dst: XMMRegister, src1: XMMRegister, src2: Mem) {
vinstrm(buf,
250,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpsubd(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: XMMRegister) {
vinstr(buf,
250,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpsubsb_mem(buf: &mut Assembler, dst: XMMRegister, src1: XMMRegister, src2: Mem) {
vinstrm(buf,
232,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpsubsb(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: XMMRegister) {
vinstr(buf,
232,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpsubsw_mem(buf: &mut Assembler, dst: XMMRegister, src1: XMMRegister, src2: Mem) {
vinstrm(buf,
233,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpsubsw(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: XMMRegister) {
vinstr(buf,
233,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpsubusb_mem(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: Mem) {
vinstrm(buf,
216,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpsubusb(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: XMMRegister) {
vinstr(buf,
216,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpsubusw_mem(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: Mem) {
vinstrm(buf,
217,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpsubusw(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: XMMRegister) {
vinstr(buf,
217,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpand_mem(buf: &mut Assembler, dst: XMMRegister, src1: XMMRegister, src2: Mem) {
vinstrm(buf,
219,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpand(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: XMMRegister) {
vinstr(buf,
219,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpor_mem(buf: &mut Assembler, dst: XMMRegister, src1: XMMRegister, src2: Mem) {
vinstrm(buf,
235,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpor(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: XMMRegister) {
vinstr(buf,
235,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpxor_mem(buf: &mut Assembler, dst: XMMRegister, src1: XMMRegister, src2: Mem) {
vinstrm(buf,
239,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn vpxor(buf: &mut Assembler,
dst: XMMRegister,
src1: XMMRegister,
src2: XMMRegister) {
vinstr(buf,
239,
dst,
src1,
src2,
k0x66,
crate::avx::LeadingOpcode::k0F,
crate::avx::VexW::W0);
}
#[no_mangle]
pub extern "C" fn pabsb_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
ssse3_or_4_instr_mem(buf, dst, src, 102 as u8, 15, 56, 28);
}
#[no_mangle]
pub extern "C" fn pabsb(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
ssse3_or_4_instr(buf, dst, src, 102 as u8, 15, 56, 28);
}
#[no_mangle]
pub extern "C" fn pabsw_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
ssse3_or_4_instr_mem(buf, dst, src, 102 as u8, 15, 56, 29);
}
#[no_mangle]
pub extern "C" fn pabsw(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
ssse3_or_4_instr(buf, dst, src, 102 as u8, 15, 56, 29);
}
#[no_mangle]
pub extern "C" fn pabsd_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
ssse3_or_4_instr_mem(buf, dst, src, 102 as u8, 15, 56, 30);
}
#[no_mangle]
pub extern "C" fn pabsd(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
ssse3_or_4_instr(buf, dst, src, 102 as u8, 15, 56, 30);
}
#[no_mangle]
pub extern "C" fn phaddd_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
ssse3_or_4_instr_mem(buf, dst, src, 102 as u8, 15, 56, 2);
}
#[no_mangle]
pub extern "C" fn phaddd(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
ssse3_or_4_instr(buf, dst, src, 102 as u8, 15, 56, 2);
}
#[no_mangle]
pub extern "C" fn phaddw_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
ssse3_or_4_instr_mem(buf, dst, src, 102 as u8, 15, 56, 1);
}
#[no_mangle]
pub extern "C" fn phaddw(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
ssse3_or_4_instr(buf, dst, src, 102 as u8, 15, 56, 1);
}
#[no_mangle]
pub extern "C" fn pshufb_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
ssse3_or_4_instr_mem(buf, dst, src, 102 as u8, 15, 56, 0);
}
#[no_mangle]
pub extern "C" fn pshufb(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
ssse3_or_4_instr(buf, dst, src, 102 as u8, 15, 56, 0);
}
#[no_mangle]
pub extern "C" fn psignb_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
ssse3_or_4_instr_mem(buf, dst, src, 102 as u8, 15, 56, 8);
}
#[no_mangle]
pub extern "C" fn psignb(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
ssse3_or_4_instr(buf, dst, src, 102 as u8, 15, 56, 8);
}
#[no_mangle]
pub extern "C" fn psignw_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
ssse3_or_4_instr_mem(buf, dst, src, 102 as u8, 15, 56, 9);
}
#[no_mangle]
pub extern "C" fn psignw(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
ssse3_or_4_instr(buf, dst, src, 102 as u8, 15, 56, 9);
}
#[no_mangle]
pub extern "C" fn psignd_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
ssse3_or_4_instr_mem(buf, dst, src, 102 as u8, 15, 56, 10);
}
#[no_mangle]
pub extern "C" fn psignd(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
ssse3_or_4_instr(buf, dst, src, 102 as u8, 15, 56, 10);
}
pub extern "C" fn ptest_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
ssse3_or_4_instr_mem(buf, dst, src, 102 as u8, 15, 56, 23);
}
#[no_mangle]
pub extern "C" fn ptest(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
ssse3_or_4_instr(buf, dst, src, 102 as u8, 15, 56, 23);
}
#[no_mangle]
pub extern "C" fn pmovsxbw_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
ssse3_or_4_instr_mem(buf, dst, src, 102 as u8, 15, 56, 32);
}
#[no_mangle]
pub extern "C" fn pmovsxbw(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
ssse3_or_4_instr(buf, dst, src, 102 as u8, 15, 56, 32);
}
#[no_mangle]
pub extern "C" fn pmovsxwd_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
ssse3_or_4_instr_mem(buf, dst, src, 102 as u8, 15, 56, 35);
}
#[no_mangle]
pub extern "C" fn pmovsxwd(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
ssse3_or_4_instr(buf, dst, src, 102 as u8, 15, 56, 35);
}
#[no_mangle]
pub extern "C" fn packusdw_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
ssse3_or_4_instr_mem(buf, dst, src, 102 as u8, 15, 56, 43);
}
#[no_mangle]
pub extern "C" fn packusdw(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
ssse3_or_4_instr(buf, dst, src, 102 as u8, 15, 56, 43);
}
#[no_mangle]
pub extern "C" fn pmovzxbw_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
ssse3_or_4_instr_mem(buf, dst, src, 102 as u8, 15, 56, 48);
}
#[no_mangle]
pub extern "C" fn pmovzxbw(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
ssse3_or_4_instr(buf, dst, src, 102 as u8, 15, 56, 48);
}
#[no_mangle]
pub extern "C" fn pmovzxwd_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
ssse3_or_4_instr_mem(buf, dst, src, 102 as u8, 15, 56, 51);
}
#[no_mangle]
pub extern "C" fn pmovzxwd(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
ssse3_or_4_instr(buf, dst, src, 102 as u8, 15, 56, 51);
}
#[no_mangle]
pub extern "C" fn pminsb_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
ssse3_or_4_instr_mem(buf, dst, src, 102 as u8, 15, 56, 56);
}
#[no_mangle]
pub extern "C" fn pminsb(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
ssse3_or_4_instr(buf, dst, src, 102 as u8, 15, 56, 56);
}
#[no_mangle]
pub extern "C" fn pminsd_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
ssse3_or_4_instr_mem(buf, dst, src, 102 as u8, 15, 56, 57);
}
#[no_mangle]
pub extern "C" fn pminsd(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
ssse3_or_4_instr(buf, dst, src, 102 as u8, 15, 56, 57);
}
#[no_mangle]
pub extern "C" fn pminuw_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
ssse3_or_4_instr_mem(buf, dst, src, 102 as u8, 15, 56, 58);
}
#[no_mangle]
pub extern "C" fn pminuw(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
ssse3_or_4_instr(buf, dst, src, 102 as u8, 15, 56, 58);
}
#[no_mangle]
pub extern "C" fn pminud_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
ssse3_or_4_instr_mem(buf, dst, src, 102 as u8, 15, 56, 59);
}
#[no_mangle]
pub extern "C" fn pminud(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
ssse3_or_4_instr(buf, dst, src, 102 as u8, 15, 56, 59);
}
#[no_mangle]
pub extern "C" fn pmaxsb_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
ssse3_or_4_instr_mem(buf, dst, src, 102 as u8, 15, 56, 60);
}
#[no_mangle]
pub extern "C" fn pmaxsb(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
ssse3_or_4_instr(buf, dst, src, 102 as u8, 15, 56, 60);
}
#[no_mangle]
pub extern "C" fn pmaxsd_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
ssse3_or_4_instr_mem(buf, dst, src, 102 as u8, 15, 56, 61);
}
#[no_mangle]
pub extern "C" fn pmaxsd(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
ssse3_or_4_instr(buf, dst, src, 102 as u8, 15, 56, 61);
}
#[no_mangle]
pub extern "C" fn pmaxuw_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
ssse3_or_4_instr_mem(buf, dst, src, 102 as u8, 15, 56, 62);
}
#[no_mangle]
pub extern "C" fn pmaxuw(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
ssse3_or_4_instr(buf, dst, src, 102 as u8, 15, 56, 62);
}
#[no_mangle]
pub extern "C" fn pmaxud_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
ssse3_or_4_instr_mem(buf, dst, src, 102 as u8, 15, 56, 63);
}
#[no_mangle]
pub extern "C" fn pmaxud(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
ssse3_or_4_instr(buf, dst, src, 102 as u8, 15, 56, 63);
}
#[no_mangle]
pub extern "C" fn pmulld_mem(buf: &mut Assembler, dst: XMMRegister, src: Mem) {
ssse3_or_4_instr_mem(buf, dst, src, 102 as u8, 15, 56, 64);
}
#[no_mangle]
pub extern "C" fn pmulld(buf: &mut Assembler, dst: XMMRegister, src: XMMRegister) {
ssse3_or_4_instr(buf, dst, src, 102 as u8, 15, 56, 64);
}
|
use rustlearn::prelude::*;
use rustlearn::linear_models::sgdclassifier::Hyperparameters;
use rustlearn::datasets::iris;
fn main() {
let (x, y) = iris::load_data();
let mut model = Hyperparameters::new(4)
.learning_rate(1.0)
.l2_penalty(0.5)
.l1_penalty(0.0)
.one_vs_rest();
model.fit(&x, &y).unwrap();
let prediction = model.predict(&x).unwrap();
// println!("Model: {:?}", model);
println!("Prediction: {:?}", prediction);
} |
use std::ops::RangeFrom;
use quote::ToTokens;
use syn::parse_quote;
pub type Counter = RangeFrom<isize>;
pub fn repeat_tuple<I: ToTokens, T: syn::parse::Parse>(rep: fn() -> I, n: usize) -> T {
let values = (1..=n).map(|_| rep()).collect::<Vec<I>>();
parse_quote!((#(#values, )*))
}
|
#![allow(clippy::integer_arithmetic)]
use {
log::*,
serial_test::serial,
solana_core::validator::ValidatorConfig,
solana_gossip::{cluster_info::Node, contact_info::ContactInfo},
solana_local_cluster::{
cluster::Cluster,
local_cluster::{ClusterConfig, LocalCluster},
validator_configs::*,
},
solana_replica_lib::accountsdb_repl_server::AccountsDbReplServiceConfig,
solana_replica_node::{
replica_node::{ReplicaNode, ReplicaNodeConfig},
replica_util,
},
solana_rpc::{rpc::JsonRpcConfig, rpc_pubsub_service::PubSubConfig},
solana_runtime::{
accounts_index::AccountSecondaryIndexes,
snapshot_archive_info::SnapshotArchiveInfoGetter,
snapshot_config::SnapshotConfig,
snapshot_utils::{self, ArchiveFormat},
},
solana_sdk::{
client::SyncClient,
clock::Slot,
commitment_config::CommitmentConfig,
epoch_schedule::MINIMUM_SLOTS_PER_EPOCH,
exit::Exit,
hash::Hash,
signature::{Keypair, Signer},
},
solana_streamer::socket::SocketAddrSpace,
std::{
net::{IpAddr, Ipv4Addr, SocketAddr},
path::{Path, PathBuf},
sync::{Arc, RwLock},
thread::sleep,
time::Duration,
},
tempfile::TempDir,
};
const RUST_LOG_FILTER: &str =
"error,solana_core::replay_stage=warn,solana_local_cluster=info,local_cluster=info";
fn wait_for_next_snapshot(
cluster: &LocalCluster,
snapshot_archives_dir: &Path,
) -> (PathBuf, (Slot, Hash)) {
// Get slot after which this was generated
let client = cluster
.get_validator_client(&cluster.entry_point_info.id)
.unwrap();
let last_slot = client
.get_slot_with_commitment(CommitmentConfig::processed())
.expect("Couldn't get slot");
// Wait for a snapshot for a bank >= last_slot to be made so we know that the snapshot
// must include the transactions just pushed
trace!(
"Waiting for snapshot archive to be generated with slot > {}",
last_slot
);
loop {
if let Some(full_snapshot_archive_info) =
snapshot_utils::get_highest_full_snapshot_archive_info(snapshot_archives_dir)
{
trace!(
"full snapshot for slot {} exists",
full_snapshot_archive_info.slot()
);
if full_snapshot_archive_info.slot() >= last_slot {
return (
full_snapshot_archive_info.path().clone(),
(
full_snapshot_archive_info.slot(),
*full_snapshot_archive_info.hash(),
),
);
}
trace!(
"full snapshot slot {} < last_slot {}",
full_snapshot_archive_info.slot(),
last_slot
);
}
sleep(Duration::from_millis(1000));
}
}
fn farf_dir() -> PathBuf {
std::env::var("FARF_DIR")
.unwrap_or_else(|_| "farf".to_string())
.into()
}
fn generate_account_paths(num_account_paths: usize) -> (Vec<TempDir>, Vec<PathBuf>) {
let account_storage_dirs: Vec<TempDir> = (0..num_account_paths)
.map(|_| tempfile::tempdir_in(farf_dir()).unwrap())
.collect();
let account_storage_paths: Vec<_> = account_storage_dirs
.iter()
.map(|a| a.path().to_path_buf())
.collect();
(account_storage_dirs, account_storage_paths)
}
struct SnapshotValidatorConfig {
_snapshot_dir: TempDir,
snapshot_archives_dir: TempDir,
account_storage_dirs: Vec<TempDir>,
validator_config: ValidatorConfig,
}
fn setup_snapshot_validator_config(
snapshot_interval_slots: u64,
num_account_paths: usize,
) -> SnapshotValidatorConfig {
// Create the snapshot config
let bank_snapshots_dir = tempfile::tempdir_in(farf_dir()).unwrap();
let snapshot_archives_dir = tempfile::tempdir_in(farf_dir()).unwrap();
let snapshot_config = SnapshotConfig {
full_snapshot_archive_interval_slots: snapshot_interval_slots,
incremental_snapshot_archive_interval_slots: Slot::MAX,
snapshot_archives_dir: snapshot_archives_dir.path().to_path_buf(),
bank_snapshots_dir: bank_snapshots_dir.path().to_path_buf(),
archive_format: ArchiveFormat::TarBzip2,
snapshot_version: snapshot_utils::SnapshotVersion::default(),
maximum_full_snapshot_archives_to_retain:
snapshot_utils::DEFAULT_MAX_FULL_SNAPSHOT_ARCHIVES_TO_RETAIN,
maximum_incremental_snapshot_archives_to_retain:
snapshot_utils::DEFAULT_MAX_INCREMENTAL_SNAPSHOT_ARCHIVES_TO_RETAIN,
};
// Create the account paths
let (account_storage_dirs, account_storage_paths) = generate_account_paths(num_account_paths);
let bind_ip_addr = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1));
let accountsdb_repl_port =
solana_net_utils::find_available_port_in_range(bind_ip_addr, (1024, 65535)).unwrap();
let replica_server_addr = SocketAddr::new(bind_ip_addr, accountsdb_repl_port);
let accountsdb_repl_service_config = Some(AccountsDbReplServiceConfig {
worker_threads: 1,
replica_server_addr,
});
// Create the validator config
let validator_config = ValidatorConfig {
snapshot_config: Some(snapshot_config),
account_paths: account_storage_paths,
accounts_hash_interval_slots: snapshot_interval_slots,
accountsdb_repl_service_config,
..ValidatorConfig::default()
};
SnapshotValidatorConfig {
_snapshot_dir: bank_snapshots_dir,
snapshot_archives_dir,
account_storage_dirs,
validator_config,
}
}
fn test_local_cluster_start_and_exit_with_config(socket_addr_space: SocketAddrSpace) {
solana_logger::setup();
const NUM_NODES: usize = 1;
let mut config = ClusterConfig {
validator_configs: make_identical_validator_configs(&ValidatorConfig::default(), NUM_NODES),
node_stakes: vec![3; NUM_NODES],
cluster_lamports: 100,
ticks_per_slot: 8,
slots_per_epoch: MINIMUM_SLOTS_PER_EPOCH as u64,
stakers_slot_offset: MINIMUM_SLOTS_PER_EPOCH as u64,
..ClusterConfig::default()
};
let cluster = LocalCluster::new(&mut config, socket_addr_space);
assert_eq!(cluster.validators.len(), NUM_NODES);
}
#[test]
#[serial]
fn test_replica_bootstrap() {
let socket_addr_space = SocketAddrSpace::new(true);
test_local_cluster_start_and_exit_with_config(socket_addr_space);
solana_logger::setup_with_default(RUST_LOG_FILTER);
// First set up the cluster with 1 node
let snapshot_interval_slots = 50;
let num_account_paths = 3;
let leader_snapshot_test_config =
setup_snapshot_validator_config(snapshot_interval_slots, num_account_paths);
info!(
"Snapshot config for the leader: accounts: {:?}, snapshot: {:?}",
leader_snapshot_test_config.account_storage_dirs,
leader_snapshot_test_config.snapshot_archives_dir
);
let stake = 10_000;
let mut config = ClusterConfig {
node_stakes: vec![stake],
cluster_lamports: 1_000_000,
validator_configs: make_identical_validator_configs(
&leader_snapshot_test_config.validator_config,
1,
),
..ClusterConfig::default()
};
let cluster = LocalCluster::new(&mut config, socket_addr_space);
assert_eq!(cluster.validators.len(), 1);
let contact_info = &cluster.entry_point_info;
info!("Contact info: {:?}", contact_info);
// Get slot after which this was generated
let snapshot_archives_dir = &leader_snapshot_test_config
.validator_config
.snapshot_config
.as_ref()
.unwrap()
.snapshot_archives_dir;
info!("Waiting for snapshot");
let (archive_filename, archive_snapshot_hash) =
wait_for_next_snapshot(&cluster, snapshot_archives_dir);
info!("found: {:?}", archive_filename);
let identity_keypair = Keypair::new();
// now bring up a replica to talk to it.
let ip_addr = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1));
let port = solana_net_utils::find_available_port_in_range(ip_addr, (8101, 8200)).unwrap();
let rpc_addr = SocketAddr::new(ip_addr, port);
let port = solana_net_utils::find_available_port_in_range(ip_addr, (8201, 8300)).unwrap();
let rpc_pubsub_addr = SocketAddr::new(ip_addr, port);
let ledger_dir = tempfile::tempdir_in(farf_dir()).unwrap();
let ledger_path = ledger_dir.path();
let snapshot_output_dir = tempfile::tempdir_in(farf_dir()).unwrap();
let snapshot_archives_dir = snapshot_output_dir.path();
let bank_snapshots_dir = snapshot_archives_dir.join("snapshot");
let account_paths: Vec<PathBuf> = vec![ledger_path.join("accounts")];
let port = solana_net_utils::find_available_port_in_range(ip_addr, (8301, 8400)).unwrap();
let gossip_addr = SocketAddr::new(ip_addr, port);
let dynamic_port_range = solana_net_utils::parse_port_range("8401-8500").unwrap();
let bind_address = solana_net_utils::parse_host("127.0.0.1").unwrap();
let node = Node::new_with_external_ip(
&identity_keypair.pubkey(),
&gossip_addr,
dynamic_port_range,
bind_address,
);
info!("The peer id: {:?}", &contact_info.id);
let entry_points = vec![ContactInfo::new_gossip_entry_point(&contact_info.gossip)];
let (cluster_info, _rpc_contact_info, _snapshot_info) = replica_util::get_rpc_peer_info(
identity_keypair,
&entry_points,
ledger_path,
&node,
None,
&contact_info.id,
snapshot_archives_dir,
socket_addr_space,
);
info!("The cluster info:\n{:?}", cluster_info.contact_info_trace());
let config = ReplicaNodeConfig {
rpc_peer_addr: contact_info.rpc,
accountsdb_repl_peer_addr: Some(
leader_snapshot_test_config
.validator_config
.accountsdb_repl_service_config
.unwrap()
.replica_server_addr,
),
rpc_addr,
rpc_pubsub_addr,
ledger_path: ledger_path.to_path_buf(),
snapshot_archives_dir: snapshot_archives_dir.to_path_buf(),
bank_snapshots_dir,
account_paths,
snapshot_info: archive_snapshot_hash,
cluster_info,
rpc_config: JsonRpcConfig::default(),
snapshot_config: None,
pubsub_config: PubSubConfig::default(),
socket_addr_space,
account_indexes: AccountSecondaryIndexes::default(),
accounts_db_caching_enabled: false,
replica_exit: Arc::new(RwLock::new(Exit::default())),
};
let _replica_node = ReplicaNode::new(config);
}
|
#[macro_use]
mod util;
pub mod app;
mod atom;
mod connecter;
mod constant;
mod molecule;
mod organism;
mod page;
mod template;
pub use app::App;
|
use wasm_bindgen::prelude::*;
use yew::prelude::*;
#[wasm_bindgen(start)]
pub fn run_app() {
App::<Model>::new().mount_to_body();
}
struct Model {
link: ComponentLink<Self>,
value: Vec<i32>,
}
enum Msg {
Modify(fn(&mut Model)),
}
impl Component for Model {
type Message = Msg;
type Properties = ();
fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self {
Self {
link,
value: vec![],
}
}
fn update(&mut self, msg: Self::Message) -> ShouldRender {
match msg {
Msg::Modify(f) => f(self),
}
true
}
fn change(&mut self, _props: Self::Properties) -> ShouldRender {
false
}
fn view(&self) -> Html {
let list = self
.value
.iter()
.map(|item: &i32| -> Html {
html! {
<li> {item} </li>
}
})
.collect::<Html>();
html! {
<div>
<button onclick=self.link.callback(|_| Msg::Modify(|model| model.value.push(model.value.len() as i32)))>{ "click me" }</button>
<ul>
{ list }
</ul>
</div>
}
}
}
|
use nix::unistd::{setuid, Uid};
use pwd::Passwd;
fn main() {
setuid(Uid::from_raw(
Passwd::from_name("root").unwrap().unwrap().uid,
))
.expect("Failed to set uid");
println!("{}", std::fs::read_to_string("/root/flag").unwrap());
}
|
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt, ByteOrder};
use {sodium, Error};
use rustc_serialize::hex::ToHex;
use std;
use std::io::{Write};
use openssl::crypto::hash;
use key::{PublicKey, SecretKey, Key};
use algorithm::*;
use encoding::{ReadValue, WriteValue, read_length};
// https://tools.ietf.org/html/rfc4880#section-5.2.1
// sed -e "s/ *\(.*\) = \(.*\),/\2 => Some(Type::\1),/"
#[derive(Debug)]
pub enum Type {
Binary = 0x00,
CanonicalText = 0x01,
Standalone = 0x02,
GenericCert = 0x10,
PersonaCert = 0x11,
CasualCert = 0x12,
PositiveCert = 0x13,
SubkeyBinding = 0x18,
PrimaryKeyBinding = 0x19,
DirectlyOnAKey = 0x1F,
KeyRevocation = 0x20,
SubkeyRevocation = 0x28,
CertificationRevocation = 0x30,
Timestamp = 0x40,
ThirdPartyConfirmation = 0x50,
}
impl Type {
pub fn from_byte(b: u8) -> Result<Self, Error> {
match b {
0x00 => Ok(Type::Binary),
0x01 => Ok(Type::CanonicalText),
0x02 => Ok(Type::Standalone),
0x10 => Ok(Type::GenericCert),
0x11 => Ok(Type::PersonaCert),
0x12 => Ok(Type::CasualCert),
0x13 => Ok(Type::PositiveCert),
0x18 => Ok(Type::SubkeyBinding),
0x19 => Ok(Type::PrimaryKeyBinding),
0x1F => Ok(Type::DirectlyOnAKey),
0x20 => Ok(Type::KeyRevocation),
0x28 => Ok(Type::SubkeyRevocation),
0x30 => Ok(Type::CertificationRevocation),
0x40 => Ok(Type::Timestamp),
0x50 => Ok(Type::ThirdPartyConfirmation),
t => Err(Error::UnknownSignatureType(t)),
}
}
}
fn sha256_version4(data: &[u8], hashed_sig_data: &[u8]) -> sodium::sha256::Digest {
let mut v: Vec<u8> = Vec::new();
v.extend(data);
v.extend(hashed_sig_data);
// https://tools.ietf.org/html/rfc4880#section-5.2.4
v.push(4);
v.push(0xff);
v.write_u32::<BigEndian>(hashed_sig_data.len() as u32).unwrap();
debug!("hashed value: {:?}", v);
sodium::sha256::hash(&v)
}
impl Verify for PublicKey {
fn verify_signature(&self, hash_algorithm:HashAlgorithm, hash:&[u8], signature:&[u8]) -> Result<bool, Error> {
use key::PublicKey::*;
match *self {
Ed25519(ref pk) => {
Ok(sodium::ed25519::verify_detached(&signature, hash, sodium::ed25519::PublicKey(pk)))
},
RSAEncryptSign(ref pk) => {
let t = match hash_algorithm {
HashAlgorithm::SHA256 => hash::Type::SHA256,
_ => unimplemented!()
};
Ok(try!(pk.verify(t, hash, &signature)))
}
}
}
}
impl Verify for SecretKey {
fn verify_signature(&self, hash_algorithm:HashAlgorithm, hash:&[u8], signature:&[u8]) -> Result<bool, Error> {
use key::SecretKey::*;
match *self {
Ed25519 { ref pk, .. } => {
Ok(sodium::ed25519::verify_detached(&signature, hash, sodium::ed25519::PublicKey(pk)))
},
RSAEncryptSign(ref sk) => {
let t = match hash_algorithm {
HashAlgorithm::SHA256 => hash::Type::SHA256,
_ => unimplemented!()
};
Ok(try!(sk.verify(t, hash, &signature)))
}
}
}
}
impl Verify for Key {
fn verify_signature(&self, hash_algorithm:HashAlgorithm, hash:&[u8], signature:&[u8]) -> Result<bool, Error> {
match *self {
Key::Secret(ref k) => k.verify_signature(hash_algorithm, hash, signature),
Key::Public(ref k) => k.verify_signature(hash_algorithm, hash, signature)
}
}
}
#[doc(hidden)]
pub trait Verify {
fn verify_signature(&self, hash_algorithm:HashAlgorithm, hash:&[u8], sig:&[u8]) -> Result<bool, Error>;
}
#[doc(hidden)]
pub fn read<P:super::PGP>(p:&mut P,
mut body: &[u8])
-> Result<(), Error> {
let initial_body = body;
debug!("initial_body.len(): {:?}", initial_body.len());
let version = try!(body.read_u8());
let mut issuer = [0;8];
debug!("signature version: {:?}", version);
let (hash_algo, digest) = if version == 3 {
if try!(body.read_u8()) != 5 {
return Err(Error::InvalidSignature)
}
let initial_body = body;
let sigtype = try!(Type::from_byte(try!(body.read_u8())));
let creation_time = try!(body.read_u32::<BigEndian>());
try!(p.signature_subpacket(Subpacket::SignatureCreationTime(creation_time)));
let (key_id, mut body) = body.split_at(8);
issuer.clone_from_slice(key_id);
let pk_algo = try!(PublicKeyAlgorithm::from_byte(try!(body.read_u8())));
let hash_algo = try!(HashAlgorithm::from_byte(try!(body.read_u8())));
match pk_algo {
PublicKeyAlgorithm::Ed25519 => {},
PublicKeyAlgorithm::RSAEncryptSign => {},
t => return Err(Error::UnsupportedPublicKey(t))
}
match hash_algo {
HashAlgorithm::SHA256 => {},
t => return Err(Error::UnsupportedHash(t))
}
let left_0 = try!(body.read_u8());
let left_1 = try!(body.read_u8());
let mut v: Vec<u8> = Vec::new();
{
let data = p.get_signed_data(sigtype);
v.extend(data);
}
v.extend(&initial_body[0..5]);
let digest = sodium::sha256::hash(&v);
if digest[0] != left_0 || digest[1] != left_1 {
return p.signature_verified(false)
}
(hash_algo, digest)
} else if version == 4 {
let sigtype = try!(Type::from_byte(try!(body.read_u8())));
let pk_algo = try!(PublicKeyAlgorithm::from_byte(try!(body.read_u8())));
let hash_algo = try!(HashAlgorithm::from_byte(try!(body.read_u8())));
match pk_algo {
PublicKeyAlgorithm::Ed25519 => {},
PublicKeyAlgorithm::RSAEncryptSign => {},
t => return Err(Error::UnsupportedPublicKey(t))
}
match hash_algo {
HashAlgorithm::SHA256 => {},
t => return Err(Error::UnsupportedHash(t))
}
debug!("{:?} {:?} {:?}", sigtype, pk_algo, hash_algo);
let mut hashed_subpacket = try!(body.read_string());
let initial_len = initial_body.len() - body.len();
debug!("initial_len: {:?}", initial_len);
let mut unhashed_subpacket = try!(body.read_string());
while hashed_subpacket.len() > 0 {
let sub = try!(Subpacket::read(&mut hashed_subpacket));
match sub {
Subpacket::Issuer(ref i) => issuer.clone_from_slice(i),
_ => {}
}
try!(p.signature_subpacket(sub))
}
while unhashed_subpacket.len() > 0 {
let sub = try!(Subpacket::read(&mut unhashed_subpacket));
match sub {
Subpacket::Issuer(ref i) => issuer.clone_from_slice(i),
_ => {}
}
try!(p.signature_subpacket(sub))
}
let left_0 = try!(body.read_u8());
let left_1 = try!(body.read_u8());
let digest = {
let data = p.get_signed_data(sigtype);
debug!("{:?} {:?}", &initial_body[0..initial_len], data);
sha256_version4(data, &initial_body[0..initial_len])
};
if digest[0] != left_0 || digest[1] != left_1 {
debug!("digest {:?}, {:?} {:?}", digest, left_0, left_1);
return p.signature_verified(false)
}
(hash_algo, digest)
} else {
return Err(Error::UnknownSignatureVersion(version))
};
// Read sig
let mut signature = Vec::new();
while body.len() > 0 {
if body.len() < 2 {
debug!("{:?}", body);
}
let next_mpi = try!(body.read_mpi());
debug!("{:?}", next_mpi.to_hex());
signature.extend(next_mpi);
}
let signature_ok = if let Some(ref key) = p.get_public_signing_key(&issuer) {
try!(key.verify_signature(hash_algo, &digest, &signature))
} else {
return Err(Error::NoPublicKey)
};
p.signature_verified(signature_ok)
}
const VERSION: u8 = 4;
macro_rules! write_subpackets (
($buffer:expr, $sub:expr) => { {
let n0 = $buffer.len();
$buffer.extend(b"\0\0");
$sub;
let n1 = $buffer.len();
BigEndian::write_u16(&mut $buffer[ n0 ..], (n1-n0-2) as u16);
} }
);
impl SecretKey {
pub fn sign(&self,
buffer: &mut Vec<u8>,
data: &[u8],
signature_type: Type,
hashed_subpackets: &[Subpacket],
unhashed_subpackets: &[Subpacket])
-> Result<(), Error> {
let i0 = buffer.len();
try!(buffer.write_u8(VERSION));
try!(buffer.write_u8(signature_type as u8));
try!(buffer.write_u8(PublicKeyAlgorithm::Ed25519 as u8));
try!(buffer.write_u8(HashAlgorithm::SHA256 as u8));
// Subpackets
write_subpackets!(buffer, {
// Write all hashed subpackets.
for p in hashed_subpackets {
try!(p.write(buffer))
}
});
let i1 = buffer.len();
// Write unhashed subpackets.
write_subpackets!(buffer, {
for p in unhashed_subpackets {
try!(p.write(buffer))
}
});
let digest = sha256_version4(data, &buffer[i0 .. i1]);
// Leftmost 16 bits.
try!(buffer.write_u8(digest[0]));
try!(buffer.write_u8(digest[1]));
match *self {
SecretKey::RSAEncryptSign(ref sk) => {
let sig = try!(sk.sign(hash::Type::SHA256, &digest));
debug!("writing RSA signature {:?}", sig);
try!(buffer.write_mpi(sig.len() << 3, &sig));
Ok(())
},
SecretKey::Ed25519 { ref sk,.. } => {
let mut sig = [0; sodium::ed25519::SIGNATUREBYTES];
sodium::ed25519::sign_detached(&mut sig, &digest, sodium::ed25519::SecretKey(sk));
try!(buffer.write_mpi(sig.len() << 3, &sig));
Ok(())
}
}
}
}
bitflags! {
pub flags KeyFlags: u8 {
const MAY_CERTIFY_KEYS = 0x1,
const MAY_SIGN_DATA = 0x2,
const MAY_ENCRYPT_COMMUNICATIONS = 0x4,
const MAY_ENCRYPT_STORAGE = 0x8,
const PRIV_MAY_HAVE_BEEN_SPLIT = 0x10,
const MAY_AUTH = 0x20,
const MORE_THAN_ONE_OWNER = 0x80,
}
}
bitflags! {
pub flags KeyServerFlags: u8 {
const NO_MODIFY = 0x80,
}
}
bitflags! {
pub flags Features: u8 {
const MODIFICATION_DETECTION = 0x1,
}
}
bitflags! {
pub flags Class: u8 {
const SENSITIVE = 0xC0,
}
}
bitflags! {
pub flags NotationFlags: u32 {
const HUMAN_READABLE = 0x80000000,
}
}
#[derive(Debug, Clone, Copy)]
pub enum RevocationCode {
NoReason = 0,
Superseeded = 1,
Compromised = 2,
Retired = 3,
InvalidUserID = 32,
}
impl RevocationCode {
fn from_byte(x:u8) -> Result<RevocationCode, Error> {
match x {
0 => Ok(RevocationCode::NoReason),
1 => Ok(RevocationCode::Superseeded),
2 => Ok(RevocationCode::Compromised),
3 => Ok(RevocationCode::Retired),
32 => Ok(RevocationCode::InvalidUserID),
_ => Err(Error::UnknownRevocationCode(x))
}
}
}
#[derive(Debug, Clone, Copy)]
pub enum Subpacket<'a> {
SignatureCreationTime(u32),
SignatureExpirationTime(u32),
ExportableCertification(bool),
TrustSignature { level: u8 },
RegularExpression(&'a [u8]),
Revocable(bool),
KeyExpirationTime(u32),
PreferredSymmetricAlgorithm(&'a [SymmetricKeyAlgorithm]),
RevocationKey { class:Class, pk_algo:PublicKeyAlgorithm, fingerprint: &'a[u8] },
Issuer([u8;8]),
NotationData { flags: NotationFlags, name:&'a str, value: &'a[u8] },
PreferredHashAlgorithm(&'a[HashAlgorithm]),
PreferredCompressionAlgorithm(&'a[CompressionAlgorithm]),
KeyServerPreferences(KeyServerFlags),
PreferredKeyServer(&'a str),
PrimaryUserID(bool),
PolicyURI(&'a str),
KeyFlags(KeyFlags),
SignersUserID(&'a [u8]),
ReasonForRevocation { code: RevocationCode, reason:&'a str },
Features(Features),
SignatureTarget { pk_algo: PublicKeyAlgorithm, hash_algo:HashAlgorithm, hash: &'a[u8] },
EmbeddedSignature(&'a[u8]),
}
impl<'a> Subpacket<'a> {
fn read(packet: &mut &'a [u8]) -> Result<Subpacket<'a>, Error> {
let p0 = try!(packet.read_u8()) as usize;
let len = try!(read_length(p0, packet));
if len <= packet.len() {
let (mut a, b) = packet.split_at(len);
*packet = b;
match try!(a.read_u8()) {
2 => Ok(Subpacket::SignatureCreationTime(try!(a.read_u32::<BigEndian>()))),
3 => Ok(Subpacket::SignatureExpirationTime(try!(a.read_u32::<BigEndian>()))),
4 => Ok(Subpacket::ExportableCertification(try!(a.read_u8()) == 1)),
5 => Ok(Subpacket::TrustSignature { level: try!(a.read_u8()) }),
6 => Ok(Subpacket::RegularExpression(a)),
7 => Ok(Subpacket::Revocable(try!(a.read_u8()) == 1)),
9 => Ok(Subpacket::KeyExpirationTime(try!(a.read_u32::<BigEndian>()))),
11 => Ok(Subpacket::PreferredSymmetricAlgorithm(SymmetricKeyAlgorithm::from_slice(a))),
12 => {
let class = try!(a.read_u8());
let algo = try!(PublicKeyAlgorithm::from_byte(try!(a.read_u8())));
Ok(Subpacket::RevocationKey {
class: Class::from_bits_truncate(class),
pk_algo: algo,
fingerprint: a
})
},
16 => {
let mut issuer = [0;8];
issuer.clone_from_slice(a);
Ok(Subpacket::Issuer(issuer))
},
20 => {
let flags = NotationFlags::from_bits_truncate(try!(a.read_u32::<BigEndian>()));
let name_len = try!(a.read_u16::<BigEndian>());
let value_len = try!(a.read_u16::<BigEndian>());
let (name, value) = a.split_at(name_len as usize);
assert_eq!(value.len(), value_len as usize);
Ok(Subpacket::NotationData {
flags: flags,
name: try!(std::str::from_utf8(name)),
value: value
})
},
21 => Ok(Subpacket::PreferredHashAlgorithm(HashAlgorithm::from_slice(a))),
22 => Ok(Subpacket::PreferredCompressionAlgorithm(CompressionAlgorithm::from_slice(a))),
23 => Ok(Subpacket::KeyServerPreferences(KeyServerFlags::from_bits_truncate(try!(a.read_u8())))),
24 => Ok(Subpacket::PreferredKeyServer(try!(std::str::from_utf8(a)))),
25 => Ok(Subpacket::PrimaryUserID(try!(a.read_u8()) == 1)),
26 => Ok(Subpacket::PolicyURI(try!(std::str::from_utf8(a)))),
27 => Ok(Subpacket::KeyFlags(KeyFlags::from_bits_truncate(try!(a.read_u8())))),
28 => Ok(Subpacket::SignersUserID(a)),
29 => {
let code = try!(RevocationCode::from_byte(try!(a.read_u8())));
let reason = try!(std::str::from_utf8(a));
Ok(Subpacket::ReasonForRevocation {
code: code,
reason: reason
})
},
30 => Ok(Subpacket::Features(Features::from_bits_truncate(try!(a.read_u8())))),
31 => {
let algo = try!(PublicKeyAlgorithm::from_byte(try!(a.read_u8())));
let hash = try!(HashAlgorithm::from_byte(try!(a.read_u8())));
Ok(Subpacket::SignatureTarget {
pk_algo: algo,
hash_algo: hash,
hash: a
})
},
32 => Ok(Subpacket::EmbeddedSignature(a)),
t => {
Err(Error::UnknownSubpacketType(t))
}
}
} else {
Err(Error::IndexOutOfBounds)
}
}
fn write<W:Write>(&self, w:&mut W) -> Result<(), Error> {
match *self {
Subpacket::SignatureCreationTime(time) => try!(write_u32(w, 2, time)),
Subpacket::SignatureExpirationTime(time) => try!(write_u32(w, 3, time)),
Subpacket::ExportableCertification(b) => try!(write_bool(w, 4, b)),
Subpacket::TrustSignature { level } => try!(write_u8(w, 5, level)),
Subpacket::RegularExpression(b) => try!(write_bytes(w, 6, b)),
Subpacket::Revocable(b) => try!(write_bool(w, 7, b)),
Subpacket::KeyExpirationTime(time) => try!(write_u32(w, 9, time)),
Subpacket::PreferredSymmetricAlgorithm(p) => try!(write_bytes(w, 11, to_slice(p))),
Subpacket::RevocationKey { class, pk_algo, ref fingerprint } => {
try!(write_len(w, 23));
try!(w.write_u8(12));
try!(w.write_u8(class.bits()));
try!(w.write_u8(pk_algo as u8));
try!(w.write(fingerprint));
},
Subpacket::Issuer(ref b) => try!(write_bytes(w, 16, b.as_ref())),
Subpacket::NotationData{ flags, name, value } => {
try!(write_len(w, 9 + name.len() + value.len()));
try!(w.write_u8(20));
try!(w.write_u32::<BigEndian>(flags.bits()));
try!(w.write_u16::<BigEndian>(name.len() as u16));
try!(w.write_u16::<BigEndian>(value.len() as u16));
try!(w.write(name.as_ref()));
try!(w.write(value));
},
Subpacket::PreferredHashAlgorithm(p) => try!(write_bytes(w, 21, to_slice(p))),
Subpacket::PreferredCompressionAlgorithm(p) => try!(write_bytes(w, 22, to_slice(p))),
Subpacket::KeyServerPreferences(flags) => try!(write_u8(w, 23, flags.bits())),
Subpacket::PreferredKeyServer(b) => try!(write_bytes(w, 24, b.as_ref())),
Subpacket::PrimaryUserID(b) => try!(write_bool(w, 25, b)),
Subpacket::PolicyURI(b) => try!(write_bytes(w, 26, b.as_ref())),
Subpacket::KeyFlags(flags) => try!(write_u8(w, 27, flags.bits())),
Subpacket::SignersUserID(b) => try!(write_bytes(w, 28, b)),
Subpacket::ReasonForRevocation { code, reason } => {
try!(write_len(w, 2 + reason.len()));
try!(w.write_u8(29));
try!(w.write_u8(code as u8));
try!(w.write(reason.as_ref()));
},
Subpacket::Features(flags) => try!(write_u8(w, 30, flags.bits())),
Subpacket::SignatureTarget{ pk_algo, hash_algo, ref hash } => {
try!(write_len(w, 3 + hash.len()));
try!(w.write_u8(31));
try!(w.write_u8(pk_algo as u8));
try!(w.write_u8(hash_algo as u8));
try!(w.write(hash));
},
Subpacket::EmbeddedSignature(b) => try!(write_bytes(w, 32, b)),
}
Ok(())
}
}
/// The `len` argument must include the packet type.
fn write_len<W:Write>(w:&mut W, len:usize) -> Result<(), Error> {
if len < 192 {
try!(w.write_u8(len as u8));
} else if len <= 8383 {
let p0 = ((len - 192) >> 8) + 192;
let p1 = (len - 192) & 0xff;
try!(w.write_u8(p0 as u8));
try!(w.write_u8(p1 as u8));
} else {
try!(w.write_u8(0xff));
try!(w.write_u32::<BigEndian>(len as u32));
}
Ok(())
}
fn write_u32<W:Write>(w:&mut W, typ: u8, x: u32) -> Result<(), Error> {
try!(write_len(w, 5));
try!(w.write_u8(typ));
try!(w.write_u32::<BigEndian>(x));
Ok(())
}
fn write_bool<W:Write>(w:&mut W, typ: u8, x: bool) -> Result<(), Error> {
try!(write_len(w, 2));
try!(w.write_u8(typ));
try!(w.write_u8(if x { 1 } else { 0 }));
Ok(())
}
fn write_bytes<W:Write>(w:&mut W, typ: u8, x: &[u8]) -> Result<(), Error> {
try!(write_len(w, 1+x.len()));
try!(w.write_u8(typ));
try!(w.write(x));
Ok(())
}
fn write_u8<W:Write>(w:&mut W, typ: u8, x: u8) -> Result<(), Error> {
try!(write_len(w, 2));
try!(w.write_u8(typ));
try!(w.write_u8(x));
Ok(())
}
|
pub struct Solution {}
/// LeetCode Monthly Challenge problem for February 20th, 2021
impl Solution {
/// Converts the roman numeral to an integer.
///
/// # Arguments
///
/// * 's' - A string consisting of the roman numerals I, V, X, L, C, D, and/or M
///
/// # Examples
///
/// ```
/// # use crate::roman_to_integer::Solution;
/// let three = String::from("III");
/// let four = String::from("IV");
/// let nine = String::from("IX");
/// let fifty_eight = String::from("LVIII");
/// let nineteen_ninety_four = String::from("MCMXCIV");
///
/// assert_eq!(Solution::roman_to_int(three), 3);
/// assert_eq!(Solution::roman_to_int(four), 4);
/// assert_eq!(Solution::roman_to_int(nine), 9);
/// assert_eq!(Solution::roman_to_int(fifty_eight), 58);
/// assert_eq!(Solution::roman_to_int(nineteen_ninety_four), 1994);
/// ```
///
/// # Constraints
/// * 1 <= s.len() <= 15
/// * It is guaranteed that s is a valid roman numeral in the range [1, 3999]
///
pub fn roman_to_int(s: String) -> i32 {
let mut res: Vec<i32> = Vec::new();
for c in s.chars() {
let mut val: i32 = match c {
'I' => 1,
'V' => 5,
'X' => 10,
'L' => 50,
'C' => 100,
'D' => 500,
'M' => 1000,
_ => continue,
};
match res.last() {
Some(x) => {
if x < &val {
val -= res.pop().unwrap();
res.push(val);
} else {
res.push(val);
}
},
None => res.push(val),
};
}
res.iter().sum()
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_roman_to_int() {
assert_eq!(
Solution::roman_to_int(String::from("III")),
3,
);
assert_eq!(
Solution::roman_to_int(String::from("IV")),
4,
);
assert_eq!(
Solution::roman_to_int(String::from("IX")),
9,
);
assert_eq!(
Solution::roman_to_int(String::from("LVIII")),
58,
);
assert_eq!(
Solution::roman_to_int(String::from("MCMXCIV")),
1994,
);
}
}
|
//! Day 4
//!
//! Identifiying room numbers
extern crate onig;
use std::collections::HashMap;
use self::onig::*;
/// Room id, with checksum.
#[derive(Debug)]
pub struct Room<'a> {
pub name: &'a str,
pub sector: u32,
pub checksum: &'a str,
}
impl<'a> From<&'a str> for Room<'a> {
/// Parse a room from a string.
fn from(s: &'a str) -> Room<'a> {
let pattern = Regex::new("([a-z\\-]+)-([0-9]+)\\[([a-z]+)\\]").unwrap();
let captures = pattern.captures(s).expect("invalid room format");
Room {
name: captures.at(1).unwrap(),
sector: captures.at(2).unwrap().parse::<u32>().unwrap(),
checksum: captures.at(3).unwrap(),
}
}
}
impl<'a> Room<'a> {
/// Test if a room's checksum is valid.
pub fn is_valid(&self) -> bool {
let mut char_counts = self.name
.replace("-", "")
.chars()
.fold(HashMap::new(), |mut counts, c| {
{
let counter = counts.entry(c).or_insert(0);
*counter += 1;
}
counts
})
.into_iter()
.collect::<Vec<_>>();
char_counts.sort_by(|a, b| {
use std::cmp::Ordering;
let ordering = b.1.cmp(&a.1);
match ordering {
Ordering::Equal => a.0.cmp(&b.0),
other => other,
}
});
let checksum = char_counts.iter().map(|count| count.0).take(5).collect::<String>();
self.checksum == checksum
}
fn decrypt_char(c: char, shift: u32) -> char {
if c == '-' {
return ' ';
}
let shift = (shift % 26) as u8;
('a' as u8 + (((c as u8 - 'a' as u8) + shift) % 26)) as char
}
/// Decrypt name
pub fn decrypt_name(&self) -> String {
self.name.chars().map(|c| Self::decrypt_char(c, self.sector)).collect()
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn parse_room_string() {
{
let r = Room::from("aaaaa-bbb-z-y-x-123[abxyz]");
assert_eq!("aaaaa-bbb-z-y-x", r.name);
assert_eq!(123, r.sector);
assert_eq!("abxyz", r.checksum);
}
{
let r = Room::from("a-b-c-d-e-f-g-h-987[abcde]");
assert_eq!("a-b-c-d-e-f-g-h", r.name);
assert_eq!(987, r.sector);
assert_eq!("abcde", r.checksum);
}
}
#[test]
fn is_valid() {
assert!(Room::from("aaaaa-bbb-z-y-x-123[abxyz]").is_valid());
assert!(Room::from("a-b-c-d-e-f-g-h-987[abcde]").is_valid());
assert!(Room::from("not-a-real-room-404[oarel]").is_valid());
}
#[test]
fn invalid_checksums() {
assert!(!Room::from("totally-real-room-200[decoy]").is_valid());
}
#[test]
fn test_decrypt_name() {
assert_eq!("very encrypted name",
Room::from("qzmt-zixmtkozy-ivhz-343[abcdef]").decrypt_name());
}
}
|
#[doc = "Reader of register DDRCTRL_PCFGQOS0_1"]
pub type R = crate::R<u32, super::DDRCTRL_PCFGQOS0_1>;
#[doc = "Writer for register DDRCTRL_PCFGQOS0_1"]
pub type W = crate::W<u32, super::DDRCTRL_PCFGQOS0_1>;
#[doc = "Register DDRCTRL_PCFGQOS0_1 `reset()`'s with value 0x0200_0e00"]
impl crate::ResetValue for super::DDRCTRL_PCFGQOS0_1 {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0x0200_0e00
}
}
#[doc = "Reader of field `RQOS_MAP_LEVEL1`"]
pub type RQOS_MAP_LEVEL1_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `RQOS_MAP_LEVEL1`"]
pub struct RQOS_MAP_LEVEL1_W<'a> {
w: &'a mut W,
}
impl<'a> RQOS_MAP_LEVEL1_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !0x0f) | ((value as u32) & 0x0f);
self.w
}
}
#[doc = "Reader of field `RQOS_MAP_LEVEL2`"]
pub type RQOS_MAP_LEVEL2_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `RQOS_MAP_LEVEL2`"]
pub struct RQOS_MAP_LEVEL2_W<'a> {
w: &'a mut W,
}
impl<'a> RQOS_MAP_LEVEL2_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x0f << 8)) | (((value as u32) & 0x0f) << 8);
self.w
}
}
#[doc = "RQOS_MAP_REGION0\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum RQOS_MAP_REGION0_A {
#[doc = "0: LPR and 1: VPR only."]
B_0X0 = 0,
}
impl From<RQOS_MAP_REGION0_A> for u8 {
#[inline(always)]
fn from(variant: RQOS_MAP_REGION0_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `RQOS_MAP_REGION0`"]
pub type RQOS_MAP_REGION0_R = crate::R<u8, RQOS_MAP_REGION0_A>;
impl RQOS_MAP_REGION0_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<u8, RQOS_MAP_REGION0_A> {
use crate::Variant::*;
match self.bits {
0 => Val(RQOS_MAP_REGION0_A::B_0X0),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `B_0X0`"]
#[inline(always)]
pub fn is_b_0x0(&self) -> bool {
*self == RQOS_MAP_REGION0_A::B_0X0
}
}
#[doc = "Write proxy for field `RQOS_MAP_REGION0`"]
pub struct RQOS_MAP_REGION0_W<'a> {
w: &'a mut W,
}
impl<'a> RQOS_MAP_REGION0_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: RQOS_MAP_REGION0_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "LPR and 1: VPR only."]
#[inline(always)]
pub fn b_0x0(self) -> &'a mut W {
self.variant(RQOS_MAP_REGION0_A::B_0X0)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x03 << 16)) | (((value as u32) & 0x03) << 16);
self.w
}
}
#[doc = "RQOS_MAP_REGION1\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum RQOS_MAP_REGION1_A {
#[doc = "0: LPR and 1: VPR only."]
B_0X0 = 0,
}
impl From<RQOS_MAP_REGION1_A> for u8 {
#[inline(always)]
fn from(variant: RQOS_MAP_REGION1_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `RQOS_MAP_REGION1`"]
pub type RQOS_MAP_REGION1_R = crate::R<u8, RQOS_MAP_REGION1_A>;
impl RQOS_MAP_REGION1_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<u8, RQOS_MAP_REGION1_A> {
use crate::Variant::*;
match self.bits {
0 => Val(RQOS_MAP_REGION1_A::B_0X0),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `B_0X0`"]
#[inline(always)]
pub fn is_b_0x0(&self) -> bool {
*self == RQOS_MAP_REGION1_A::B_0X0
}
}
#[doc = "Write proxy for field `RQOS_MAP_REGION1`"]
pub struct RQOS_MAP_REGION1_W<'a> {
w: &'a mut W,
}
impl<'a> RQOS_MAP_REGION1_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: RQOS_MAP_REGION1_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "LPR and 1: VPR only."]
#[inline(always)]
pub fn b_0x0(self) -> &'a mut W {
self.variant(RQOS_MAP_REGION1_A::B_0X0)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x03 << 20)) | (((value as u32) & 0x03) << 20);
self.w
}
}
#[doc = "Reader of field `RQOS_MAP_REGION2`"]
pub type RQOS_MAP_REGION2_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `RQOS_MAP_REGION2`"]
pub struct RQOS_MAP_REGION2_W<'a> {
w: &'a mut W,
}
impl<'a> RQOS_MAP_REGION2_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x03 << 24)) | (((value as u32) & 0x03) << 24);
self.w
}
}
impl R {
#[doc = "Bits 0:3 - RQOS_MAP_LEVEL1"]
#[inline(always)]
pub fn rqos_map_level1(&self) -> RQOS_MAP_LEVEL1_R {
RQOS_MAP_LEVEL1_R::new((self.bits & 0x0f) as u8)
}
#[doc = "Bits 8:11 - RQOS_MAP_LEVEL2"]
#[inline(always)]
pub fn rqos_map_level2(&self) -> RQOS_MAP_LEVEL2_R {
RQOS_MAP_LEVEL2_R::new(((self.bits >> 8) & 0x0f) as u8)
}
#[doc = "Bits 16:17 - RQOS_MAP_REGION0"]
#[inline(always)]
pub fn rqos_map_region0(&self) -> RQOS_MAP_REGION0_R {
RQOS_MAP_REGION0_R::new(((self.bits >> 16) & 0x03) as u8)
}
#[doc = "Bits 20:21 - RQOS_MAP_REGION1"]
#[inline(always)]
pub fn rqos_map_region1(&self) -> RQOS_MAP_REGION1_R {
RQOS_MAP_REGION1_R::new(((self.bits >> 20) & 0x03) as u8)
}
#[doc = "Bits 24:25 - RQOS_MAP_REGION2"]
#[inline(always)]
pub fn rqos_map_region2(&self) -> RQOS_MAP_REGION2_R {
RQOS_MAP_REGION2_R::new(((self.bits >> 24) & 0x03) as u8)
}
}
impl W {
#[doc = "Bits 0:3 - RQOS_MAP_LEVEL1"]
#[inline(always)]
pub fn rqos_map_level1(&mut self) -> RQOS_MAP_LEVEL1_W {
RQOS_MAP_LEVEL1_W { w: self }
}
#[doc = "Bits 8:11 - RQOS_MAP_LEVEL2"]
#[inline(always)]
pub fn rqos_map_level2(&mut self) -> RQOS_MAP_LEVEL2_W {
RQOS_MAP_LEVEL2_W { w: self }
}
#[doc = "Bits 16:17 - RQOS_MAP_REGION0"]
#[inline(always)]
pub fn rqos_map_region0(&mut self) -> RQOS_MAP_REGION0_W {
RQOS_MAP_REGION0_W { w: self }
}
#[doc = "Bits 20:21 - RQOS_MAP_REGION1"]
#[inline(always)]
pub fn rqos_map_region1(&mut self) -> RQOS_MAP_REGION1_W {
RQOS_MAP_REGION1_W { w: self }
}
#[doc = "Bits 24:25 - RQOS_MAP_REGION2"]
#[inline(always)]
pub fn rqos_map_region2(&mut self) -> RQOS_MAP_REGION2_W {
RQOS_MAP_REGION2_W { w: self }
}
}
|
pub fn run(){
let age: u8 = 30;
let check_id: bool = true;
if age >= 21 && check_id{
println!("bartender: what would u like to drink?")
}else if age < 21 && check_id{
println!("bartender: go away!")
}else {
println!{"bartender: your id please"}
}
let bool_result_shorthand= if age > 1{true} else {false};
} |
#[doc = "Register `CCIPR4` reader"]
pub type R = crate::R<CCIPR4_SPEC>;
#[doc = "Register `CCIPR4` writer"]
pub type W = crate::W<CCIPR4_SPEC>;
#[doc = "Field `OCTOSPI1SEL` reader - OCTOSPI1 kernel clock source selection Set and reset by software."]
pub type OCTOSPI1SEL_R = crate::FieldReader;
#[doc = "Field `OCTOSPI1SEL` writer - OCTOSPI1 kernel clock source selection Set and reset by software."]
pub type OCTOSPI1SEL_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>;
#[doc = "Field `SYSTICKSEL` reader - SYSTICK clock source selection Note: rcc_hclk frequency must be four times higher than lsi_ker_ck/lse_ck (period (LSI/LSE) ≥ 4 * period (HCLK)."]
pub type SYSTICKSEL_R = crate::FieldReader;
#[doc = "Field `SYSTICKSEL` writer - SYSTICK clock source selection Note: rcc_hclk frequency must be four times higher than lsi_ker_ck/lse_ck (period (LSI/LSE) ≥ 4 * period (HCLK)."]
pub type SYSTICKSEL_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>;
#[doc = "Field `USBFSSEL` reader - USBFS kernel clock source selection"]
pub type USBFSSEL_R = crate::FieldReader;
#[doc = "Field `USBFSSEL` writer - USBFS kernel clock source selection"]
pub type USBFSSEL_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>;
#[doc = "Field `SDMMC1SEL` reader - SDMMC1 kernel clock source selection"]
pub type SDMMC1SEL_R = crate::BitReader;
#[doc = "Field `SDMMC1SEL` writer - SDMMC1 kernel clock source selection"]
pub type SDMMC1SEL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `SDMMC2SEL` reader - SDMMC2 kernel clock source selection"]
pub type SDMMC2SEL_R = crate::BitReader;
#[doc = "Field `SDMMC2SEL` writer - SDMMC2 kernel clock source selection"]
pub type SDMMC2SEL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `I2C1SEL` reader - I2C1 kernel clock source selection"]
pub type I2C1SEL_R = crate::FieldReader;
#[doc = "Field `I2C1SEL` writer - I2C1 kernel clock source selection"]
pub type I2C1SEL_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>;
#[doc = "Field `I2C2SEL` reader - I2C2 kernel clock source selection"]
pub type I2C2SEL_R = crate::FieldReader;
#[doc = "Field `I2C2SEL` writer - I2C2 kernel clock source selection"]
pub type I2C2SEL_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>;
#[doc = "Field `I2C3SEL` reader - I2C3 kernel clock source selection"]
pub type I2C3SEL_R = crate::FieldReader;
#[doc = "Field `I2C3SEL` writer - I2C3 kernel clock source selection"]
pub type I2C3SEL_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>;
#[doc = "Field `I2C4SEL` reader - I2C4 kernel clock source selection"]
pub type I2C4SEL_R = crate::FieldReader;
#[doc = "Field `I2C4SEL` writer - I2C4 kernel clock source selection"]
pub type I2C4SEL_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>;
#[doc = "Field `I3C1SEL` reader - I3C1 kernel clock source selection"]
pub type I3C1SEL_R = crate::FieldReader;
#[doc = "Field `I3C1SEL` writer - I3C1 kernel clock source selection"]
pub type I3C1SEL_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>;
impl R {
#[doc = "Bits 0:1 - OCTOSPI1 kernel clock source selection Set and reset by software."]
#[inline(always)]
pub fn octospi1sel(&self) -> OCTOSPI1SEL_R {
OCTOSPI1SEL_R::new((self.bits & 3) as u8)
}
#[doc = "Bits 2:3 - SYSTICK clock source selection Note: rcc_hclk frequency must be four times higher than lsi_ker_ck/lse_ck (period (LSI/LSE) ≥ 4 * period (HCLK)."]
#[inline(always)]
pub fn systicksel(&self) -> SYSTICKSEL_R {
SYSTICKSEL_R::new(((self.bits >> 2) & 3) as u8)
}
#[doc = "Bits 4:5 - USBFS kernel clock source selection"]
#[inline(always)]
pub fn usbfssel(&self) -> USBFSSEL_R {
USBFSSEL_R::new(((self.bits >> 4) & 3) as u8)
}
#[doc = "Bit 6 - SDMMC1 kernel clock source selection"]
#[inline(always)]
pub fn sdmmc1sel(&self) -> SDMMC1SEL_R {
SDMMC1SEL_R::new(((self.bits >> 6) & 1) != 0)
}
#[doc = "Bit 7 - SDMMC2 kernel clock source selection"]
#[inline(always)]
pub fn sdmmc2sel(&self) -> SDMMC2SEL_R {
SDMMC2SEL_R::new(((self.bits >> 7) & 1) != 0)
}
#[doc = "Bits 16:17 - I2C1 kernel clock source selection"]
#[inline(always)]
pub fn i2c1sel(&self) -> I2C1SEL_R {
I2C1SEL_R::new(((self.bits >> 16) & 3) as u8)
}
#[doc = "Bits 18:19 - I2C2 kernel clock source selection"]
#[inline(always)]
pub fn i2c2sel(&self) -> I2C2SEL_R {
I2C2SEL_R::new(((self.bits >> 18) & 3) as u8)
}
#[doc = "Bits 20:21 - I2C3 kernel clock source selection"]
#[inline(always)]
pub fn i2c3sel(&self) -> I2C3SEL_R {
I2C3SEL_R::new(((self.bits >> 20) & 3) as u8)
}
#[doc = "Bits 22:23 - I2C4 kernel clock source selection"]
#[inline(always)]
pub fn i2c4sel(&self) -> I2C4SEL_R {
I2C4SEL_R::new(((self.bits >> 22) & 3) as u8)
}
#[doc = "Bits 24:25 - I3C1 kernel clock source selection"]
#[inline(always)]
pub fn i3c1sel(&self) -> I3C1SEL_R {
I3C1SEL_R::new(((self.bits >> 24) & 3) as u8)
}
}
impl W {
#[doc = "Bits 0:1 - OCTOSPI1 kernel clock source selection Set and reset by software."]
#[inline(always)]
#[must_use]
pub fn octospi1sel(&mut self) -> OCTOSPI1SEL_W<CCIPR4_SPEC, 0> {
OCTOSPI1SEL_W::new(self)
}
#[doc = "Bits 2:3 - SYSTICK clock source selection Note: rcc_hclk frequency must be four times higher than lsi_ker_ck/lse_ck (period (LSI/LSE) ≥ 4 * period (HCLK)."]
#[inline(always)]
#[must_use]
pub fn systicksel(&mut self) -> SYSTICKSEL_W<CCIPR4_SPEC, 2> {
SYSTICKSEL_W::new(self)
}
#[doc = "Bits 4:5 - USBFS kernel clock source selection"]
#[inline(always)]
#[must_use]
pub fn usbfssel(&mut self) -> USBFSSEL_W<CCIPR4_SPEC, 4> {
USBFSSEL_W::new(self)
}
#[doc = "Bit 6 - SDMMC1 kernel clock source selection"]
#[inline(always)]
#[must_use]
pub fn sdmmc1sel(&mut self) -> SDMMC1SEL_W<CCIPR4_SPEC, 6> {
SDMMC1SEL_W::new(self)
}
#[doc = "Bit 7 - SDMMC2 kernel clock source selection"]
#[inline(always)]
#[must_use]
pub fn sdmmc2sel(&mut self) -> SDMMC2SEL_W<CCIPR4_SPEC, 7> {
SDMMC2SEL_W::new(self)
}
#[doc = "Bits 16:17 - I2C1 kernel clock source selection"]
#[inline(always)]
#[must_use]
pub fn i2c1sel(&mut self) -> I2C1SEL_W<CCIPR4_SPEC, 16> {
I2C1SEL_W::new(self)
}
#[doc = "Bits 18:19 - I2C2 kernel clock source selection"]
#[inline(always)]
#[must_use]
pub fn i2c2sel(&mut self) -> I2C2SEL_W<CCIPR4_SPEC, 18> {
I2C2SEL_W::new(self)
}
#[doc = "Bits 20:21 - I2C3 kernel clock source selection"]
#[inline(always)]
#[must_use]
pub fn i2c3sel(&mut self) -> I2C3SEL_W<CCIPR4_SPEC, 20> {
I2C3SEL_W::new(self)
}
#[doc = "Bits 22:23 - I2C4 kernel clock source selection"]
#[inline(always)]
#[must_use]
pub fn i2c4sel(&mut self) -> I2C4SEL_W<CCIPR4_SPEC, 22> {
I2C4SEL_W::new(self)
}
#[doc = "Bits 24:25 - I3C1 kernel clock source selection"]
#[inline(always)]
#[must_use]
pub fn i3c1sel(&mut self) -> I3C1SEL_W<CCIPR4_SPEC, 24> {
I3C1SEL_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "RCC kernel clock configuration register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ccipr4::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`ccipr4::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct CCIPR4_SPEC;
impl crate::RegisterSpec for CCIPR4_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`ccipr4::R`](R) reader structure"]
impl crate::Readable for CCIPR4_SPEC {}
#[doc = "`write(|w| ..)` method takes [`ccipr4::W`](W) writer structure"]
impl crate::Writable for CCIPR4_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets CCIPR4 to value 0"]
impl crate::Resettable for CCIPR4_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
#![allow(non_snake_case, non_camel_case_types)]
use libc::{c_char, c_int, c_void};
use crate::session::ssh_session;
/// No logging at all
pub const SSH_LOG_NOLOG: i32 = 0;
/// Only warnings
pub const SSH_LOG_WARNING: i32 = 1;
/// High level protocol information
pub const SSH_LOG_PROTOCOL: i32 = 2;
/// Lower level protocol infomations, packet level
pub const SSH_LOG_PACKET: i32 = 3;
/// Every function path
pub const SSH_LOG_FUNCTIONS: i32 = 4;
// Logging verbosity levels. Debug levels for logging.
/// No logging at all
pub const SSH_LOG_NONE: u32 = 0;
/// Show only warnings
pub const SSH_LOG_WARN: u32 = 1;
/// Get some information what's going on
pub const SSH_LOG_INFO: u32 = 2;
/// Get detailed debuging information
pub const SSH_LOG_DEBUG: u32 = 3;
/// Get trace output, packet information
pub const SSH_LOG_TRACE: u32 = 4;
extern "C" {
#[deprecated(note = "Use _ssh_log instead.")]
pub fn ssh_log(session: ssh_session, prioriry: c_int, format: *const c_char, ...);
pub fn _ssh_log(verbosity: c_int, function: *const c_char, format: *const c_char, ...);
pub fn ssh_set_log_level(level: c_int) -> c_int;
pub fn ssh_get_log_level() -> c_int;
pub fn ssh_set_log_userdata(data: *mut c_void) -> c_int;
pub fn ssh_get_log_userdata() -> *mut c_void;
}
|
use std::error::Error;
#[derive(Clone, Debug)]
pub struct ValidationError(pub Option<String>);
impl Error for ValidationError {}
impl From<&str> for ValidationError {
fn from(msg: &str) -> Self {
Self(Some(msg.to_owned()))
}
}
impl From<String> for ValidationError {
fn from(msg: String) -> Self {
Self(Some(msg))
}
}
impl From<Option<String>> for ValidationError {
fn from(msg: Option<String>) -> Self {
Self(msg)
}
}
impl std::fmt::Display for ValidationError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}",
self.0
.as_ref()
.map(String::as_str)
.unwrap_or("Validation error")
)
}
}
#[macro_export]
macro_rules! invalid {
() => { ValidationError::from(None) };
($($arg:tt)+) => {
ValidationError::from(format!($($arg)+))
};
}
pub trait Validatable {
fn validate(&self) -> Result<(), ValidationError> {
Ok(())
}
}
|
//! Library to valide google-sign-in tokens
//!
//! See https://developers.google.com/identity/sign-in/web/backend-auth
//!
#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate serde_json;
extern crate base64;
extern crate time;
extern crate openssl;
/// Error types and their utilities
pub mod errors;
use errors::Error;
use std::io::Read;
use time::Timespec;
use openssl::bn::BigNum;
use openssl::hash::MessageDigest;
use openssl::pkey::{Public, PKey};
use openssl::rsa::Rsa;
use openssl::sign::Verifier;
use std::collections::HashMap;
type JsonValue = serde_json::value::Value;
type JsonObject = serde_json::map::Map<String, JsonValue>;
#[derive(Deserialize,Debug)]
struct Header {
pub alg: String,
pub kid: String,
}
struct Payload {
pub sub: String,
pub iss: String,
pub aud: String,
pub exp: Timespec,
}
#[derive(Deserialize)]
struct JsonKey {
pub kty: String,
pub alg: String,
#[serde(rename = "use")]
pub use_: String,
pub kid: String,
pub n: String,
pub e: String,
}
#[derive(Deserialize)]
struct JsonKeys {
pub keys: Vec<JsonKey>,
}
struct Key {
alg: String,
pkey: PKey<Public>,
}
type KeysMap = HashMap<String, Key>;
/// Context used to store Client_id and google public keys
pub struct Ctx {
client_id: String,
keys: KeysMap,
}
impl Ctx {
/// Instantiate a new context
///
/// Use `set_keys_from_reader` to set google public keys
pub fn new(client_id: String) -> Ctx {
Ctx {
client_id: client_id,
keys: HashMap::new(),
}
}
fn set_keys_from_json_keys(&mut self, jsonkeys: JsonKeys) -> Result<(), Error> {
let mut map: KeysMap = HashMap::new();
for key in jsonkeys.keys {
if key.use_ != "sig" {
continue;
}
match key.alg.as_ref() {
"RS256" => {
let n_decoded = base64_decode_url(&key.n)?;
let n = BigNum::from_slice(&n_decoded)?;
let e_decoded = base64_decode_url(&key.e)?;
let e = BigNum::from_slice(&e_decoded)?;
let rsa = Rsa::from_public_components(n, e)?;
let pkey : PKey<Public> = PKey::from_rsa(rsa)?;
let k = Key {
alg: key.alg.clone(),
pkey: pkey,
};
map.insert(key.kid, k);
}
_ => return Err(Error::UnsupportedAlgorithm),
}
}
if map.len() == 0 {
return Err(Error::NoKeys);
}
self.keys = map;
Ok(())
}
/// Set google public keys used to verify tokens' signatures
///
/// Expected format is JWK and an be found at
/// https://www.googleapis.com/oauth2/v3/certs
pub fn set_keys_from_reader<R>(&mut self, reader: R) -> Result<(), Error>
where R: Read
{
let jsonkeys: JsonKeys = serde_json::from_reader(reader)?;
return self.set_keys_from_json_keys(jsonkeys);
}
/// Set google public keys used to verify tokens' signatures
///
/// Expected format is JWK and an be found at
/// https://www.googleapis.com/oauth2/v3/certs
pub fn set_keys_from_str<'a>(&mut self, s: &'a str) -> Result<(), Error>
{
let jsonkeys: JsonKeys = serde_json::from_str(s)?;
return self.set_keys_from_json_keys(jsonkeys);
}
/// Validate a google sign-in token
///
/// What is checked:
///
/// - The ID token is properly signed by Google using Google's public keys
/// - The value of `aud` in the token is equal to the client ID.
/// - The value of `iss` in the token is equal to accounts.google.com or
/// https://accounts.google.com.
/// - The expiry time (exp) of the token has not passed, with an hour delay
/// to handle time skews
///
/// Returns the `sub` field as a `String` or an `Error`
pub fn google_signin_from_str(&self, token: &str) -> Result<String, Error> {
let arr: Vec<&str> = token.split(".").collect();
if arr.len() != 3 {
return Err(Error::InvalidToken);
}
let hdr_base64 = arr[0];
let payload_base64 = arr[1];
let sig_base64 = arr[2];
let hdr = decode_header(hdr_base64)?;
let payload = decode_payload(payload_base64)?;
let sig = base64_decode_url(sig_base64)?;
let sig_slice: &[u8] = &sig;
verify_payload(self, &payload)?;
verify_signature(self, &hdr, &hdr_base64, &payload_base64, sig_slice)?;
Ok(payload.sub)
}
}
fn base64_decode_url(msg: &str) -> Result<Vec<u8>, base64::DecodeError> {
base64::decode_config(msg, base64::URL_SAFE)
}
fn decode_header(base64_hdr: &str) -> Result<Header, Error> {
let hdr = base64_decode_url(base64_hdr)?;
let hdr: Header = serde_json::from_slice(&hdr)?;
Ok(hdr)
}
fn json_get_str<'a>(obj: &'a JsonObject, name: &'static str) -> Result<&'a str, Error> {
let o: Option<&JsonValue> = obj.get(name);
if let Some(v) = o {
if !v.is_string() {
return Err(Error::InvalidTypeField(name));
}
return Ok(v.as_str().unwrap());
} else {
return Err(Error::MissingField(name));
}
}
fn json_get_numeric_date(obj: &JsonObject, name: &'static str) -> Result<Timespec, Error> {
let o: Option<&JsonValue> = obj.get(name);
if let Some(v) = o {
if !v.is_i64() {
return Err(Error::InvalidTypeField(name));
}
let sec = v.as_i64().unwrap();
return Ok(Timespec { sec: sec, nsec: 0 });
} else {
return Err(Error::MissingField(name));
}
}
fn decode_payload(base64_payload: &str) -> Result<Payload, Error> {
let payload_json = base64_decode_url(base64_payload)?;
let obj: JsonValue = serde_json::from_slice(&payload_json)?;
if !obj.is_object() {
return Err(Error::InvalidTypeField(""));
}
let obj = obj.as_object().unwrap();
let sub = json_get_str(obj, "sub")?;
let iss = json_get_str(obj, "iss")?;
let aud = json_get_str(obj, "aud")?;
let exp = json_get_numeric_date(obj, "exp")?;
Ok(Payload {
sub: sub.to_string(),
iss: iss.to_string(),
aud: aud.to_string(),
exp: exp,
})
}
fn verify_payload(ctx: &Ctx, payload: &Payload) -> Result<(), Error> {
if payload.aud != ctx.client_id {
return Err(Error::InvalidAudience);
}
if payload.iss != "accounts.google.com" && payload.iss != "https://accounts.google.com" {
return Err(Error::InvalidIssuer);
}
let now = time::now_utc().to_timespec();
if payload.exp.sec + 3600 < now.sec {
return Err(Error::Expired);
}
Ok(())
}
fn verify_rs256(txt: &str, key: &Key, sig: &[u8]) -> Result<(), Error> {
let digest = MessageDigest::sha256();
let mut verifier = Verifier::new(digest, &key.pkey)?;
verifier.update(txt.as_bytes())?;
let res = verifier.verify(sig);
match res {
Ok(true) => Ok(()),
Ok(false) => Err(Error::InvalidSignature),
Err(_) => Err(Error::InvalidSignature),
}
}
fn verify_signature(ctx: &Ctx,
hdr: &Header,
hdr_base64: &str,
payload_base64: &str,
sig: &[u8])
-> Result<(), Error> {
let txt = format!("{}.{}", hdr_base64, payload_base64);
let key = ctx.keys.get(&hdr.kid);
if key.is_none() {
return Err(Error::NoMatchingSigningKey);
}
let key = key.unwrap();
if key.alg != hdr.alg {
return Err(Error::NoMatchingSigningKey);
}
match key.alg.as_ref() {
"RS256" => verify_rs256(&txt, key, sig),
_ => Err(Error::UnsupportedAlgorithm),
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs::File;
fn content_from_file(filename: &str) -> String {
let mut file = File::open(filename).unwrap();
let mut buf = String::new();
assert!(file.read_to_string(&mut buf).is_ok());
buf.pop(); // remove trailing \n
buf
}
#[test]
fn from_token_file() {
let token = content_from_file("token");
let client_id = content_from_file("client_id");
let mut ctx = Ctx::new(client_id);
let keys = File::open("google_keys.json").unwrap();
assert!(ctx.set_keys_from_reader(keys).is_ok());
let res = ctx.google_signin_from_str(&token);
assert!(res.is_ok());
}
}
|
//! # Usage
//!
//! There are two main concepts in this library:
//!
//! - Sources, represented with the `Source` trait, that provide sound data.
//! - Sinks, which accept sound data.
//!
//! In order to play a sound, you need to create a source, a sink, and connect the two. For example
//! here is how you play a sound file:
//!
//! ```no_run
//! use std::io::BufReader;
//!
//! let endpoint = rodio::get_default_endpoint().unwrap();
//! let sink = rodio::Sink::new(&endpoint);
//!
//! let file = std::fs::File::open("music.ogg").unwrap();
//! let source = rodio::Decoder::new(BufReader::new(file)).unwrap();
//! sink.append(source);
//! ```
//!
//! The `append` method takes ownership of the source and starts playing it. If a sink is already
//! playing a sound when you call `append`, the sound is added to a queue and will start playing
//! when the existing source is over.
//!
//! If you want to play multiple sounds simultaneously, you should create multiple sinks.
//!
//! # How it works
//!
//! Rodio spawns a background thread that is dedicated to reading from the sources and sending
//! the output to the endpoint.
//!
//! All the sounds are mixed together by rodio before being sent. Since this is handled by the
//! software, there is no restriction for the number of sinks that can be created.
//!
//! # Adding effects
//!
//! The `Source` trait provides various filters, similarly to the standard `Iterator` trait.
//!
//! Example:
//!
//! ```ignore
//! use rodio::Source;
//! use std::time::Duration;
//!
//! // repeats the first five seconds of this sound forever
//! let source = source.take_duration(Duration::from_secs(5)).repeat_infinite();
//! ```
#![cfg_attr(test, deny(missing_docs))]
extern crate cpal;
extern crate futures;
extern crate hound;
#[macro_use]
extern crate lazy_static;
extern crate vorbis;
pub use cpal::{Endpoint, get_endpoints_list, get_default_endpoint};
pub use conversions::Sample;
pub use decoder::Decoder;
pub use source::Source;
use std::io::{Read, Seek};
use std::time::Duration;
use std::thread;
mod conversions;
mod engine;
pub mod decoder;
pub mod source;
lazy_static! {
static ref ENGINE: engine::Engine = engine::Engine::new();
}
/// Handle to an endpoint that outputs sounds.
///
/// Dropping the `Sink` stops all sounds. You can use `detach` if you want the sounds to continue
/// playing.
pub struct Sink {
handle: engine::Handle,
// if true, then the sound will stop playing at the end
stop: bool,
}
impl Sink {
/// Builds a new `Sink`.
#[inline]
pub fn new(endpoint: &Endpoint) -> Sink {
Sink {
handle: ENGINE.start(&endpoint),
stop: true,
}
}
/// Appends a sound to the queue of sounds to play.
#[inline]
pub fn append<S>(&self, source: S) where S: Source + Send + 'static,
S::Item: Sample, S::Item: Send
{
self.handle.append(source);
}
/// Changes the volume of the sound.
///
/// The value `1.0` is the "normal" volume (unfiltered input). Any value other than 1.0 will
/// multiply each sample by this value.
#[inline]
pub fn set_volume(&mut self, value: f32) {
self.handle.set_volume(value);
}
/// Destroys the sink without stopping the sounds that are still playing.
#[inline]
pub fn detach(mut self) {
self.stop = false;
}
/// Sleeps the current thread until the sound ends.
#[inline]
pub fn sleep_until_end(&self) {
self.handle.sleep_until_end();
}
}
impl Drop for Sink {
#[inline]
fn drop(&mut self) {
if self.stop {
self.handle.stop();
}
}
}
/// Plays a sound once. Returns a `Sink` that can be used to control the sound.
#[inline]
pub fn play_once<R>(endpoint: &Endpoint, input: R) -> Result<Sink, decoder::DecoderError>
where R: Read + Seek + Send + 'static
{
let input = try!(decoder::Decoder::new(input));
let sink = Sink::new(endpoint);
sink.append(input);
Ok(sink)
}
|
use std::collections::vec_deque::VecDeque;
use std::fmt;
use std::mem;
use std::ops::{Deref, DerefMut};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Mutex, MutexGuard};
use std::task::{Context, Waker};
struct Waiter {
key: usize,
waker: Waker,
}
struct Inner {
queue: VecDeque<Waiter>,
notified_count: usize,
min_key: usize,
next_key: usize,
}
// Set when there is at least one notifiable waker
const WAITING: usize = 1 << 1;
// Set when we at least one task has been notified, but hasn't
// yet been removed
const NOTIFIED: usize = 1 << 2;
/// An ordered list of [`std::task::Waker`]s.
///
/// This allows waking wakers in the same order that they were added to this queue.
pub struct Waitlist {
flags: AtomicUsize,
inner: Mutex<Inner>,
}
/// Handle for controlling the wait status of a task.
pub struct WaitHandle<'a> {
waitlist: &'a Waitlist,
key: Option<usize>,
}
impl Waitlist {
/// Create a new `Waitlist`
#[inline]
pub fn new() -> Waitlist {
Self::with_capacity(0)
}
/// Create a new waitlist with a given initial capacity
///
/// This determines how much capacity the underlying `Vec` should be created with.
#[inline]
pub fn with_capacity(cap: usize) -> Waitlist {
Waitlist {
flags: AtomicUsize::new(0),
inner: Mutex::new(Inner {
queue: VecDeque::with_capacity(cap),
notified_count: 0,
min_key: 0,
next_key: 0,
}),
}
}
/// Lock `inner`, and give a new guard that includes the atomic flags
fn lock(&self) -> Guard<'_> {
Guard {
flags: &self.flags,
inner: self.inner.lock().unwrap(),
}
}
/// Return a handle a task can use to wait for events
///
/// Calling this method doesn't do anything itself, but gives you an object
/// that you can then call [`WaitHandle::set_context`] on to attach a polling context to the task so
/// that it is notified when one of the `notify_*` methods is called. It is also used to mark
/// the the task as done or canceled.
#[inline]
pub fn wait(&self) -> WaitHandle<'_> {
WaitHandle {
waitlist: self,
key: None,
}
}
/// Wake the first waker in the queue
///
/// Returns true if a waker was woken and false if no task was woken (that is, the queue
/// was empty).
#[inline]
pub fn notify_one(&self) -> bool {
if self.flags.load(Ordering::Relaxed) & WAITING != 0 {
self.lock().notify_first()
} else {
false
}
}
/// Wake all wakers in the queue
///
/// Returns true if at least one waker was woken. False otherwise.
#[inline]
pub fn notify_all(&self) -> bool {
if self.flags.load(Ordering::Relaxed) & WAITING != 0 {
self.lock().notify_all()
} else {
false
}
}
/// Wake the next waker, unless it has already been notified.
///
/// This ensures that at least one waker has been notified, but avoid waking
/// multiple wakers if multiple events occur before the first task has marked the
/// handle as completed.
#[inline]
pub fn notify_any(&self) -> bool {
let flags = self.flags.load(Ordering::Relaxed);
if flags & NOTIFIED == 0 && flags & WAITING != 0 {
let mut inner = self.lock();
// We need check the notified_count, because
// the number of notified tasks may have changed
// between checking the flags and getting the lock
if inner.notified_count == 0 {
inner.notify_first()
} else {
false
}
} else {
false
}
}
}
impl fmt::Debug for Waitlist {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("Waitlist")
.field("flags", &self.flags)
.finish()
}
}
impl WaitHandle<'_> {
/// Mark this task as completed.
///
/// If this handle still has a waker on the queue,
/// remove that waker without triggering another notify
/// and return true. Otherwise, return false.
#[inline]
pub fn finish(&mut self) -> bool {
if let Some(key) = self.key.take() {
self.waitlist.lock().remove(key)
} else {
false
}
}
/// Mark that the task was cancelled.
///
/// If this handle currently has a waker on the queue and there is
/// at least one other task waiting on the queue, remove this waker from the queue,
/// wake the next task, and return true. Otherwise return false.
#[inline]
pub fn cancel(&mut self) -> bool {
if let Some(key) = self.key.take() {
self.waitlist.lock().cancel(key)
} else {
false
}
}
#[inline]
pub fn set_context(&mut self, cx: &Context) {
let key = if let Some(key) = self.key {
self.waitlist.lock().update(key, cx)
} else {
self.waitlist.lock().insert(cx)
};
self.key = Some(key);
}
/// Return true if the WaitHandle has been polled at least once, and has not been
/// completed (by calling either `finish` or `cancel`).
pub fn is_pending(&self) -> bool {
self.key.is_some()
}
/// Mark as finished if this was notified, otherwise update the context.
///
/// This is roughly equivalent to
///
/// ```no_run
/// # let waitlist = waitlist::Waitlist::new();
/// # let mut handle = waitlist.wait();
/// # let waker = futures_task::noop_waker();
/// # let cx = std::task::Context::from_waker(&waker);
/// let did_finish = if handle.finish() {
/// handle.set_context(&cx);
/// false
/// } else {
/// true
/// };
/// ```
/// but operates atomically on the waitlist.
pub fn try_finish(&mut self, cx: &mut Context<'_>) -> bool {
if let Some(key) = self.key {
if self.waitlist.lock().update_if_pending(key, cx) {
return false;
} else {
self.key = None;
}
}
true
}
/// Convert into a key that can later be used with `from_key` to convert back into a `WaitHandle`.
pub fn into_key(self) -> Option<usize> {
let key = self.key;
mem::forget(self);
key
}
// should this be unsafe?
/// Create a `WaitHandle` for a `Waitlist` using a key that was previously acquired from
/// `into_key`.
///
/// For this to work as expected, `key` should be a key returned by a previous call to `into_key`
/// on a `WaitHandle` that was created from the same `waitlist`. This takes ownership of the wait
/// entry for this key.
///
/// You should avoid using this if possible, but in some cases it is necessary to avoid
/// self-reference.
pub fn from_key(waitlist: &Waitlist, key: Option<usize>) -> WaitHandle<'_> {
WaitHandle { waitlist, key }
}
}
impl<'a> Drop for WaitHandle<'a> {
fn drop(&mut self) {
if let Some(key) = self.key {
self.waitlist.lock().cancel(key);
}
}
}
unsafe impl Send for Waitlist {}
unsafe impl Sync for Waitlist {}
impl Default for Waitlist {
fn default() -> Self {
Self::new()
}
}
impl Inner {
fn is_in_waiting_range(&self, key: usize) -> bool {
// the part after `||` is to deal with if the key wraps around
key >= self.min_key || (self.next_key < self.min_key && key < self.next_key)
}
fn insert(&mut self, cx: &Context<'_>) -> usize {
let key = self.next_key;
let waker = cx.waker().clone();
self.next_key = self.next_key.wrapping_add(1);
self.queue.push_back(Waiter { key, waker });
key
}
fn update(&mut self, key: usize, cx: &Context<'_>) -> usize {
if self.is_in_waiting_range(key) {
if let Some(w) = self.queue.iter_mut().find(|w| w.key == key) {
w.waker = cx.waker().clone();
return key;
}
}
self.notified_count -= 1; // the waiter was already notified, so we need to decrement the number of actively notified tasks
self.insert(cx)
}
fn remove(&mut self, key: usize) -> bool {
if self.is_in_waiting_range(key) {
if let Some(idx) = self.queue.iter().position(|w| w.key == key) {
self.queue.remove(idx);
return false;
}
}
self.notified_count -= 1;
true
}
fn cancel(&mut self, key: usize) -> bool {
if self.remove(key) {
self.notify_first()
} else {
false
}
}
/// Update the waker for the task for `key`, but only if it is still waiting to
/// be woken.
///
/// Return true if a waker was updated, false, if no waiting task was found.
///
/// If no waker was updated decrement the notified_count to mark that one of the notified tasks
/// has been handled.
fn update_if_pending(&mut self, key: usize, cx: &Context<'_>) -> bool {
// all we really need to do here is decrement notified_count if the key isn't in the queue
if self.is_in_waiting_range(key) {
if let Some(w) = self.queue.iter_mut().find(|w| w.key == key) {
w.waker = cx.waker().clone();
return true;
}
}
self.notified_count -= 1;
false
}
fn notify_first(&mut self) -> bool {
if let Some(waiter) = self.queue.pop_front() {
self.notified_count += 1;
debug_assert!(waiter.key >= self.min_key);
self.min_key = waiter.key.wrapping_add(1);
waiter.waker.wake();
true
} else {
false
}
}
fn notify_all(&mut self) -> bool {
let num_notified = self.queue.len();
while let Some(w) = self.queue.pop_front() {
w.waker.wake();
}
self.notified_count += num_notified;
self.min_key = self.next_key;
num_notified > 0
}
}
struct Guard<'a> {
flags: &'a AtomicUsize,
inner: MutexGuard<'a, Inner>,
}
impl<'a> Deref for Guard<'a> {
type Target = Inner;
#[inline]
fn deref(&self) -> &Inner {
&self.inner
}
}
impl<'a> DerefMut for Guard<'a> {
#[inline]
fn deref_mut(&mut self) -> &mut Inner {
&mut self.inner
}
}
impl<'a> Drop for Guard<'a> {
fn drop(&mut self) {
let mut flags = 0;
if !self.queue.is_empty() {
flags |= WAITING;
}
if self.notified_count > 0 {
flags |= NOTIFIED;
}
// Update flags. Use relaxed ordering because
// releasing the mutex will create a memory boundary.
self.flags.store(flags, Ordering::Relaxed);
}
}
#[cfg(test)]
mod test {
use super::*;
use futures_task::noop_waker;
#[test]
fn wraparound() {
const KEY_START: usize = usize::max_value() - 1;
let mut inner = Inner {
queue: VecDeque::new(),
notified_count: 0,
min_key: KEY_START,
next_key: KEY_START,
};
let waker = noop_waker();
let context = Context::from_waker(&waker);
inner.insert(&context);
let k2 = inner.insert(&context);
let k3 = inner.insert(&context);
assert_eq!(0, k3);
assert_eq!(1, inner.next_key);
assert!(inner.notify_first());
assert_eq!(usize::max_value(), inner.min_key);
assert!(inner.is_in_waiting_range(k2));
assert!(inner.is_in_waiting_range(k3));
assert_eq!(0, inner.update(0, &context));
assert!(!inner.remove(0));
assert!(!inner.remove(k2));
}
}
|
use std::error::Error;
use std::fmt::{self, Display, Formatter};
use std::string::FromUtf8Error;
use cgmath::{InnerSpace, Vector3};
use rayon::ThreadPool;
use renderer::vertex::PosNormTex;
use wavefront_obj::ParseError;
use wavefront_obj::obj::{parse, Normal, NormalIndex, ObjSet, Object, Primitive, TVertex,
TextureIndex, Vertex, VertexIndex};
use assets::{Format, SpawnedFuture};
/// A future which will eventually have an vertices available.
pub type VerticesFuture<V> = SpawnedFuture<Vec<V>, ObjError>;
/// Error type of `ObjFormat`
#[derive(Debug)]
pub enum ObjError {
/// Coundn't convert bytes to `String`
Utf8(FromUtf8Error),
/// Cound't parse obj file
Parse(ParseError),
}
impl Error for ObjError {
fn description(&self) -> &str {
match *self {
ObjError::Utf8(ref err) => err.description(),
ObjError::Parse(_) => "Obj parsing error",
}
}
fn cause(&self) -> Option<&Error> {
match *self {
ObjError::Utf8(ref err) => Some(err),
ObjError::Parse(_) => None,
}
}
}
impl Display for ObjError {
fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
match *self {
ObjError::Utf8(ref err) => write!(fmt, "Obj file not a unicode: {:?}", err),
ObjError::Parse(ref err) => write!(fmt, "Obj parsing error: {}", err.message),
}
}
}
/// Allows loading from Wavefront files
/// see: https://en.wikipedia.org/wiki/Wavefront_.obj_file
pub struct ObjFormat;
impl Format for ObjFormat {
const EXTENSIONS: &'static [&'static str] = &["obj"];
type Data = Vec<PosNormTex>;
type Error = ObjError;
type Result = VerticesFuture<PosNormTex>;
fn parse(&self, bytes: Vec<u8>, pool: &ThreadPool) -> Self::Result {
VerticesFuture::spawn(pool, move || {
String::from_utf8(bytes)
.map_err(ObjError::Utf8)
.and_then(|string| parse(string).map_err(ObjError::Parse))
.map(|set| from_data(set))
})
}
}
fn convert(
object: &Object,
vi: VertexIndex,
ti: Option<TextureIndex>,
ni: Option<NormalIndex>,
) -> PosNormTex {
PosNormTex {
position: {
let vertex: Vertex = object.vertices[vi];
[vertex.x as f32, vertex.y as f32, vertex.z as f32]
},
normal: ni.map(|i| {
let normal: Normal = object.normals[i];
Vector3::from([normal.x as f32, normal.y as f32, normal.z as f32])
.normalize()
.into()
}).unwrap_or([0.0, 0.0, 0.0]),
tex_coord: ti.map(|i| {
let tvertex: TVertex = object.tex_vertices[i];
[tvertex.u as f32, tvertex.v as f32]
}).unwrap_or([0.0, 0.0]),
}
}
fn convert_primitive(object: &Object, prim: &Primitive) -> Option<[PosNormTex; 3]> {
match *prim {
Primitive::Triangle(v1, v2, v3) => Some([
convert(object, v1.0, v1.1, v1.2),
convert(object, v2.0, v2.1, v2.2),
convert(object, v3.0, v3.1, v3.2),
]),
_ => None,
}
}
fn from_data(obj_set: ObjSet) -> Vec<PosNormTex> {
// Takes a list of objects that contain geometries that contain shapes that contain
// vertex/texture/normal indices into the main list of vertices, and converts to a
// flat vec of `PosNormTex` objects.
// TODO: Doesn't differentiate between objects in a `*.obj` file, treats
// them all as a single mesh.
let vertices = obj_set.objects.iter().flat_map(|object| {
object.geometry.iter().flat_map(move |geometry| {
geometry
.shapes
.iter()
.filter_map(move |s| convert_primitive(object, &s.primitive))
})
});
let mut result = Vec::new();
for vvv in vertices {
result.push(vvv[0]);
result.push(vvv[1]);
result.push(vvv[2]);
}
result
}
|
use crossbeam_channel;
use etherparse;
use etherparse::TransportHeader;
use std::sync::Arc;
use tun_tap;
use crate::errors::TitError;
use crate::errors::{Result, TcpChannelError};
use crate::print;
use crate::print::Direction;
use crate::tcp;
use crate::tcp::TcpPacket;
/// Ethernet MTU = 1500
pub type EthernetPacket = [u8; 1500];
pub type NetworkChannelContents = (Box<EthernetPacket>, usize);
pub type SendEthernetPacket = crossbeam_channel::Sender<NetworkChannelContents>;
pub fn start_nic(tcp: tcp::IncomingPackets) -> Result<SendEthernetPacket> {
// We don't care about the 4 byte header
let tun = Arc::new(tun_tap::Iface::without_packet_info(
"tun_tit%d",
tun_tap::Mode::Tun,
)?);
let (incoming_packets, outgoing_packets) =
crossbeam_channel::unbounded::<(Box<EthernetPacket>, usize)>();
let write_tun = tun.clone();
let _write = std::thread::spawn(move || {
let tun = write_tun;
let send_packet = move || -> Result<()> {
let (packet, len) = outgoing_packets
.recv()
.map_err(|e| TitError::OutgoingNetworkChannelClosed(e))?;
eprintln!("SENDING");
print::packet_overview(&packet[..len], Direction::Outgoing);
eprintln!();
tun.send(&packet[..len])?;
Ok(())
};
loop {
send_packet().expect("error on NIC send thread");
}
});
let _read = std::thread::spawn(|| {
// I don't like reusing these, feels like I could accidentally expose data from previous packets if I'm not careful
let mut rec_buf: EthernetPacket = [0u8; 1500];
let mut receive_packet = move || -> Result<()> {
let num_bytes = (&tun).recv(&mut rec_buf)?;
assert!(num_bytes <= 1500);
let raw_packet = &rec_buf[..num_bytes];
handle_packet(&tcp, &raw_packet)?;
Ok(())
};
loop {
receive_packet().expect("error on NIC read thread");
}
});
Ok(incoming_packets)
}
fn handle_packet(tcp: &tcp::IncomingPackets, raw_packet: &[u8]) -> Result<()> {
eprintln!("RECEIVED");
print::packet_overview(&raw_packet, Direction::Incoming);
eprintln!();
match etherparse::PacketHeaders::from_ip_slice(&raw_packet) {
Err(error) => eprintln!("Error: {}", error),
Ok(packet) => {
// TODO: would be nice to be able to respond to e.g. pings (ICMP)
if let (Some(ip_header), Some(trans_header)) =
(&packet.ip, &packet.transport)
{
match trans_header {
TransportHeader::Tcp(tcp_header) => {
tcp.0
.send(TcpPacket::new(
ip_header.clone(),
tcp_header.clone(),
&packet.payload,
))
.map_err(|e| {
TitError::IncomingTcpChannelClosed(
TcpChannelError::Send(e.into()),
)
})?;
}
TransportHeader::Udp(_header) => {}
}
}
}
}
Ok(())
}
|
use clap::{App, Arg};
use permutator::CartesianProductIterator;
use rayon::iter::ParallelBridge;
use rayon::prelude::ParallelIterator;
use std::fs::OpenOptions;
use std::io::prelude::*;
use std::sync::{Arc, Mutex};
use serde;
use serde::{Serialize, Deserialize};
use pbr::ProgressBar;
use std::collections::BTreeMap;
use regen::{Generator, Result};
#[derive(Debug, Deserialize, PartialEq)]
struct Builder {
parts: Vec<FormatString>,
}
#[derive(Debug, Deserialize, PartialEq)]
#[serde(untagged)]
enum FormatString {
Part(String),
Regex(BTreeMap<String, String>),
}
fn main() {
let matches = App::new("Captain Crunch")
.version("0.1.0")
.author("Thomas Graves <0o0o0o0o0@protonmail.ch>")
.about("Captain Crunch is a modern wordlist generator that lets you specify a collection of character sets and then generate all possible permutations.")
.arg(Arg::new("config")
.short('c')
.long("config")
.value_name("FILE")
.about("Sets the config file that defines how to generate words")
.takes_value(true)
.required(true))
.arg(Arg::new("output")
.short('o')
.long("output")
.value_name("FILE")
.about("Sets the file the wordlist will be written to")
.takes_value(true)
.required(true))
.arg(Arg::new("progress")
.short('p')
.long("progress")
.about("Display progress bar (VERY SLOW FOR LARGE SETS!)")
.takes_value(false)
.required(false))
.get_matches();
let format_strings = if let Some(i) = matches.value_of("config") {
let f = std::fs::File::open(i).unwrap();
let yaml: Builder = serde_yaml::from_reader(f).unwrap();
parse_format_strings(yaml)
} else {
panic!();
};
let mut num_permus = 1;
for arr in format_strings.iter() {
num_permus *= arr.len();
}
// Convert the `Vec<Vec<String>>` into a `Vec<Vec<&str>>`
let tmp: Vec<Vec<&str>> = format_strings.iter()
.map(|list| list.iter().map(AsRef::as_ref).collect::<Vec<&str>>())
.collect();
// Convert the `Vec<Vec<&str>>` into a `Vec<&[&str]>`
let vector_of_arrays: Vec<&[&str]> = tmp.iter()
.map(AsRef::as_ref).collect();
let file = if let Some(i) = matches.value_of("output") {
Arc::new(Mutex::new(OpenOptions::new()
.create(true)
.write(true)
.truncate(true)
.open(i)
.unwrap()))
} else {
panic!()
};
let progress = matches.is_present("progress");
println!("Generating {:?} different permutations", num_permus);
let pb = Arc::new(Mutex::new(ProgressBar::new(num_permus as u64)));
CartesianProductIterator::new(&vector_of_arrays[..]).into_iter().par_bridge().for_each(|p| {
writeln!(&mut file.lock().unwrap(), "{}", p.iter().map(|s| **s).collect::<Vec<&str>>().join(""));
if progress {
pb.lock().unwrap().inc();
}
});
pb.lock().unwrap().finish_print("done");
}
fn parse_format_strings(builder: Builder) -> Vec<Vec<String>> {
let mut all = Vec::new();
for format_string in builder.parts.iter() {
match format_string {
FormatString::Part(part) => {
let options = tokenize(part);
all.push(options);
},
FormatString::Regex(regex) => {
let mut strings = Vec::new();
let mut out = Vec::new();
let options = ®ex["regex"];
let mut gen = Generator::new(&options).unwrap();
while gen.append_next(&mut out).is_some() {
let s = String::from_utf8_lossy(&out);
strings.push(String::from(s));
out.clear();
}
all.push(strings);
}
}
}
all
}
const SEPARATOR: char = '|';
const ESCAPE: char = '\\';
fn tokenize(string: &str) -> Vec<String> {
let mut token = String::new();
let mut tokens: Vec<String> = Vec::new();
let mut chars = string.chars();
while let Some(ch) = chars.next() {
match ch {
SEPARATOR => {
tokens.push(token);
token = String::new();
},
ESCAPE => {
if let Some(next) = chars.next() {
token.push(next);
}
},
_ => token.push(ch),
}
}
tokens.push(token);
tokens
}
|
use core::fmt;
use core::marker::PhantomData;
use conquer_pointer::{MarkedNonNull, MarkedPtr, Null};
use crate::{Maybe, Protected, Shared, Unlinked, Unprotected};
////////////////////////////////////////////////////////////////////////////////////////////////////
// Comparable
////////////////////////////////////////////////////////////////////////////////////////////////////
/// A raw, nullable and potentially marked pointer type this is associated to a
/// [`Reclaimer`][crate::Reclaim] and can be used as the compare argument for
/// a *compare-and-swap* operation.
pub struct Comparable<T, R, const N: usize> {
inner: MarkedPtr<T, N>,
_marker: PhantomData<R>,
}
/********** impl Clone ****************************************************************************/
impl<T, R, const N: usize> Clone for Comparable<T, R, N> {
#[inline]
fn clone(&self) -> Self {
Self { inner: self.inner, _marker: PhantomData }
}
}
/********** impl Copy *****************************************************************************/
impl<T, R, const N: usize> Copy for Comparable<T, R, N> {}
/********** impl inherent *************************************************************************/
impl<T, R, const N: usize> Comparable<T, R, N> {
/// Creates a new `null` pointer.
#[inline]
pub const fn null() -> Self {
Self::new(MarkedPtr::null())
}
/// Returns the inner raw [`MarkedPtr`].
#[inline]
pub const fn into_marked_ptr(self) -> MarkedPtr<T, N> {
self.inner
}
/// Creates a new `Comparable`.
#[inline]
pub(crate) const fn new(inner: MarkedPtr<T, N>) -> Self {
Self { inner, _marker: PhantomData }
}
}
/********** impl Debug ****************************************************************************/
impl<T, R, const N: usize> fmt::Debug for Comparable<T, R, N> {
impl_fmt_debug!(Comparable);
}
/********** impl From (Protected) *****************************************************************/
impl<T, R, const N: usize> From<Protected<'_, T, R, N>> for Comparable<T, R, N> {
#[inline]
fn from(protected: Protected<'_, T, R, N>) -> Self {
Self { inner: protected.inner, _marker: PhantomData }
}
}
/********** impl From (Shared) ********************************************************************/
impl<T, R, const N: usize> From<Shared<'_, T, R, N>> for Comparable<T, R, N> {
#[inline]
fn from(shared: Shared<'_, T, R, N>) -> Self {
Self { inner: shared.inner.into_marked_ptr(), _marker: PhantomData }
}
}
/********** impl From (Unprotected) ***************************************************************/
impl<T, R, const N: usize> From<Unprotected<T, R, N>> for Comparable<T, R, N> {
#[inline]
fn from(unprotected: Unprotected<T, R, N>) -> Self {
Self { inner: unprotected.inner, _marker: PhantomData }
}
}
/********** impl Pointer **************************************************************************/
impl<T, R, const N: usize> fmt::Pointer for Comparable<T, R, N> {
impl_fmt_pointer!();
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// Unlink (trait)
////////////////////////////////////////////////////////////////////////////////////////////////////
/// An internal (not exported) trait for transforming some marked pointer type
/// into an appropriate [`Unlinked`] or `null` variant after a successful
/// *compare-and-swap* operation.
pub trait Unlink {
/// The [`Unlinked`] type.
type Unlinked;
/// Converts `self` into the associated unlinked type.
unsafe fn into_unlinked(self) -> Self::Unlinked;
}
/********** impl Protected ************************************************************************/
impl<T, R, const N: usize> Unlink for Protected<'_, T, R, N> {
type Unlinked = Maybe<Unlinked<T, R, N>>;
#[inline]
unsafe fn into_unlinked(self) -> Self::Unlinked {
Unprotected { inner: self.inner, _marker: PhantomData }.into_unlinked()
}
}
/********** impl Shared ***************************************************************************/
impl<T, R, const N: usize> Unlink for Shared<'_, T, R, N> {
type Unlinked = Unlinked<T, R, N>;
#[inline]
unsafe fn into_unlinked(self) -> Self::Unlinked {
Unlinked { inner: self.inner, _marker: PhantomData }
}
}
/********** impl Unprotected **********************************************************************/
impl<T, R, const N: usize> Unlink for Unprotected<T, R, N> {
type Unlinked = Maybe<Unlinked<T, R, N>>;
#[inline]
unsafe fn into_unlinked(self) -> Self::Unlinked {
match MarkedNonNull::new(self.inner) {
Ok(inner) => Maybe::Some(Unlinked { inner, _marker: PhantomData }),
Err(Null(tag)) => Maybe::Null(tag),
}
}
}
|
/*
* Copyright Stalwart Labs Ltd. See the COPYING
* file at the top-level directory of this distribution.
*
* Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
* https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
* <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
* option. This file may not be copied, modified, or distributed
* except according to those terms.
*/
use crate::{
client::Client,
core::request::{Arguments, Request},
Method,
};
use super::copy::{CopyBlobRequest, CopyBlobResponse};
impl Client {
#[maybe_async::maybe_async]
pub async fn blob_copy(
&self,
from_account_id: impl Into<String>,
blob_id: impl Into<String>,
) -> crate::Result<String> {
let blob_id = blob_id.into();
let mut request = self.build();
request.copy_blob(from_account_id).blob_id(&blob_id);
request
.send_single::<CopyBlobResponse>()
.await?
.copied(&blob_id)
}
}
impl Request<'_> {
#[maybe_async::maybe_async]
pub fn copy_blob(&mut self, from_account_id: impl Into<String>) -> &mut CopyBlobRequest {
self.add_method_call(
Method::CopyBlob,
Arguments::blob_copy(self.params(Method::CopyBlob), from_account_id.into()),
)
.blob_copy_mut()
}
#[maybe_async::maybe_async]
pub async fn send_copy_blob(self) -> crate::Result<CopyBlobResponse> {
self.send_single().await
}
}
|
use crate::prelude::*;
use crate::responses::CreateUserDefinedFunctionResponse;
use azure_core::prelude::*;
use http::StatusCode;
use std::convert::TryInto;
#[derive(Debug, Clone)]
pub struct CreateOrReplaceUserDefinedFunctionBuilder<'a, 'b> {
user_defined_function_client: &'a UserDefinedFunctionClient,
is_create: bool,
user_agent: Option<UserAgent<'b>>,
activity_id: Option<ActivityId<'b>>,
consistency_level: Option<ConsistencyLevel>,
}
impl<'a, 'b> CreateOrReplaceUserDefinedFunctionBuilder<'a, 'b> {
pub(crate) fn new(
user_defined_function_client: &'a UserDefinedFunctionClient,
is_create: bool,
) -> Self {
Self {
user_defined_function_client,
is_create,
user_agent: None,
activity_id: None,
consistency_level: None,
}
}
}
impl<'a, 'b> CreateOrReplaceUserDefinedFunctionBuilder<'a, 'b> {
setters! {
user_agent: &'b str => Some(UserAgent::new(user_agent)),
activity_id: &'b str => Some(ActivityId::new(activity_id)),
consistency_level: ConsistencyLevel => Some(consistency_level),
}
}
impl<'a, 'b> CreateOrReplaceUserDefinedFunctionBuilder<'a, 'b> {
pub async fn execute<B: AsRef<str>>(
&self,
body: B,
) -> crate::Result<CreateUserDefinedFunctionResponse> {
trace!("CreateOrReplaceUserDefinedFunctionBuilder::execute called");
// Create is POST with no name in the URL. Expected return is CREATED.
// See https://docs.microsoft.com/rest/api/cosmos-db/create-a-user-defined-function
// Replace is PUT with name appended to the URL. Expected return is OK.
// See: https://docs.microsoft.com/rest/api/cosmos-db/replace-a-user-defined-function
let req = match self.is_create {
true => self
.user_defined_function_client
.prepare_request(http::Method::POST),
false => self
.user_defined_function_client
.prepare_request_with_user_defined_function_name(http::Method::PUT),
};
// add trait headers
let req = azure_core::headers::add_optional_header(&self.user_agent, req);
let req = azure_core::headers::add_optional_header(&self.activity_id, req);
let req = azure_core::headers::add_optional_header(&self.consistency_level, req);
let req = req.header(http::header::CONTENT_TYPE, "application/json");
#[derive(Debug, Serialize)]
struct Request<'a> {
body: &'a str,
id: &'a str,
}
let request = Request {
body: body.as_ref(),
id: self
.user_defined_function_client
.user_defined_function_name(),
};
let request = azure_core::to_json(&request)?;
let request = req.body(request)?;
let result = if self.is_create {
self.user_defined_function_client
.http_client()
.execute_request_check_status(request, StatusCode::CREATED)
.await?
} else {
self.user_defined_function_client
.http_client()
.execute_request_check_status(request, StatusCode::OK)
.await?
};
Ok(result.try_into()?)
}
}
|
//! Define the main evaluation stack of the Nickel abstract machine and related operations.
//!
//! See [eval](../eval/index.html).
use crate::eval::Closure;
use crate::operation::OperationCont;
use crate::position::RawSpan;
use std::cell::RefCell;
use std::rc::Weak;
/// An element of the stack.
#[derive(Debug)]
pub enum Marker {
/// An argument of an application.
Arg(Closure, Option<RawSpan>),
/// A thunk, which is pointer to a mutable memory cell to be updated.
Thunk(Weak<RefCell<Closure>>),
/// The continuation of a primitive operation.
Cont(
OperationCont,
usize, /*callStack size*/
Option<RawSpan>, /*position span of the operation*/
),
}
impl Marker {
pub fn is_arg(&self) -> bool {
match *self {
Marker::Arg(_, _) => true,
Marker::Thunk(_) => false,
Marker::Cont(_, _, _) => false,
}
}
pub fn is_thunk(&self) -> bool {
match *self {
Marker::Arg(_, _) => false,
Marker::Thunk(_) => true,
Marker::Cont(_, _, _) => false,
}
}
pub fn is_cont(&self) -> bool {
match *self {
Marker::Arg(_, _) => false,
Marker::Thunk(_) => false,
Marker::Cont(_, _, _) => true,
}
}
}
/// The evaluation stack.
#[derive(Debug)]
pub struct Stack(Vec<Marker>);
impl IntoIterator for Stack {
type Item = Marker;
type IntoIter = ::std::vec::IntoIter<Marker>;
fn into_iter(self) -> Self::IntoIter {
self.0.into_iter()
}
}
impl Stack {
pub fn new() -> Stack {
Stack(Vec::new())
}
/// Count the number of consecutive elements satisfying `pred` from the top of the stack.
fn count<P>(&self, pred: P) -> usize
where
P: Fn(&Marker) -> bool,
{
let mut count = 0;
for marker in self.0.iter().rev() {
if pred(marker) {
count += 1;
} else {
break;
}
}
count
}
/// Count the number of arguments at the top of the stack.
pub fn count_args(&self) -> usize {
Stack::count(self, Marker::is_arg)
}
pub fn push_arg(&mut self, arg: Closure, pos: Option<RawSpan>) {
self.0.push(Marker::Arg(arg, pos))
}
pub fn push_thunk(&mut self, thunk: Weak<RefCell<Closure>>) {
self.0.push(Marker::Thunk(thunk))
}
pub fn push_op_cont(&mut self, cont: OperationCont, len: usize, pos: Option<RawSpan>) {
self.0.push(Marker::Cont(cont, len, pos))
}
pub fn pop_arg(&mut self) -> Option<(Closure, Option<RawSpan>)> {
match self.0.pop() {
Some(Marker::Arg(arg, pos)) => Some((arg, pos)),
Some(m) => {
self.0.push(m);
None
}
_ => None,
}
}
pub fn pop_thunk(&mut self) -> Option<Weak<RefCell<Closure>>> {
match self.0.pop() {
Some(Marker::Thunk(thunk)) => Some(thunk),
Some(m) => {
self.0.push(m);
None
}
_ => None,
}
}
pub fn pop_op_cont(&mut self) -> Option<(OperationCont, usize, Option<RawSpan>)> {
match self.0.pop() {
Some(Marker::Cont(cont, len, pos)) => Some((cont, len, pos)),
Some(m) => {
self.0.push(m);
None
}
_ => None,
}
}
/// Check if the top element is an argument.
pub fn is_top_thunk(&self) -> bool {
self.0.last().map(Marker::is_thunk).unwrap_or(false)
}
/// Check if the top element is an operation continuation.
pub fn is_top_cont(&self) -> bool {
self.0.last().map(Marker::is_cont).unwrap_or(false)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::term::{Term, UnaryOp};
use std::rc::Rc;
impl Stack {
/// Count the number of thunks at the top of the stack.
pub fn count_thunks(&self) -> usize {
Stack::count(self, Marker::is_thunk)
}
/// Count the number of operation continuation at the top of the stack.
pub fn count_conts(&self) -> usize {
Stack::count(self, Marker::is_cont)
}
}
fn some_closure() -> Closure {
Closure::atomic_closure(Term::Bool(true).into())
}
fn some_cont() -> OperationCont {
OperationCont::Op1(UnaryOp::IsZero(), None)
}
fn some_arg_marker() -> Marker {
Marker::Arg(some_closure(), None)
}
fn some_thunk_marker() -> Marker {
let rc = Rc::new(RefCell::new(some_closure()));
Marker::Thunk(Rc::downgrade(&rc))
}
fn some_cont_marker() -> Marker {
Marker::Cont(some_cont(), 42, None)
}
#[test]
fn marker_differentiates() {
assert!(some_arg_marker().is_arg());
assert!(some_thunk_marker().is_thunk());
assert!(some_cont_marker().is_cont());
}
#[test]
fn pushing_and_poping_args() {
let mut s = Stack::new();
assert_eq!(0, s.count_args());
s.push_arg(some_closure(), None);
s.push_arg(some_closure(), None);
assert_eq!(2, s.count_args());
assert_eq!(some_closure(), s.pop_arg().expect("Already checked").0);
assert_eq!(1, s.count_args());
}
#[test]
fn pushing_and_poping_thunks() {
let mut s = Stack::new();
assert_eq!(0, s.count_thunks());
s.push_thunk(Rc::downgrade(&Rc::new(RefCell::new(some_closure()))));
s.push_thunk(Rc::downgrade(&Rc::new(RefCell::new(some_closure()))));
assert_eq!(2, s.count_thunks());
s.pop_thunk().expect("Already checked");
assert_eq!(1, s.count_thunks());
}
#[test]
fn pushing_and_poping_conts() {
let mut s = Stack::new();
assert_eq!(0, s.count_conts());
s.push_op_cont(some_cont(), 3, None);
s.push_op_cont(some_cont(), 4, None);
assert_eq!(2, s.count_conts());
assert_eq!(
(some_cont(), 4, None),
s.pop_op_cont().expect("Already checked")
);
assert_eq!(1, s.count_conts());
}
}
|
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
const BUCKET_COUNT: usize = 16;
const LIST_LE: [f64; BUCKET_COUNT-1] = [0.5, 1.0, 2.0, 5.0, 10.0, 20.0, 50.0, 100.0, 200.0, 500.0, 1000.0, 2000.0, 5000.0, 10000.0, 20000.0];
#[derive(Serialize, Deserialize)]
pub struct MetricsValue {
value: usize,
tags: HashMap<String, String>,
}
impl MetricsValue {
pub fn new(value: usize, tags: HashMap<String, String>) -> Self {
MetricsValue { value, tags }
}
}
#[derive(Serialize, Deserialize, Copy, Clone, Debug)]
pub struct CommandCounters {
pub count: u128,
pub duration_ms_sum: u128,
pub duration_ms_bucket: [u128; BUCKET_COUNT],
}
impl CommandCounters {
pub fn new() -> Self {
CommandCounters {count: 0, duration_ms_sum: 0, duration_ms_bucket: [0; BUCKET_COUNT]}
}
pub fn add(&mut self, duration: u128) {
self.count += 1;
self.duration_ms_sum += duration;
self.add_buckets(duration);
}
fn add_buckets(&mut self, duration: u128) {
for (le_index, le_value) in LIST_LE.iter().enumerate() {
if duration <= *le_value as u128 {
self.duration_ms_bucket[le_index] += 1;
}
}
self.duration_ms_bucket[self.duration_ms_bucket.len()-1] += 1;
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_counters_are_initialized_as_zeros() {
let command_counters = CommandCounters::new();
assert_eq!(command_counters.count, 0);
assert_eq!(command_counters.duration_ms_sum, 0);
assert_eq!(command_counters.duration_ms_bucket, [0; BUCKET_COUNT]);
}
}
|
pub use field_mask::{BitwiseWrap, DeserializeFieldMaskError, FieldMask, FieldMaskInput};
pub use fieldmask_derive::Maskable;
pub use maskable::{DeserializeMaskError, Maskable, OptionMaskable, SelfMaskable};
mod field_mask;
mod maskable;
|
#![feature(map_first_last)]
pub mod row;
pub mod table;
pub use row::Row;
pub use table::Table;
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
}
|
use nom::{alphanumeric1, digit1, multispace0, multispace1};
use crate::table::Chamber;
#[allow(unreachable_pub)]
#[derive(Debug, PartialEq, Eq)]
pub enum Statement {
Select(SelectStatement),
Insert(InsertStatement),
}
#[allow(unreachable_pub)]
#[derive(Debug, PartialEq, Eq)]
crate enum ColumnClause {
Star,
Names(Vec<String>),
}
#[allow(unreachable_pub)]
#[derive(Debug, PartialEq, Eq)]
pub struct WhereClause {
crate column_name: String,
// XXX TODO: this actually needs to be a `Chamber`
// and how will we detect Integer vs. Key?!
crate value: Chamber,
}
#[allow(unreachable_pub)]
#[derive(Debug, PartialEq, Eq)]
pub struct SelectStatement {
crate column_names: ColumnClause,
crate table_name: String,
crate where_clause: Option<WhereClause>,
}
named!(string_literal <&str, Chamber>,
do_parse!(
value: delimited!(
char!('\''),
take_until!("'"),
char!('\'')
) >>
(Chamber::String(value.to_owned()))
)
);
named!(integer_literal <&str, Chamber>,
do_parse!(
value: digit1 >>
(Chamber::Integer(value.parse().unwrap()))
)
);
named!(literal <&str, Chamber>,
alt!(integer_literal | string_literal)
);
named!(parse_where_clause<&str, WhereClause>,
do_parse!(
tag!("WHERE") >>
multispace1 >>
column_name: alphanumeric1 >>
multispace0 >>
tag!("=") >>
multispace0 >>
value: literal >>
(WhereClause { column_name: column_name.to_owned(),
value })
)
);
named!(parse_star<&str, ColumnClause>,
do_parse!(
tag!("*") >>
(ColumnClause::Star)
)
);
named!(parse_select_column_names<&str, ColumnClause>,
do_parse!(
names: separated_list!(commaspace, alphanumeric1) >>
(ColumnClause::Names(names.iter().map(|name| {
name.clone().to_owned() // really?
}).collect()))
)
);
named!(parse_select_column_clause<&str, ColumnClause>,
alt!(parse_star | parse_select_column_names)
);
named!(parse_select_statement<&str, Statement>,
do_parse!(
tag!("SELECT") >>
multispace1 >>
column_names: parse_select_column_clause >>
multispace1 >>
tag!("FROM") >>
multispace1 >>
table_name: alphanumeric1 >>
multispace1 >>
where_clause: opt!(parse_where_clause) >>
multispace0 >>
tag!(";") >>
(Statement::Select(
SelectStatement { column_names,
table_name: table_name.to_string(),
where_clause }
)
)
)
);
#[allow(unreachable_pub)]
#[derive(Debug, PartialEq, Eq)]
pub struct InsertStatement {
crate table_name: String,
crate values: Vec<Chamber>,
}
named!(commaspace <&str, char>,
delimited!(
multispace0,
char!(','),
multispace0
)
);
named!(parse_values <&str, Vec<Chamber>>,
delimited!(
char!('('),
separated_list!(commaspace, literal),
char!(')')
)
);
named!(parse_insert_statement<&str, Statement>,
do_parse!(
tag!("INSERT") >>
multispace1 >>
tag!("INTO") >>
multispace1 >>
table_name: alphanumeric1 >>
multispace1 >>
tag!("VALUES") >>
multispace1 >>
values: parse_values >>
multispace0 >>
tag!(";") >>
(Statement::Insert(InsertStatement {
table_name: table_name.to_string(),
values
}))
)
);
// nom doesn't know about `pub(crate)`/`crate` (Issue #807, PR #792)
named!(pub parse_statement<&str, Statement>,
alt!(parse_select_statement | parse_insert_statement)
);
#[cfg(test)]
mod tests {
use super::*;
use crate::table::Chamber;
#[test]
fn concerning_parsing_a_where_clause_for_an_integer_column() {
assert_eq!(
parse_where_clause("WHERE year = 2018 "),
Ok((
" ",
WhereClause {
column_name: "year".to_owned(),
value: Chamber::Integer(2018)
}
))
);
}
#[test]
fn concerning_parsing_a_select_star_statement() {
assert_eq!(
parse_select_statement("SELECT * FROM books WHERE year = 2018;"),
Ok((
"",
Statement::Select(SelectStatement {
column_names: ColumnClause::Star,
table_name: "books".to_owned(),
where_clause: Some(WhereClause {
column_name: "year".to_owned(),
value: Chamber::Integer(2018)
}),
})
))
);
}
#[test]
fn concerning_parsing_a_whereless_select_statement() {
assert_eq!(
parse_select_statement("SELECT * FROM books ;"),
Ok((
"",
Statement::Select(SelectStatement {
column_names: ColumnClause::Star,
table_name: "books".to_owned(),
where_clause: None
})
))
);
}
#[test]
fn concerning_parsing_a_select_column_names_statement() {
assert_eq!(
parse_select_statement(
"SELECT title, author FROM books WHERE year = 2018;"
),
Ok((
"",
Statement::Select(SelectStatement {
column_names: ColumnClause::Names(vec![
"title".to_owned(),
"author".to_owned(),
]),
table_name: "books".to_owned(),
where_clause: Some(WhereClause {
column_name: "year".to_owned(),
value: Chamber::Integer(2018),
}),
})
))
);
}
#[test]
fn concerning_the_parsing_of_literals() {
assert_eq!(
string_literal("'hello SQL world'"),
Ok((
"",
Chamber::String("hello SQL world".to_owned())
))
);
assert_eq!(
literal("'hello SQL world'"),
Ok((
"",
Chamber::String("hello SQL world".to_owned())
))
);
assert_eq!(
integer_literal("9001 "),
Ok((" ", Chamber::Integer(9001)))
);
assert_eq!(
literal("9001 "),
Ok((" ", Chamber::Integer(9001)))
)
}
#[test]
fn concerning_the_parsing_of_value_lists() {
assert_eq!(
parse_values("(1, 'Structure and Interpretation')"),
Ok((
"",
vec![
Chamber::Integer(1),
Chamber::String("Structure and Interpretation".to_owned()),
]
))
)
}
#[test]
fn concerning_parsing_an_insert_integers_statement() {
assert_eq!(
parse_insert_statement("INSERT INTO prices VALUES (120, 8401);"),
Ok((
"",
Statement::Insert(InsertStatement {
table_name: "prices".to_owned(),
values: vec![
Chamber::Integer(120),
Chamber::Integer(8401),
],
})
))
);
}
#[test]
fn concerning_parsing_an_insert_statement() {
assert_eq!(
parse_insert_statement(
"INSERT INTO books VALUES \
('Mathematical Analysis: A Concise Introduction', 2007);"
),
Ok((
"",
Statement::Insert(InsertStatement {
table_name: "books".to_owned(),
values: vec![
Chamber::String(
"Mathematical Analysis: A Concise Introduction"
.to_owned(),
),
Chamber::Integer(2007),
],
})
))
);
}
}
|
use std::net::SocketAddr;
pub const CLIENT_NAME: &str = "srwc";
pub const VERSION: &str = "0.1.0";
pub const DEFAULT_TYPE: ServerType = ServerType::HTTP;
pub const DEFAULT_ADDR: &str = "0.0.0.0:1417";
pub const DEFAULT_STORAGE: &str = "/tmp/srwc";
pub const BUFFER_SIZE: usize = 8;
pub const ACK_MESSAGE: &str = "ACK";
pub const PREPARE_TRANSFER_MESSAGE: &str = "prepare transfer file";
pub const CANNOT_FIND_FILE_MESSAGE: &str = "cannot find file";
pub const REMOVED_OK_MESSAGE: &str = "removed ok";
pub const REMOVED_NOK_MESSAGE: &str = "removed nok";
pub const GRPC_METADATA_FILENAME: &str = "filename";
pub const GRPC_URL_SCHEMA: &str = "http://";
#[derive(Debug)]
pub enum ServerType {
HTTP,
HTTPS,
GRPC,
}
#[derive(Debug)]
pub struct ClientConfig {
pub server_type: ServerType,
pub address: SocketAddr,
pub storage: String,
}
impl ClientConfig {
pub fn new() -> Self {
ClientConfig {
server_type: DEFAULT_TYPE,
address: DEFAULT_ADDR.parse().expect("Unable to parse socket address"),
storage: DEFAULT_STORAGE.to_string(),
}
}
}
#[derive(Debug)]
pub struct ServerFile {
pub fullpath: String,
pub name: String,
pub size: u64,
}
impl ServerFile {
pub fn new() -> Self {
ServerFile {
fullpath: String::from(""),
name: String::from(""),
size: 0,
}
}
}
|
extern crate rand;
extern crate swim;
use std::io::prelude::*;
use std::net::TcpListener;
use std::net::TcpStream;
use std::fs::File;
use rand::{thread_rng, Rng};
fn main() {
let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
let lanes = 10;
let pool = swim::Pool::new(lanes);
for stream in listener.incoming() {
let stream = stream.unwrap();
let lane_id = thread_rng().gen_range(0, lanes);
pool.send(lane_id, || {
handle_connection(stream)
});
}
fn handle_connection(mut stream: TcpStream) {
let mut buffer = [0; 512];
stream.read(&mut buffer).unwrap();
println!("{}", String::from_utf8_lossy(&buffer[..]));
let mut file = File::open("hello.html").unwrap();
let mut contents = String::new();
file.read_to_string(&mut contents).unwrap();
let response = format!("HTTP/1.1 200 OK\r\n\r\n{}", contents);
stream.write(response.as_bytes()).unwrap();
stream.flush().unwrap();
}
}
|
mod tag_components;
pub mod for_characters;
pub mod for_ground_entities;
pub mod misc;
pub mod physics;
pub use self::tag_components::*;
|
//!
//! Echo server - poppo.
//!
//! A simple server that writes "poppo\n" when reads any.
//!
//! cd C:\Users\むずでょ\source\repos\practice-rust\echo-server
//! cargo check
//! cargo build
//! cargo run
//!
//! See: [Rustにっき/8日目・TCPサーバ](https://cha-shu00.hatenablog.com/entry/2019/03/02/174532)
//!
extern crate serde_derive;
extern crate toml;
use std::io::{BufRead, BufReader, BufWriter, Error, Write};
use std::net::{TcpListener, TcpStream, ToSocketAddrs};
use std::thread;
mod config;
use config::*;
fn main() {
match read_toml("./config.toml".to_string()) {
Ok(config) => {
let host = config.host.unwrap();
let host_text = format!("{}:{}", host.domain.unwrap(), host.port.unwrap());
println!("Host | {}", host_text);
let mut addrs = host_text.to_socket_addrs().unwrap();
// Change to ip v4.
if let Some(addr) = addrs.find(|x| (*x).is_ipv4()) {
// Server standup | 127.0.0.1:9696
println!("Server standup | {}", addr);
// Wait for connection.
let listener = TcpListener::bind(addr).expect("Error. failed to bind.");
for streams in listener.incoming() {
match streams {
Err(e) => eprintln!("error: {}", e),
Ok(stream) => {
// Create the thread.
thread::spawn(move || {
handle_client(stream)
.unwrap_or_else(|error| eprintln!("{:?}", error));
});
}
}
}
} else {
eprintln!("Invalid Host:Port Number");
}
}
Err(err) => panic!(err),
}
}
fn handle_client(stream: TcpStream) -> Result<(), Error> {
println!("Connection from | {}", stream.peer_addr()?);
// Buffering.
let mut reader = BufReader::new(&stream);
let mut writer = BufWriter::new(&stream);
let mut line = String::new();
loop {
println!("Info | Waiting...");
if let Err(err) = reader.read_line(&mut line) {
// panic!("error during receive a line: {}", err);
println!("Error | {}", err);
}
println!("Read | {}", line);
if line == "quit" {
return Ok(());
}
line.clear();
// 改行を付けないと、受信側が 受信完了しません。
let msg = "poppo";
println!("Write | {}", msg);
writer.write(format!("{}\n", msg).as_bytes())?;
writer.flush()?;
}
}
|
#![ allow (unused_parens) ]
extern crate clap;
extern crate output;
extern crate rand;
extern crate rustc_serialize;
extern crate rzbackup;
use std::process;
use rzbackup::client::*;
use rzbackup::commands::*;
use rzbackup::convert::*;
use rzbackup::misc::*;
use rzbackup::server::*;
fn main () {
let output =
output::open ();
let commands = vec! [
client_command (),
convert_command (),
decrypt_command (),
restore_command (),
server_command (),
];
let arguments =
parse_arguments (
& commands);
match arguments.perform (
& output,
) {
Ok (true) => {
output.flush ();
process::exit (0);
},
Ok (false) => {
output.flush ();
process::exit (1);
},
Err (error) => {
output.message (
error);
output.flush ();
process::exit (1);
}
}
}
fn parse_arguments (
commands: & [Box <Command>],
) -> Box <CommandArguments> {
let mut clap_application =
commands.iter ().fold (
clap::App::new ("RZBackup")
.version (rzbackup::VERSION)
.author (rzbackup::AUTHOR)
.about ("Backup tool compatible with ZBackup"),
|clap_application, command|
clap_application.subcommand (
command.clap_subcommand (),
)
);
let clap_matches =
clap_application.clone ().get_matches ();
commands.iter ().map (
|command|
clap_matches.subcommand_matches (
command.name (),
).map (
|clap_matches|
command.clap_arguments_parse (
clap_matches,
)
)
).find (
|clap_matches|
clap_matches.is_some ()
).unwrap_or_else (|| {
println! ("");
clap_application.print_help ().unwrap ();
println! ("");
println! ("");
process::exit (0);
}).unwrap ()
}
// ex: noet ts=4 filetype=rust
|
use futures::{Poll, Async, AsyncSink, StartSend};
use futures::stream::Stream;
use futures::sink::Sink;
pub struct Serial;
impl Stream for Serial {
type Item = u8;
type Error = ();
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
#[allow(unused_unsafe)]
let v = unsafe { sys::serial_read() };
if v < 0 {
Ok(Async::NotReady)
} else {
Ok(Async::Ready(Some(v as u8)))
}
}
}
impl Sink for Serial {
type SinkItem = u8;
type SinkError = ();
fn start_send(&mut self, item: Self::SinkItem) -> StartSend<Self::SinkItem, Self::SinkError> {
// TODO: make async
unsafe {
sys::serial_write(item);
}
Ok(AsyncSink::Ready)
}
fn poll_complete(&mut self) -> Poll<(), Self::SinkError> {
Ok(Async::Ready(()))
}
fn close(&mut self) -> Poll<(), Self::SinkError> {
self.poll_complete()
}
}
mod sys {
extern {
pub fn serial_write(b: u8) -> u8;
}
#[cfg(target_arch = "msp430")]
pub mod platform {
extern {
pub fn serial_read() -> i16;
}
}
#[cfg(target_arch = "arm")]
pub mod platform {
extern {
pub fn serial_read() -> i32;
}
}
#[cfg(not(any(target_arch = "arm", target_arch = "msp430")))]
pub mod platform {
pub fn serial_read() -> i32 { unimplemented!() }
}
pub use self::platform::*;
}
|
use zero::std_types::*;
/* STM32F4xx_StdPeriph_Driver
*/
/* GPIO
*/
/* Exported types ------------------------------------------------------------*/
macro_rules! IS_GPIO_ALL_PERIPH {($PERIPH:ident) => ((($PERIPH) == GPIOA) ||
(($PERIPH) == GPIOB) ||
(($PERIPH) == GPIOC) ||
(($PERIPH) == GPIOD) ||
(($PERIPH) == GPIOE) ||
(($PERIPH) == GPIOF) ||
(($PERIPH) == GPIOG) ||
(($PERIPH) == GPIOH) ||
(($PERIPH) == GPIOI));}
/*
* GPIO Configuration Mode enumeration
*/
pub type GPIOMode_TypeDef = c_uint;
macro_rules! GPIO_Mode_IN {() => (0x00u32 as c_uint);} /*< GPIO Input Mode */
macro_rules! GPIO_Mode_OUT {() => (0x01u32 as c_uint);} /*< GPIO Output Mode */
macro_rules! GPIO_Mode_AF {() => (0x02u32 as c_uint);} /*< GPIO Alternate function Mode */
macro_rules! GPIO_Mode_AN {() => (0x03u32 as c_uint);} /*< GPIO Analog Mode */
macro_rules! IS_GPIO_MODE {($MODE:ident) => ((($MODE) == GPIO_Mode_IN!()) || (($MODE) == GPIO_Mode_OUT!()) ||
(($MODE) == GPIO_Mode_AF!())|| (($MODE) == GPIO_Mode_AN!()));}
/*
* GPIO Output type enumeration
*/
pub type GPIOOType_TypeDef = c_uint;
macro_rules! GPIO_OType_PP {() => (0x00u32 as c_uint);}
macro_rules! GPIO_OType_OD {() => (0x01u32 as c_uint);}
macro_rules! IS_GPIO_OTYPE {($OTYPE:ident) => ((($OTYPE) == GPIO_OType_PP!()) || (($OTYPE) == GPIO_OType_OD!()));}
/*
* GPIO Output Maximum frequency enumeration
*/
pub type GPIOSpeed_TypeDef = c_uint;
macro_rules! GPIO_Speed_2MHz {() => (0x00u32 as c_uint);} /*< Low speed */
macro_rules! GPIO_Speed_25MHz {() => (0x01u32 as c_uint);} /*< Medium speed */
macro_rules! GPIO_Speed_50MHz {() => (0x02u32 as c_uint);} /*< Fast speed */
macro_rules! GPIO_Speed_100MHz {() => (0x03u32 as c_uint);} /*< High speed on 30 pF (80 MHz Output max speed on 15 pF) */
macro_rules! IS_GPIO_SPEED {($SPEED:ident) => ((($SPEED) == GPIO_Speed_2MHz!()) || (($SPEED) == GPIO_Speed_25MHz!()) ||
(($SPEED) == GPIO_Speed_50MHz!())|| (($SPEED) == GPIO_Speed_100MHz!()));}
/*
* GPIO Configuration PullUp PullDown enumeration
*/
pub type GPIOPuPd_TypeDef = c_uint;
macro_rules! GPIO_PuPd_NOPULL {() => (0x00u32 as c_uint);}
macro_rules! GPIO_PuPd_UP {() => (0x01u32 as c_uint);}
macro_rules! GPIO_PuPd_DOWN {() => (0x02u32 as c_uint);}
macro_rules! IS_GPIO_PUPD {($PUPD:ident) => ((($PUPD) == GPIO_PuPd_NOPULL!()) || (($PUPD) == GPIO_PuPd_UP!()) ||
(($PUPD) == GPIO_PuPd_DOWN!()));}
/*
* GPIO Bit SET and Bit RESET enumeration
*/
pub type BitAction = c_uint;
macro_rules! Bit_RESET {() => (0u32 as c_uint);}
macro_rules! Bit_SET {() => (1u32 as c_uint);}
macro_rules! IS_GPIO_BIT_ACTION {($ACTION:ident) => ((($ACTION) == Bit_RESET!()) || (($ACTION) == Bit_SET!()));}
/*
* GPIO Init structure definition
*/
pub struct GPIO_InitTypeDef {
pub GPIO_Pin :uint32_t, /*< Specifies the GPIO pins to be configured.
This parameter can be any value of GPIO_pins_define */
pub GPIO_Mode :GPIOMode_TypeDef, /*< Specifies the operating mode for the selected pins.
This parameter can be a value of GPIOMode_TypeDef */
pub GPIO_Speed :GPIOSpeed_TypeDef, /*< Specifies the speed for the selected pins.
This parameter can be a value of GPIOSpeed_TypeDef */
pub GPIO_OType :GPIOOType_TypeDef, /*< Specifies the operating output type for the selected pins.
This parameter can be a value of GPIOOType_TypeDef */
pub GPIO_PuPd :GPIOPuPd_TypeDef /*< Specifies the operating Pull-up/Pull down for the selected pins.
This parameter can be a value of GPIOPuPd_TypeDef */
}
/* Exported constants --------------------------------------------------------*/
/* GPIO_Exported_Constants
*/
/* GPIO_pins_define
*/
macro_rules! GPIO_Pin_0 {() => (0x0001u16 as uint16_t);} /* Pin 0 selected */
macro_rules! GPIO_Pin_1 {() => (0x0002u16 as uint16_t);} /* Pin 1 selected */
macro_rules! GPIO_Pin_2 {() => (0x0004u16 as uint16_t);} /* Pin 2 selected */
macro_rules! GPIO_Pin_3 {() => (0x0008u16 as uint16_t);} /* Pin 3 selected */
macro_rules! GPIO_Pin_4 {() => (0x0010u16 as uint16_t);} /* Pin 4 selected */
macro_rules! GPIO_Pin_5 {() => (0x0020u16 as uint16_t);} /* Pin 5 selected */
macro_rules! GPIO_Pin_6 {() => (0x0040u16 as uint16_t);} /* Pin 6 selected */
macro_rules! GPIO_Pin_7 {() => (0x0080u16 as uint16_t);} /* Pin 7 selected */
macro_rules! GPIO_Pin_8 {() => (0x0100u16 as uint16_t);} /* Pin 8 selected */
macro_rules! GPIO_Pin_9 {() => (0x0200u16 as uint16_t);} /* Pin 9 selected */
macro_rules! GPIO_Pin_10 {() => (0x0400u16 as uint16_t);} /* Pin 10 selected */
macro_rules! GPIO_Pin_11 {() => (0x0800u16 as uint16_t);} /* Pin 11 selected */
macro_rules! GPIO_Pin_12 {() => (0x1000u16 as uint16_t);} /* Pin 12 selected */
macro_rules! GPIO_Pin_13 {() => (0x2000u16 as uint16_t);} /* Pin 13 selected */
macro_rules! GPIO_Pin_14 {() => (0x4000u16 as uint16_t);} /* Pin 14 selected */
macro_rules! GPIO_Pin_15 {() => (0x8000u16 as uint16_t);} /* Pin 15 selected */
macro_rules! GPIO_Pin_All {() => (0xFFFFu16 as uint16_t);} /* All pins selected */
macro_rules! IS_GPIO_PIN {($PIN:ident) => (((($PIN) & (0x00u16 as uint16_t)) == 0x00) && ((PIN) != (0x00u16 as uint16_t)));}
macro_rules! IS_GET_GPIO_PIN {($PIN:ident) => ((($PIN) == GPIO_Pin_0!()) ||
(($PIN) == GPIO_Pin_1!()) ||
(($PIN) == GPIO_Pin_2!()) ||
(($PIN) == GPIO_Pin_3!()) ||
(($PIN) == GPIO_Pin_4!()) ||
(($PIN) == GPIO_Pin_5!()) ||
(($PIN) == GPIO_Pin_6!()) ||
(($PIN) == GPIO_Pin_7!()) ||
(($PIN) == GPIO_Pin_8!()) ||
(($PIN) == GPIO_Pin_9!()) ||
(($PIN) == GPIO_Pin_10!()) ||
(($PIN) == GPIO_Pin_11!()) ||
(($PIN) == GPIO_Pin_12!()) ||
(($PIN) == GPIO_Pin_13!()) ||
(($PIN) == GPIO_Pin_14!()) ||
(($PIN) == GPIO_Pin_15!()));}
/* GPIO_Pin_sources
*/
macro_rules! GPIO_PinSource0 {() => (0x00u8 as uint8_t);}
macro_rules! GPIO_PinSource1 {() => (0x01u8 as uint8_t);}
macro_rules! GPIO_PinSource2 {() => (0x02u8 as uint8_t);}
macro_rules! GPIO_PinSource3 {() => (0x03u8 as uint8_t);}
macro_rules! GPIO_PinSource4 {() => (0x04u8 as uint8_t);}
macro_rules! GPIO_PinSource5 {() => (0x05u8 as uint8_t);}
macro_rules! GPIO_PinSource6 {() => (0x06u8 as uint8_t);}
macro_rules! GPIO_PinSource7 {() => (0x07u8 as uint8_t);}
macro_rules! GPIO_PinSource8 {() => (0x08u8 as uint8_t);}
macro_rules! GPIO_PinSource9 {() => (0x09u8 as uint8_t);}
macro_rules! GPIO_PinSource10 {() => (0x0Au8 as uint8_t);}
macro_rules! GPIO_PinSource11 {() => (0x0Bu8 as uint8_t);}
macro_rules! GPIO_PinSource12 {() => (0x0Cu8 as uint8_t);}
macro_rules! GPIO_PinSource13 {() => (0x0Du8 as uint8_t);}
macro_rules! GPIO_PinSource14 {() => (0x0Eu8 as uint8_t);}
macro_rules! GPIO_PinSource15 {() => (0x0Fu8 as uint8_t);}
macro_rules! IS_GPIO_PIN_SOURCE {($PINSOURCE:ident) => ((($PINSOURCE) == GPIO_PinSource0!()) ||
(($PINSOURCE) == GPIO_PinSource1!()) ||
(($PINSOURCE) == GPIO_PinSource2!()) ||
(($PINSOURCE) == GPIO_PinSource3!()) ||
(($PINSOURCE) == GPIO_PinSource4!()) ||
(($PINSOURCE) == GPIO_PinSource5!()) ||
(($PINSOURCE) == GPIO_PinSource6!()) ||
(($PINSOURCE) == GPIO_PinSource7!()) ||
(($PINSOURCE) == GPIO_PinSource8!()) ||
(($PINSOURCE) == GPIO_PinSource9!()) ||
(($PINSOURCE) == GPIO_PinSource10!()) ||
(($PINSOURCE) == GPIO_PinSource11!()) ||
(($PINSOURCE) == GPIO_PinSource12!()) ||
(($PINSOURCE) == GPIO_PinSource13!()) ||
(($PINSOURCE) == GPIO_PinSource14!()) ||
(($PINSOURCE) == GPIO_PinSource15!()));}
/* GPIO_Alternat_function_selection_define
*/
/*
* AF 0 selection
*/
macro_rules! GPIO_AF_RTC_50Hz {() => (0x00u8 as uint8_t);} /* RTC_50Hz Alternate Function mapping */
macro_rules! GPIO_AF_MCO {() => (0x00u8 as uint8_t);} /* MCO (MCO1 and MCO2) Alternate Function mapping */
macro_rules! GPIO_AF_TAMPER {() => (0x00u8 as uint8_t);} /* TAMPER (TAMPER_1 and TAMPER_2) Alternate Function mapping */
macro_rules! GPIO_AF_SWJ {() => (0x00u8 as uint8_t);} /* SWJ (SWD and JTAG) Alternate Function mapping */
macro_rules! GPIO_AF_TRACE {() => (0x00u8 as uint8_t);} /* TRACE Alternate Function mapping */
/*
* AF 1 selection
*/
macro_rules! GPIO_AF_TIM1 {() => (0x01u8 as uint8_t);} /* TIM1 Alternate Function mapping */
macro_rules! GPIO_AF_TIM2 {() => (0x01u8 as uint8_t);} /* TIM2 Alternate Function mapping */
/*
* AF 2 selection
*/
macro_rules! GPIO_AF_TIM3 {() => (0x02u8 as uint8_t);} /* TIM3 Alternate Function mapping */
macro_rules! GPIO_AF_TIM4 {() => (0x02u8 as uint8_t);} /* TIM4 Alternate Function mapping */
macro_rules! GPIO_AF_TIM5 {() => (0x02u8 as uint8_t);} /* TIM5 Alternate Function mapping */
/*
* AF 3 selection
*/
macro_rules! GPIO_AF_TIM8 {() => (0x03u8 as uint8_t);} /* TIM8 Alternate Function mapping */
macro_rules! GPIO_AF_TIM9 {() => (0x03u8 as uint8_t);} /* TIM9 Alternate Function mapping */
macro_rules! GPIO_AF_TIM10 {() => (0x03u8 as uint8_t);} /* TIM10 Alternate Function mapping */
macro_rules! GPIO_AF_TIM11 {() => (0x03u8 as uint8_t);} /* TIM11 Alternate Function mapping */
/*
* AF 4 selection
*/
macro_rules! GPIO_AF_I2C1 {() => (0x04u8 as uint8_t);} /* I2C1 Alternate Function mapping */
macro_rules! GPIO_AF_I2C2 {() => (0x04u8 as uint8_t);} /* I2C2 Alternate Function mapping */
macro_rules! GPIO_AF_I2C3 {() => (0x04u8 as uint8_t);} /* I2C3 Alternate Function mapping */
/*
* AF 5 selection
*/
macro_rules! GPIO_AF_SPI1 {() => (0x05u8 as uint8_t);} /* SPI1 Alternate Function mapping */
macro_rules! GPIO_AF_SPI2 {() => (0x05u8 as uint8_t);} /* SPI2/I2S2 Alternate Function mapping */
/*
* AF 6 selection
*/
macro_rules! GPIO_AF_SPI3 {() => (0x06u8 as uint8_t);} /* SPI3/I2S3 Alternate Function mapping */
/*
* AF 7 selection
*/
macro_rules! GPIO_AF_USART1 {() => (0x07u8 as uint8_t);} /* USART1 Alternate Function mapping */
macro_rules! GPIO_AF_USART2 {() => (0x07u8 as uint8_t);} /* USART2 Alternate Function mapping */
macro_rules! GPIO_AF_USART3 {() => (0x07u8 as uint8_t);} /* USART3 Alternate Function mapping */
macro_rules! GPIO_AF_I2S3ext {() => (0x07u8 as uint8_t);} /* I2S3ext Alternate Function mapping */
/*
* AF 8 selection
*/
macro_rules! GPIO_AF_UART4 {() => (0x08u8 as uint8_t);} /* UART4 Alternate Function mapping */
macro_rules! GPIO_AF_UART5 {() => (0x08u8 as uint8_t);} /* UART5 Alternate Function mapping */
macro_rules! GPIO_AF_USART6 {() => (0x08u8 as uint8_t);} /* USART6 Alternate Function mapping */
/*
* AF 9 selection
*/
macro_rules! GPIO_AF_CAN1 {() => (0x09u8 as uint8_t);} /* CAN1 Alternate Function mapping */
macro_rules! GPIO_AF_CAN2 {() => (0x09u8 as uint8_t);} /* CAN2 Alternate Function mapping */
macro_rules! GPIO_AF_TIM12 {() => (0x09u8 as uint8_t);} /* TIM12 Alternate Function mapping */
macro_rules! GPIO_AF_TIM13 {() => (0x09u8 as uint8_t);} /* TIM13 Alternate Function mapping */
macro_rules! GPIO_AF_TIM14 {() => (0x09u8 as uint8_t);} /* TIM14 Alternate Function mapping */
/*
* AF 10 selection
*/
macro_rules! GPIO_AF_OTG_FS {() => (0xAu8 as uint8_t);} /* OTG_FS Alternate Function mapping */
macro_rules! GPIO_AF_OTG_HS {() => (0xAu8 as uint8_t);} /* OTG_HS Alternate Function mapping */
/*
* AF 11 selection
*/
macro_rules! GPIO_AF_ETH {() => (0x0Bu8 as uint8_t);} /* ETHERNET Alternate Function mapping */
/*
* AF 12 selection
*/
macro_rules! GPIO_AF_FSMC {() => (0xCu8 as uint8_t);} /* FSMC Alternate Function mapping */
macro_rules! GPIO_AF_OTG_HS_FS {() => (0xCu8 as uint8_t);} /* OTG HS configured in FS, Alternate Function mapping */
macro_rules! GPIO_AF_SDIO {() => (0xCu8 as uint8_t);} /* SDIO Alternate Function mapping */
/*
* AF 13 selection
*/
macro_rules! GPIO_AF_DCMI {() => (0x0Du8 as uint8_t);} /* DCMI Alternate Function mapping */
/*
* AF 15 selection
*/
macro_rules! GPIO_AF_EVENTOUT {() => (0x0Fu8 as uint8_t);} /* EVENTOUT Alternate Function mapping */
macro_rules! IS_GPIO_AF {($AF:ident) => ((($AF) == GPIO_AF_RTC_50Hz!()) || (($AF) == GPIO_AF_TIM14!()) ||
(($AF) == GPIO_AF_MCO!()) || (($AF) == GPIO_AF_TAMPER!()) ||
(($AF) == GPIO_AF_SWJ!()) || (($AF) == GPIO_AF_TRACE!()) ||
(($AF) == GPIO_AF_TIM1!()) || (($AF) == GPIO_AF_TIM2!()) ||
(($AF) == GPIO_AF_TIM3!()) || (($AF) == GPIO_AF_TIM4!()) ||
(($AF) == GPIO_AF_TIM5!()) || (($AF) == GPIO_AF_TIM8!()) ||
(($AF) == GPIO_AF_I2C1!()) || (($AF) == GPIO_AF_I2C2!()) ||
(($AF) == GPIO_AF_I2C3!()) || (($AF) == GPIO_AF_SPI1!()) ||
(($AF) == GPIO_AF_SPI2!()) || (($AF) == GPIO_AF_TIM13!()) ||
(($AF) == GPIO_AF_SPI3!()) || (($AF) == GPIO_AF_TIM14!()) ||
(($AF) == GPIO_AF_USART1!()) || (($AF) == GPIO_AF_USART2!()) ||
(($AF) == GPIO_AF_USART3!()) || (($AF) == GPIO_AF_UART4!()) ||
(($AF) == GPIO_AF_UART5!()) || (($AF) == GPIO_AF_USART6!()) ||
(($AF) == GPIO_AF_CAN1!()) || (($AF) == GPIO_AF_CAN2!()) ||
(($AF) == GPIO_AF_OTG_FS!()) || (($AF) == GPIO_AF_OTG_HS!()) ||
(($AF) == GPIO_AF_ETH!()) || (($AF) == GPIO_AF_FSMC!()) ||
(($AF) == GPIO_AF_OTG_HS_FS!()) || (($AF) == GPIO_AF_SDIO!()) ||
(($AF) == GPIO_AF_DCMI!()) || (($AF) == GPIO_AF_EVENTOUT!()));}
/* GPIO_Legacy
*/
macro_rules! GPIO_Mode_AIN {() => (GPIO_Mode_AN!());}
macro_rules! GPIO_AF_OTG1_FS {() => (GPIO_AF_OTG_FS!());}
macro_rules! GPIO_AF_OTG2_HS {() => (GPIO_AF_OTG_HS!());}
macro_rules! GPIO_AF_OTG2_FS {() => (GPIO_AF_OTG_HS_FS!());}
// /* Exported macro ------------------------------------------------------------*/
// /* Exported functions --------------------------------------------------------*/
// /* Function used to set the GPIO configuration to the default reset state ****/
// void GPIO_DeInit(GPIO_TypeDef* GPIOx);
// /* Initialization and Configuration functions *********************************/
// void GPIO_Init(GPIO_TypeDef* GPIOx, GPIO_InitTypeDef* GPIO_InitStruct);
// void GPIO_StructInit(GPIO_InitTypeDef* GPIO_InitStruct);
// void GPIO_PinLockConfig(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin);
// /* GPIO Read and Write functions **********************************************/
// uint8_t GPIO_ReadInputDataBit(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin);
// uint16_t GPIO_ReadInputData(GPIO_TypeDef* GPIOx);
// uint8_t GPIO_ReadOutputDataBit(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin);
// uint16_t GPIO_ReadOutputData(GPIO_TypeDef* GPIOx);
// void GPIO_SetBits(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin);
// void GPIO_ResetBits(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin);
// void GPIO_WriteBit(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin, BitAction BitVal);
// void GPIO_Write(GPIO_TypeDef* GPIOx, uint16_t PortVal);
// void GPIO_ToggleBits(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin);
// /* GPIO Alternate functions configuration function ****************************/
// void GPIO_PinAFConfig(GPIO_TypeDef* GPIOx, uint16_t GPIO_PinSource, uint8_t GPIO_AF);
|
// Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#[no_mangle]
pub extern "C" fn say_hello_from_cpp() {
say_hello();
}
pub fn say_hello() {
println!("Hello, world - from a Rust library. Calculations suggest that 3+4={}", do_maths());
}
fn do_maths() -> i32 {
3 + 4
}
#[test]
fn test_hello() {
assert_eq!(7, do_maths());
}
|
//! Get a vector of tokens from an input string.
// Note that this module is mostly tests. This is by
// design. The parts that the user should care about
// are the lexer interface, the error type, and the
// result type. Everything else is really an implementation
// detail.
pub mod error;
pub mod token;
pub use lex::error::{Error, Result};
use lex::token::StrTokenIterator;
/// Lexes an input string to get a vector of tokens from it.
pub fn lex<S: AsRef<str>>(s: S) -> Result {
// Note that the `collect` call does some magic thanks to
// a stdlib impl for `Vec`. It actually auto-converts a
// `Vec<Result<Token, Error>>` into `Result<Vec<Token>, Error>`.
// This means that only the first error is retained, which
// for now is what we want to do. In the future we'd likely
// want to have a better strategy which doesn't halt lexing
// at every error, and instead differentiates between errors
// which can be worked around and errors which can't, or at
// least tries to provide more information for the user to
// address at once, rather than requiring a slower feedback
// cycle, which can be annoying.
s.as_ref().tokens().collect::<Result>()
}
#[cfg(test)]
mod tests {
use lex::lex;
use lex::Error;
use lex::token::{Token, Location};
#[test]
fn lex_the_empty_program() {
let tokens = lex("");
let expected = Ok(vec![]);
assert_eq!(tokens, expected);
}
#[test]
fn lex_a_single_open_paren() {
let tokens = lex("(");
let expected = Ok(vec![Token::open_paren(Location(1))]);
assert_eq!(tokens, expected);
}
#[test]
fn lex_a_single_close_paren() {
let tokens = lex(")");
let expected = Ok(vec![Token::close_paren(Location(1))]);
assert_eq!(tokens, expected);
}
#[test]
fn lex_matching_parens() {
let tokens = lex("()");
let expected = Ok(vec![
Token::open_paren(Location(1)),
Token::close_paren(Location(2)),
]);
assert_eq!(tokens, expected);
}
#[test]
fn lex_a_simple_program() {
let tokens = lex("(+ 2 3)");
let expected = Ok(vec![
Token::open_paren(Location(1)),
Token::ident("+", Location(2)),
Token::integer(2, Location(4), Location(4)),
Token::integer(3, Location(6), Location(6)),
Token::close_paren(Location(7)),
]);
assert_eq!(tokens, expected);
}
#[test]
fn lex_a_more_complex_program() {
let tokens = lex("(+ (add-two 2) 3.2)");
let expected = Ok(vec![
Token::open_paren(Location(1)),
Token::ident("+", Location(2)),
Token::open_paren(Location(4)),
Token::ident("add-two", Location(5)),
Token::integer(2, Location(13), Location(13)),
Token::close_paren(Location(14)),
Token::float(3.2, Location(16), Location(18)),
Token::close_paren(Location(19)),
]);
assert_eq!(tokens, expected);
}
#[test]
fn lex_a_complex_identifier() {
let tokens = lex("(%a+/d 2 4)");
let expected = Ok(vec![
Token::open_paren(Location(1)),
Token::ident("%a+/d", Location(2)),
Token::integer(2, Location(8), Location(8)),
Token::integer(4, Location(10), Location(10)),
Token::close_paren(Location(11)),
]);
assert_eq!(tokens, expected);
}
#[test]
fn fail_to_lex_a_non_ascii_character() {
let result = lex("(+ (¢ 3) 4)");
let expected = Err(Error::InvalidCharacter('¢', 5));
assert_eq!(result, expected);
}
#[test]
fn lex_a_short_boolean() {
let result = lex("(#t)");
let expected = Ok(vec![
Token::open_paren(Location(1)),
Token::boolean(true, Location(2), Location(3)),
Token::close_paren(Location(4)),
]);
assert_eq!(result, expected);
}
#[test]
fn lex_a_long_boolean() {
let result = lex("(#false)");
let expected = Ok(vec![
Token::open_paren(Location(1)),
Token::boolean(false, Location(2), Location(7)),
Token::close_paren(Location(8)),
]);
assert_eq!(result, expected);
}
#[test]
fn lex_an_invalid_literal() {
let result = lex("(#what)");
let expected = Err(Error::InvalidLiteral("#what".to_string(), 2));
assert_eq!(result, expected);
}
#[test]
fn lex_a_string() {
let result = lex("\"hello\"");
let expected = Ok(vec![Token::string("hello".to_string(), Location(1))]);
assert_eq!(result, expected);
}
#[test]
fn lex_a_string_in_a_function() {
let result = lex("(f 2 \"blah\")");
let expected = Ok(vec![
Token::open_paren(Location(1)),
Token::ident("f", Location(2)),
Token::integer(2, Location(4), Location(4)),
Token::string("blah", Location(6)),
Token::close_paren(Location(12)),
]);
assert_eq!(result, expected);
}
#[test]
fn lex_a_string_with_an_escape_equence() {
let result = lex("(g \"hello\n\" 4)");
let expected = Ok(vec![
Token::open_paren(Location(1)),
Token::ident("g", Location(2)),
Token::string("hello\n", Location(4)),
Token::integer(4, Location(13), Location(13)),
Token::close_paren(Location(14)),
]);
assert_eq!(result, expected);
}
#[test]
fn lex_mix_of_delimiters() {
let result = lex("([{}])");
let expected = Ok(vec![
Token::open_paren(Location(1)),
Token::open_bracket(Location(2)),
Token::open_brace(Location(3)),
Token::close_brace(Location(4)),
Token::close_bracket(Location(5)),
Token::close_paren(Location(6)),
]);
assert_eq!(result, expected);
}
}
|
fn main() -> std::io::Result<()> {
prost_build::compile_protos(&["net.proto"], &["./proto/"])?;
Ok(())
}
|
// use std::collections::BTreeMap;
use std::hash::Hash;
use std::collections::HashMap;
use std::rc::Rc;
// use std::cmp::Ordering;
// use rand::Rng;
use rand::distributions::{Distribution};
use crate::AlgorithmParams;
use crate::distributions::standard_weighted::StandardWeighted;
use crate::{abstractions::CustomDistribution};
// use crate::utils::BoltzmannParams;
use crate::distributions::boltzmann::Boltzmann;
use super::super::Genetic;
use crate::GeneticCustom;
pub type GenHash<T> = HashMap<Rc<T>, f64>;
// TODO: Implement elitism
pub fn genetic_algorithm<T>(
initial_population: &Vec<Rc<T>>,
params: &AlgorithmParams,
fitness: &Box<dyn Fn(&T) -> f64>,
cache: &mut GenHash<T>
) -> Vec<Rc<T>>
where
T: GeneticCustom + Copy + Eq + Hash
{
/*
Hash with respect to ds.
Before calculating fitness check if it is on the hash, retrieve from hash
otherwise, calculate the fitness then store the new one in the hash
also store the btree.
Once stored in the btree check what the size is and when you surpace the size just erase
until you get to the actual size.
if you erase from btree erase from hash
NOTE: Try to do it with a reference count.
Implement: f_1(sample) -> SampleFitness
Implement: f_2() -> Borrow to btree
Implement: f_3() -> Borrow to hash
Eventually change function return type to new SampleFitness.
*/
let mut population = initial_population.clone();
for i in 0..params.rounds {
let mut rng = rand::thread_rng();
let boltzmann_params = Boltzmann {
distribution: None,
t_coefficient: 1f64,
f_max: 1f64,
generation: i as f64,
max_generation: params.rounds as f64,
};
let std_weighted = StandardWeighted{
distribution: None
};
// let sampler= std_weighted.new(&population, fitness, cache);
// let dist = sampler.distribution.unwrap();
// let dist = utils::boltzmann_selection(&population, boltzmann_params, fitness, cache);
let sampler = boltzmann_params.new(&population, fitness, cache);
let dist = sampler.distribution.unwrap();
let mut new_population: Vec<Rc<T>> = Vec::new();
while new_population.len() < params.max_popuation as usize {
let parent_1 = &population[dist.sample(&mut rng)];
let parent_2 = &population[dist.sample(&mut rng)];
// let (child_1, child_2 )= parent_1.cross_over(&parent_2, params.co_factor);
// let mutated_child_1 = child_1.mutation(params.mutation_rate);
// let mutated_child_2 = child_2.mutation(params.mutation_rate);
let (mutated_child_1, mutated_child_2) = parent_1.mutate_step(parent_2, params);
new_population.push(Rc::new(mutated_child_1));
new_population.push(Rc::new(mutated_child_2));
}
population = new_population;
}
return population;
}
|
pub mod intern_file;
|
use drg::*;
use crate::internal::*;
use crate::keyboard::*;
use crate::operations::*;
use crate::property_editor::*;
use crate::tools::*;
use imgui::*;
use std::path::Path;
const MAIN_WINDOW_FLAGS: WindowFlags = WindowFlags::NO_BRING_TO_FRONT_ON_FOCUS;
pub fn start_editor_with_path(fp: &Path) {
let editor = match AssetHeader::read_from(fp) {
Err(err) => Editor {
state: State::None,
err: Some(err),
tool: None,
keyboard: Keyboard::default(),
},
Ok(header) => Editor {
state: State::Header {
header,
path: Box::from(fp),
import_editor: ImportEditor::default(),
},
err: None,
tool: None,
keyboard: Keyboard::default(),
},
};
init_editor(editor)
}
pub fn start_editor_empty() {
init_editor(Editor::default())
}
pub fn init_editor(editor: Editor) {
let mut editor = editor;
let mut operations = Operations::default();
ToolEditor::register_ops(&mut operations);
let system = crate::support::init("DRG Editor");
system.main_loop(move |(width, height), run, ui| {
let dims = (width as f32, height as f32);
draw_editor(dims, run, ui, &mut editor, &mut operations);
})
}
fn draw_editor(
(width, height): (f32, f32),
run: &mut bool,
ui: &Ui,
editor: &mut Editor,
ops: &mut Operations,
) {
let frame_color = ui.push_style_color(StyleColor::WindowBg, [0.1, 0.1, 0.12, 1.0]);
let menu_height = 35.0;
let (left, top) = (0.0, menu_height);
let (width, height) = (width, height - menu_height);
error_modal(editor, ui);
// Check keyboard shortcuts
editor.keyboard.update(ui);
ops.run(editor, ui);
draw_menu([0.0, 0.0], [width, menu_height], run, ui, editor);
if let Some(tool_editor) = &mut editor.tool {
let mut done = false;
tool_editor.draw(&mut editor.state, ui, &mut done);
if done {
editor.tool = None;
}
}
match &mut editor.state {
State::None => {
let w = Window::new(im_str!("Message"))
.title_bar(false)
.resizable(false)
.collapsible(false)
.movable(false)
.scroll_bar(false)
.position([left, top], Condition::Always)
.size([width, height], Condition::Always);
w.build(&ui, || {
ui.text("Open a file to start hex modding");
});
}
State::Header {
header,
import_editor,
..
} => {
draw_imports_editor(
[left, top],
[width / 2.0, height / 2.0],
ui,
header,
import_editor,
);
draw_exports_loader(
[left + width / 2.0, top],
[width / 2.0, height / 2.0],
ui,
editor,
);
}
State::Asset {
asset,
import_editor,
export_editor,
..
} => {
draw_imports_editor(
[left, top],
[width / 2.0, height / 2.0],
ui,
&mut asset.header,
import_editor,
);
draw_exports_selector(
[left + width / 2.0, top],
[width / 2.0, height / 2.0],
ui,
asset,
export_editor,
);
draw_properties_editor(
(left, top + height / 2.0),
(width, height / 2.0),
ui,
asset,
export_editor,
);
}
}
frame_color.pop(ui);
}
fn draw_menu(_pos: [f32; 2], _size: [f32; 2], run: &mut bool, ui: &Ui, editor: &mut Editor) {
if let Some(main_menu_bar) = ui.begin_main_menu_bar() {
if let Some(file_menu) = ui.begin_menu(im_str!("File"), true) {
error_modal(editor, ui);
// FILE > OPEN
if MenuItem::new(im_str!("Open"))
.shortcut(im_str!("Ctrl+O"))
.build(ui)
{
crate::operations::io::open(editor, ui);
}
// FILE > SAVE
if MenuItem::new(im_str!("Save As"))
.shortcut(im_str!("Ctrl+S"))
.enabled(editor.state.has_header())
.build(ui)
{
crate::operations::io::save(editor, ui);
}
if MenuItem::new(im_str!("Exit")).build(ui) {
*run = false;
}
file_menu.end(ui);
}
if let Some(edit_menu) = ui.begin_menu(im_str!("Edit"), true) {
if let Some(tool_editor) = ToolEditor::menu_items(&editor.state, ui) {
editor.tool = Some(tool_editor);
}
edit_menu.end(ui);
}
main_menu_bar.end(ui);
}
}
fn draw_imports_editor(
pos: [f32; 2],
size: [f32; 2],
ui: &Ui,
header: &mut AssetHeader,
editor: &mut ImportEditor,
) {
let w = Window::new(im_str!("Imports"))
.flags(MAIN_WINDOW_FLAGS)
.resizable(false)
.collapsible(false)
.movable(false)
.position(pos, Condition::Always)
.scroll_bar(false)
.size(size, Condition::Always);
w.build(&ui, || {
ui.columns(2, im_str!("??"), true);
// LIST PANE
let list_w = ChildWindow::new("importlist")
.horizontal_scrollbar(true)
.movable(false);
list_w.build(&ui, || {
for import in header.list_imports() {
let active = Some(import.name.clone()) == editor.selected_import;
if ui.radio_button_bool(
&ImString::from(import.name.to_string(&header.names)),
active,
) {
editor.selected_import = Some(import.name.clone());
}
}
});
// EDITING PANE
ui.next_column();
let edit_w = ChildWindow::new("importedit")
.movable(false)
.horizontal_scrollbar(true);
edit_w.build(&ui, || {
if ui.button(im_str!("Add Import"), [0.0, 0.0]) {
editor.new_import = Some(EditableImport::default());
ui.open_popup(im_str!("Add Import"));
}
ui.separator();
if let Some(selected) = &editor.selected_import {
let import = header
.list_imports()
.iter()
.find(|im| selected == &im.name)
.expect("Invalid Import select state");
// TODO: this name deserialization should probably happen after reading
// imports during Asset::read. But that will require a bunch of work
let outer = Reference::deserialize(import.outer_index, &header.imports, &header.exports)
.expect("Invalid Import outer");
ui.text(format!(
"Class Package: {}",
import.class_package.to_string(&header.names)
));
ui.text(format!("Class: {}", import.class.to_string(&header.names)));
ui.text(format!("Name: {}", import.name.to_string(&header.names)));
ui.text(format!("Outer: {}", outer.to_string(&header.names)));
} else {
ui.text("Select an import");
}
// ADD IMPORT MODAL
ui.popup_modal(im_str!("Add Import"))
.always_auto_resize(true)
.build(|| {
let new_import = editor
.new_import
.as_mut()
.expect("Add Import modal not initialized properly");
input_import(ui, &header, new_import);
if ui.button(im_str!("Add"), [0.0, 0.0]) {
header.import(
new_import.class_package.as_ref(),
new_import.class.as_ref(),
new_import.name.as_ref(),
new_import.outer.clone(),
);
editor.new_import = None;
ui.close_current_popup();
}
ui.same_line(0.0);
if ui.button(im_str!("Cancel"), [0.0, 0.0]) {
editor.new_import = None;
ui.close_current_popup();
}
});
});
});
}
fn draw_exports_loader(pos: [f32; 2], size: [f32; 2], ui: &Ui, editor: &mut Editor) {
let w = Window::new(im_str!("Exports"))
.flags(MAIN_WINDOW_FLAGS)
.resizable(false)
.collapsible(false)
.movable(false)
.position(pos, Condition::Always)
.size(size, Condition::Always);
w.build(&ui, || {
error_modal(editor, ui);
if ui.button(im_str!("Load Export Data [Ctrl+Shift+L]"), [0.0, 0.0]) {
crate::operations::io::load_exports(editor, ui);
}
});
}
fn draw_exports_selector(
pos: [f32; 2],
size: [f32; 2],
ui: &Ui,
asset: &mut Asset,
editor: &mut ExportEditor,
) {
let w = Window::new(im_str!("Exports"))
.flags(MAIN_WINDOW_FLAGS)
.resizable(false)
.collapsible(false)
.movable(false)
.position(pos, Condition::Always)
.size(size, Condition::Always);
w.build(&ui, || {
for export in asset.list_exports() {
let active = Some(export.clone()) == editor.selected_export;
if ui.radio_button_bool(&ImString::from(export.to_string(asset.names())), active) && !active {
// The selected export is changing, so have to deselect the property
editor.selected_export = Some(export.clone());
editor.properties_editor = Some(PropertiesEditor::default().with_flags(MAIN_WINDOW_FLAGS));
}
}
});
}
fn draw_properties_editor(
left_top: (f32, f32),
width_height: (f32, f32),
ui: &Ui,
asset: &mut Asset,
export_editor: &mut ExportEditor,
) {
match export_editor {
ExportEditor {
selected_export: Some(selected_export),
properties_editor: Some(properties_editor),
} => {
let struct_idx = asset
.list_exports()
.iter()
.position(|x| x == selected_export)
.expect("Invalid selected export. Report this crash to the maintainer.");
let properties = &mut asset.exports.structs[struct_idx].properties;
properties_editor.draw(left_top, width_height, ui, &mut asset.header, properties);
}
_ => {
// don't draw properties if no editor/no selected export
}
}
}
fn input_import(ui: &Ui, header: &AssetHeader, import: &mut EditableImport) {
ui.input_text(im_str!("Class Package"), &mut import.class_package)
.resize_buffer(true)
.build();
ui.input_text(im_str!("Class"), &mut import.class)
.resize_buffer(true)
.build();
ui.input_text(im_str!("Name"), &mut import.name)
.resize_buffer(true)
.build();
if let Some(new_dep) = input_dependency(ui, "Outer", header, import.outer.clone()) {
import.outer = new_dep;
}
}
|
use futures::Stream;
use gear::{
system::{Path, PathBuf},
Error, Map, Result, Time,
};
use notify::{Event, RecommendedWatcher, RecursiveMode, Watcher as FsWatcher};
use std::{
pin::Pin,
sync::{Arc, Mutex},
task::{Context, Poll, Waker},
};
#[derive(Default)]
struct State {
done: bool,
error: Option<Error>,
paths: Map<PathBuf, Time>,
waker: Option<Waker>,
}
pub struct Watcher(RecommendedWatcher);
#[derive(Default, Clone)]
pub struct Events(Arc<Mutex<State>>);
impl Events {
fn handle(&self, result: notify::Result<Event>) {
let mut state = self.0.lock().unwrap();
match result {
Ok(event) => {
let time = Time::now();
for path in event.paths {
state
.paths
.entry(path.into())
.and_modify(|value| {
*value = time;
})
.or_insert(time);
}
}
Err(error) => {
state.error = Some(error.into());
state.done = true;
}
}
if let Some(waker) = state.waker.take() {
waker.wake();
}
}
}
impl Stream for Events {
type Item = Result<Vec<(PathBuf, Time)>>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
let mut state = self.0.lock().unwrap();
state.waker = Some(cx.waker().clone());
if !state.paths.is_empty() {
Poll::Ready(Some(Ok(state.paths.drain(..).collect())))
} else if let Some(error) = state.error.take() {
Poll::Ready(Some(Err(error)))
} else if state.done {
Poll::Ready(None)
} else {
Poll::Pending
}
}
}
impl Watcher {
pub fn new() -> Result<(Self, Events)> {
let events = Events::default();
let watcher = RecommendedWatcher::new_immediate({
let handler = events.clone();
move |result| handler.handle(result)
})?;
Ok((Self(watcher), events))
}
pub fn watch(&mut self, path: impl AsRef<Path>, recursive: bool) -> Result<()> {
self.0.watch(
path.as_ref(),
if recursive {
RecursiveMode::Recursive
} else {
RecursiveMode::NonRecursive
},
)?;
Ok(())
}
pub fn unwatch(&mut self, path: impl AsRef<Path>) -> Result<()> {
self.0.unwatch(path.as_ref())?;
Ok(())
}
}
|
use glutin_window::GlutinWindow;
use graphics::color::hex;
use opengl_graphics::{Filter, GlGraphics, GlyphCache, OpenGL, TextureSettings};
use piston::event_loop::{EventSettings, Events};
use piston::input::RenderEvent;
use piston::window::WindowSettings;
use std::time::{Duration, Instant};
pub use nonogram_board::NonogramBoard;
pub use nonogram_board_view::{NonogramView, NonogramViewSettings};
pub use nonogram_controller::NonogramController;
mod common;
mod nonogram_board;
mod nonogram_board_view;
mod nonogram_controller;
use crate::common::{INITIAL_BOARD_DIMENSIONS, INITIAL_WINDOW_SIZE};
/// Does everything necessary to run the game. Creates the initial classes, window, and sits in a
/// while loop that's constantly redrawing the contents of the window and checking for events.
fn main() {
let opengl = OpenGL::V3_2;
let settings = WindowSettings::new("Nonogram", INITIAL_WINDOW_SIZE)
.graphics_api(opengl)
.samples(4);
let mut window: GlutinWindow = settings.build().expect("Could not create window");
let mut events = Events::new(EventSettings::new());
let mut gl = GlGraphics::new(opengl);
let nonogram = NonogramBoard::new(INITIAL_BOARD_DIMENSIONS, false);
let mut nonogram_controller = NonogramController::new(nonogram);
let mut nonogram_view_settings =
NonogramViewSettings::new(nonogram_controller.nonogram.dimensions);
let mut nonogram_view = NonogramView::new(nonogram_view_settings);
// Everything necessary for the variants fonts to work.
let assets = find_folder::Search::ParentsThenKids(3, 3)
.for_folder("assets")
.unwrap();
let texture_settings = TextureSettings::new().filter(Filter::Nearest);
let font = &assets.join("FiraSans-Regular.ttf");
let glyphs = &mut GlyphCache::new(font, (), texture_settings)
.expect("Could not load FiraSans-Regular.ttf");
let mark_font = &assets.join("Monoround.ttf");
let mark_glyphs = &mut GlyphCache::new(mark_font, (), texture_settings)
.expect("Could not load Monoround.ttf");
let material_icons_font = &assets.join("MaterialIcons-Regular.ttf");
let material_icons_glyphs = &mut GlyphCache::new(material_icons_font, (), texture_settings)
.expect("Could not load MaterialIcons-Regular.ttf");
println!("Nonogram game started.");
while let Some(e) = events.next(&mut window) {
nonogram_controller.event(
nonogram_view.settings.position,
nonogram_view.settings.board_dimensions,
nonogram_view.settings.dimensions_dropdown_menu_box,
nonogram_view.settings.restart_box,
nonogram_view.settings.new_game_box,
&e,
);
if let Some(args) = e.render_args() {
gl.draw(args.viewport(), |c, g| {
use graphics::clear;
if !nonogram_controller.nonogram.end_game_screen {
nonogram_controller.nonogram.duration =
match nonogram_controller.nonogram.game_start {
Some(game_start) => match nonogram_controller.nonogram.game_end {
Some(game_end) => game_end - game_start,
None => Instant::now() - game_start,
},
None => Duration::from_secs(0),
};
}
clear(hex("222222"), g);
nonogram_view.draw(
&nonogram_controller,
glyphs,
mark_glyphs,
material_icons_glyphs,
&c,
g,
);
});
}
// The board is reset when pressing the key bound to "restart", clicking the "restart" button
// while a board is loaded, or when clicking the "new game" button when on the win screen.
//
// Resetting the board causes it to wipe the current state, potentially create a new board with different
// dimensions than the current board depending on the user's choice, and generate a new goal state.
if nonogram_controller.nonogram.reset_board {
nonogram_controller.nonogram = nonogram_board::NonogramBoard::new(
nonogram_controller.nonogram.next_dimensions,
true,
);
nonogram_view_settings =
NonogramViewSettings::new(nonogram_controller.nonogram.dimensions);
nonogram_view = NonogramView::new(nonogram_view_settings);
}
}
}
|
use crate::input::InputPreprocessor;
use crate::tool::{DocumentToolData, Fsm, ToolActionHandlerData};
use crate::{document::DocumentMessageHandler, message_prelude::*};
use glam::DAffine2;
use graphene::{layers::style, Operation};
#[derive(Default)]
pub struct Pen {
fsm_state: PenToolFsmState,
data: PenToolData,
}
#[impl_message(Message, ToolMessage, Pen)]
#[derive(PartialEq, Clone, Debug, Hash)]
pub enum PenMessage {
Undo,
DragStart,
DragStop,
PointerMove,
Confirm,
Abort,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum PenToolFsmState {
Ready,
Dragging,
}
impl<'a> MessageHandler<ToolMessage, ToolActionHandlerData<'a>> for Pen {
fn process_action(&mut self, action: ToolMessage, data: ToolActionHandlerData<'a>, responses: &mut VecDeque<Message>) {
self.fsm_state = self.fsm_state.transition(action, data.0, data.1, &mut self.data, data.2, responses);
}
fn actions(&self) -> ActionList {
use PenToolFsmState::*;
match self.fsm_state {
Ready => actions!(PenMessageDiscriminant; Undo, DragStart, DragStop, Confirm, Abort),
Dragging => actions!(PenMessageDiscriminant; DragStop, PointerMove, Confirm, Abort),
}
}
}
impl Default for PenToolFsmState {
fn default() -> Self {
PenToolFsmState::Ready
}
}
#[derive(Clone, Debug, Default)]
struct PenToolData {
points: Vec<DAffine2>,
next_point: DAffine2,
path: Option<Vec<LayerId>>,
}
impl Fsm for PenToolFsmState {
type ToolData = PenToolData;
fn transition(
self,
event: ToolMessage,
document: &DocumentMessageHandler,
tool_data: &DocumentToolData,
data: &mut Self::ToolData,
input: &InputPreprocessor,
responses: &mut VecDeque<Message>,
) -> Self {
let transform = document.document.root.transform;
let pos = transform.inverse() * DAffine2::from_translation(input.mouse.position);
use PenMessage::*;
use PenToolFsmState::*;
if let ToolMessage::Pen(event) = event {
match (self, event) {
(Ready, DragStart) => {
responses.push_back(DocumentMessage::StartTransaction.into());
responses.push_back(DocumentMessage::DeselectAllLayers.into());
data.path = Some(vec![generate_uuid()]);
data.points.push(pos);
data.next_point = pos;
Dragging
}
(Dragging, DragStop) => {
// TODO: introduce comparison threshold when operating with canvas coordinates (https://github.com/GraphiteEditor/Graphite/issues/100)
if data.points.last() != Some(&pos) {
data.points.push(pos);
data.next_point = pos;
}
responses.extend(make_operation(data, tool_data, true));
Dragging
}
(Dragging, PointerMove) => {
data.next_point = pos;
responses.extend(make_operation(data, tool_data, true));
Dragging
}
(Dragging, Confirm) => {
if data.points.len() >= 2 {
responses.push_back(DocumentMessage::DeselectAllLayers.into());
responses.extend(make_operation(data, tool_data, false));
responses.push_back(DocumentMessage::CommitTransaction.into());
} else {
responses.push_back(DocumentMessage::AbortTransaction.into());
}
data.path = None;
data.points.clear();
Ready
}
(Dragging, Abort) => {
responses.push_back(DocumentMessage::AbortTransaction.into());
data.points.clear();
data.path = None;
Ready
}
_ => self,
}
} else {
self
}
}
}
fn make_operation(data: &PenToolData, tool_data: &DocumentToolData, show_preview: bool) -> [Message; 2] {
let mut points: Vec<(f64, f64)> = data.points.iter().map(|p| (p.translation.x, p.translation.y)).collect();
if show_preview {
points.push((data.next_point.translation.x, data.next_point.translation.y))
}
[
Operation::DeleteLayer { path: data.path.clone().unwrap() }.into(),
Operation::AddPen {
path: data.path.clone().unwrap(),
insert_index: -1,
transform: DAffine2::IDENTITY.to_cols_array(),
points,
style: style::PathStyle::new(Some(style::Stroke::new(tool_data.primary_color, 5.)), Some(style::Fill::none())),
}
.into(),
]
}
|
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#[macro_use]
extern crate failure;
#[macro_use]
extern crate log;
extern crate serde;
extern crate serde_json;
#[macro_use]
mod macros;
pub mod file;
mod serializer;
use failure::Error;
use std::result;
pub type Result<T> = result::Result<T, AuthDbError>;
/// Errors that may result from operations on an AuthDb.
#[derive(Debug, Fail)]
pub enum AuthDbError {
/// An illegal input argument was supplied, such as an invalid path.
#[fail(display = "invalid argument")]
InvalidArguments,
/// A lower level failure occured while serialization and writing the data.
/// See logs for more information.
#[fail(display = "unexpected error serializing or deserialing the database")]
SerializationError,
/// A lower level failure occured while reading and deserialization the
/// data.
#[fail(display = "unexpected IO error accessing the database: {}", _0)]
IoError(#[cause] std::io::Error),
/// The existing contents of the DB are not valid. This could be caused by
/// a change in file format or by data corruption.
#[fail(display = "database contents could not be parsed")]
DbInvalid,
/// The requested credential is not present in the DB.
#[fail(display = "credential not found")]
CredentialNotFound,
}
/// Unique identifier for a user credential as stored in the auth db.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
pub struct CredentialKey {
/// A string identifier for an configured identity provider, such as
/// 'Google'.
identity_provider: String,
/// A string identifier provided by the identity provider, typically the
/// user's email address or profile url.
id: String,
}
impl CredentialKey {
/// Create a new CredentialKey, or returns an Error if any input is
/// empty.
pub fn new(identity_provider: String, id: String) -> result::Result<CredentialKey, Error> {
if identity_provider.is_empty() {
Err(format_err!("identity_provider cannot be empty"))
} else if id.is_empty() {
Err(format_err!("id cannot be empty"))
} else {
Ok(CredentialKey {
identity_provider,
id,
})
}
}
}
/// The set of data to be stored for a user credential.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct CredentialValue {
/// A unique identifier for credential including the IdP and account.
credential_key: CredentialKey,
/// An OAuth refresh token.
refresh_token: String,
}
impl CredentialValue {
/// Create a new CredentialValue, or returns an Error if any input is empty.
pub fn new(
identity_provider: String,
id: String,
refresh_token: String,
) -> result::Result<CredentialValue, Error> {
if refresh_token.is_empty() {
Err(format_err!("refresh_token cannot be empty"))
} else {
Ok(CredentialValue {
credential_key: CredentialKey::new(identity_provider, id)?,
refresh_token,
})
}
}
}
/// A trait expressing the functionality that all auth databases must provide.
pub trait AuthDb {
/// Adds a new user credential to the database. The operation may insert a
/// new user credential or replace an existing user credential.
/// Replacement of an existing credential is useful when the credential
/// has been expired or invalidated by the identity provider.
fn add_credential(&mut self, credential: CredentialValue) -> Result<()>;
/// Deletes the specified existing user credential from the database.
fn delete_credential(&mut self, credential_key: &CredentialKey) -> Result<()>;
/// Returns all the credentials provisioned in this instance of the
/// database.
fn get_all_credentials<'a>(&'a self) -> Result<Vec<&'a CredentialValue>>;
/// Returns the refresh token for a specified user credential.
fn get_refresh_token<'a>(&'a self, credential_key: &CredentialKey) -> Result<&'a str>;
}
#[cfg(test)]
mod tests {
use super::*;
const TEST_IDP: &str = "test.com";
const TEST_ID: &str = "user@test.com";
const TEST_REFRESH_TOKEN: &str = "123456789@#$&*(%)_@(&";
#[test]
fn test_new_valid_credential() {
let cred = CredentialValue::new(
TEST_IDP.to_string(),
TEST_ID.to_string(),
TEST_REFRESH_TOKEN.to_string(),
).unwrap();
assert_eq!(cred.credential_key.identity_provider, TEST_IDP);
assert_eq!(cred.credential_key.id, TEST_ID);
assert_eq!(cred.refresh_token, TEST_REFRESH_TOKEN);
}
#[test]
fn test_new_invalid_credential() {
assert!(
CredentialValue::new(
"".to_string(),
TEST_ID.to_string(),
TEST_REFRESH_TOKEN.to_string()
).is_err()
);
assert!(
CredentialValue::new(
TEST_IDP.to_string(),
"".to_string(),
TEST_REFRESH_TOKEN.to_string()
).is_err()
);
assert!(
CredentialValue::new(TEST_IDP.to_string(), TEST_ID.to_string(), "".to_string())
.is_err()
);
}
}
|
use std::cell::RefCell;
use std::fmt;
/// Named-Field Structs
pub struct Point {
pub x: i32,
pub y: i32,
z: i32,
n: RefCell<i32>,
}
impl Point {
pub fn new(x: i32, y: i32) -> Point {
Point {
x: x,
y: y,
z: 1,
n: RefCell::new(2),
}
}
// cannot assign to `self.z` which is behind a `&` reference
// `self` is a `&` reference, so the data it refers to cannot be written
// pub fn pluse_z(&self) {
pub fn pluse_z(&mut self) {
self.z += self.dummy_private_func();
}
fn dummy_private_func(&self) -> i32 {
self.z
}
pub fn pluse_n(&self) {
let mut n = self.n.borrow_mut();
*n += *n;
}
}
impl fmt::Display for Point {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"Point(x={}, y={}, z={}, n={})",
self.x,
self.y,
self.z,
self.n.borrow()
)
}
}
|
use std::fmt::Display;
use std::path::PathBuf;
use anyhow::Context;
use clap::{Parser, Subcommand};
use pyo3::exceptions::PyException;
use pyo3::prelude::*;
use pyo3::types::PyList;
use crate::{AnyhowError, AnyhowWrapper};
#[derive(Parser, Debug)]
#[command(name = "Hydro Deploy", author, version, about, long_about = None)]
struct Cli {
#[command(subcommand)]
command: Commands,
}
#[derive(Subcommand, Debug)]
enum Commands {
/// Deploys an application given a Python deployment script.
Deploy {
/// Path to the deployment script.
config: PathBuf,
/// Additional arguments to pass to the deployment script.
#[arg(last(true))]
args: Vec<String>,
},
}
fn async_wrapper_module(py: Python) -> Result<&PyModule, PyErr> {
PyModule::from_code(
py,
include_str!("../hydro/async_wrapper.py"),
"wrapper.py",
"wrapper",
)
}
#[derive(Debug)]
struct PyErrWithTraceback {
err_display: String,
traceback: String,
}
impl std::error::Error for PyErrWithTraceback {}
impl Display for PyErrWithTraceback {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
writeln!(f, "{}", self.err_display)?;
write!(f, "{}", self.traceback)
}
}
fn deploy(config: PathBuf, args: Vec<String>) -> anyhow::Result<()> {
Python::with_gil(|py| -> anyhow::Result<()> {
let syspath: &PyList = py
.import("sys")
.and_then(|s| s.getattr("path"))
.and_then(|p| Ok(p.downcast::<PyList>()?))?;
syspath.insert(0, PathBuf::from(".").canonicalize().unwrap())?;
let filename = config.canonicalize().unwrap();
let fun: Py<PyAny> = PyModule::from_code(
py,
std::fs::read_to_string(config).unwrap().as_str(),
filename.to_str().unwrap(),
"",
)
.with_context(|| format!("failed to load deployment script: {}", filename.display()))?
.getattr("main")
.context("expected deployment script to define a `main` function, but one was not found")?
.into();
let wrapper = async_wrapper_module(py)?;
match wrapper.call_method1("run", (fun, args)) {
Ok(_) => Ok(()),
Err(err) => {
let traceback = err
.traceback(py)
.context("traceback was expected but none found")
.and_then(|tb| Ok(tb.format()?))?
.trim()
.to_string();
if err.is_instance_of::<AnyhowError>(py) {
let args = err
.value(py)
.getattr("args")?
.extract::<Vec<AnyhowWrapper>>()?;
let wrapper = args.get(0).unwrap();
let underlying = &wrapper.underlying;
let mut underlying = underlying.blocking_write();
Err(underlying.take().unwrap()).context(traceback)
} else {
Err(PyErrWithTraceback {
err_display: format!("{}", err),
traceback,
}
.into())
}
}
}
})?;
Ok(())
}
#[pyfunction]
fn cli_entrypoint(args: Vec<String>) -> PyResult<()> {
match Cli::try_parse_from(args) {
Ok(args) => {
let res = match args.command {
Commands::Deploy { config, args } => deploy(config, args),
};
match res {
Ok(_) => Ok(()),
Err(err) => {
eprintln!("{:?}", err);
Err(PyErr::new::<PyException, _>(""))
}
}
}
Err(err) => {
err.print().unwrap();
Err(PyErr::new::<PyException, _>(""))
}
}
}
#[pymodule]
pub fn cli(_py: Python, m: &PyModule) -> PyResult<()> {
m.add_function(wrap_pyfunction!(cli_entrypoint, m)?)?;
Ok(())
}
|
use crate::{common::Solution, reparse};
use lazy_static::lazy_static;
use regex::Regex;
use std::collections::{HashMap, HashSet};
lazy_static! {
static ref PRODUCT_REGX: Regex = Regex::new(r"([\w ]+) \(contains ([\w, ]+)\)").unwrap();
}
type AllergenToProdMap = HashMap<String, HashSet<String>>;
fn resolve_mapping(allergen_to_prods: &mut AllergenToProdMap) -> HashMap<String, String> {
let mut allerg_mapping: HashMap<String, String> = HashMap::new();
while !allergen_to_prods.is_empty() {
let singles: Vec<(String, String)> = allergen_to_prods
.iter()
.filter_map(|(al, prods)| {
if prods.len() == 1 {
Some((al.to_string(), prods.iter().next().unwrap().to_string()))
} else {
None
}
})
.collect();
singles.iter().for_each(|(al, prod)| {
allerg_mapping.insert(al.to_string(), prod.to_string());
allergen_to_prods.remove(al);
allergen_to_prods.iter_mut().for_each(|(_, prods)| {
prods.remove(prod);
});
});
}
allerg_mapping
}
fn find_common_prods(input: &InputType) -> AllergenToProdMap {
input
.all_allergens
.iter()
.map(|al| {
let foods_with_al = input
.data
.iter()
.filter(|&f| f.allergens.contains(al))
.map(|f| &f.products)
.collect::<Vec<&HashSet<String>>>();
let common_prods: HashSet<String> = foods_with_al[0]
.iter()
.filter(|&prod| foods_with_al[1..].iter().all(|food| food.contains(prod)))
.map(|prod| prod.to_string())
.collect();
(al.to_string(), common_prods)
})
.collect()
}
fn part1(input: &InputType) -> String {
let mut allergen_to_prods = find_common_prods(input);
let identified = resolve_mapping(&mut allergen_to_prods);
let allergic_prods: HashSet<String> = identified.values().map(|x| x.to_string()).collect();
input
.data
.iter()
.flat_map(|f| f.products.iter())
.filter(|&prod| !allergic_prods.contains(prod))
.count()
.to_string()
}
fn part2(input: &InputType) -> String {
let mut allergen_to_prods = find_common_prods(input);
let identified = resolve_mapping(&mut allergen_to_prods);
let mut allergens_sorted: Vec<String> =
input.all_allergens.iter().map(|x| x.to_string()).collect();
allergens_sorted.sort_unstable();
allergens_sorted
.iter()
.map(|key| identified.get(key).unwrap().to_string())
.collect::<Vec<String>>()
.join(",")
.to_string()
}
struct Food {
products: HashSet<String>,
allergens: HashSet<String>,
}
struct FoodList {
data: Vec<Food>,
all_allergens: HashSet<String>,
}
type InputType = FoodList;
fn parse_input(raw_input: &[String]) -> InputType {
let mut all_allergens: HashSet<String> = HashSet::new();
let data = raw_input
.iter()
.map(|x| {
let (prod_str, allerg_str) = reparse!(x, PRODUCT_REGX, String, String).unwrap();
let products: HashSet<String> =
prod_str.split_whitespace().map(|x| x.to_string()).collect();
let allergens: HashSet<String> =
allerg_str.split(", ").map(|x| x.to_string()).collect();
allergens.iter().for_each(|x| {
all_allergens.insert(x.to_string());
});
Food {
products,
allergens,
}
})
.collect();
FoodList {
data,
all_allergens,
}
}
pub fn solve(raw_input: &[String]) -> Solution {
let input = parse_input(raw_input);
use std::time::Instant;
let now = Instant::now();
let solution = (part1(&input), part2(&input));
let elapsed = now.elapsed();
(solution, elapsed)
}
|
const N: usize = 8;
fn try(mut board: &mut [[bool; N]; N], row: usize, mut count: &mut i64) {
if row == N {
*count += 1;
for r in board.iter() {
println!("{}", r.iter().map(|&x| if x {"x"} else {"."}.to_string()).collect::<Vec<String>>().join(" "))
}
println!("");
return
}
for i in 0..N {
let mut ok: bool = true;
for j in 0..row {
if board[j][i]
|| i+j >= row && board[j][i+j-row]
|| i+row < N+j && board[j][i+row-j]
{ ok = false }
}
if ok {
board[row][i] = true;
try(&mut board, row+1, &mut count);
board[row][i] = false;
}
}
}
fn main() {
let mut board: [[bool; N]; N] = [[false; N]; N];
let mut count: i64 = 0;
try (&mut board, 0, &mut count);
println!("Found {} solutions", count)
}
|
mod server;
mod ws_server;
pub use server::start;
|
#[doc = "Register `RCC_MP_MLAHBENSETR` reader"]
pub type R = crate::R<RCC_MP_MLAHBENSETR_SPEC>;
#[doc = "Register `RCC_MP_MLAHBENSETR` writer"]
pub type W = crate::W<RCC_MP_MLAHBENSETR_SPEC>;
#[doc = "Field `RETRAMEN` reader - RETRAMEN"]
pub type RETRAMEN_R = crate::BitReader;
#[doc = "Field `RETRAMEN` writer - RETRAMEN"]
pub type RETRAMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bit 4 - RETRAMEN"]
#[inline(always)]
pub fn retramen(&self) -> RETRAMEN_R {
RETRAMEN_R::new(((self.bits >> 4) & 1) != 0)
}
}
impl W {
#[doc = "Bit 4 - RETRAMEN"]
#[inline(always)]
#[must_use]
pub fn retramen(&mut self) -> RETRAMEN_W<RCC_MP_MLAHBENSETR_SPEC, 4> {
RETRAMEN_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "This register is used to set the peripheral clock enable bit\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`rcc_mp_mlahbensetr::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`rcc_mp_mlahbensetr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct RCC_MP_MLAHBENSETR_SPEC;
impl crate::RegisterSpec for RCC_MP_MLAHBENSETR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`rcc_mp_mlahbensetr::R`](R) reader structure"]
impl crate::Readable for RCC_MP_MLAHBENSETR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`rcc_mp_mlahbensetr::W`](W) writer structure"]
impl crate::Writable for RCC_MP_MLAHBENSETR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets RCC_MP_MLAHBENSETR to value 0x10"]
impl crate::Resettable for RCC_MP_MLAHBENSETR_SPEC {
const RESET_VALUE: Self::Ux = 0x10;
}
|
pub mod data;
pub mod dataset;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.