blob_id
stringlengths 40
40
| language
stringclasses 1
value | repo_name
stringlengths 5
140
| path
stringlengths 5
183
| src_encoding
stringclasses 6
values | length_bytes
int64 12
5.32M
| score
float64 2.52
4.94
| int_score
int64 3
5
| detected_licenses
listlengths 0
47
| license_type
stringclasses 2
values | text
stringlengths 12
5.32M
| download_success
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
4b1bb07f27f7ba4be9279adeb57188c316fe03c5
|
Rust
|
andrewwhitehead/suspend-rs
|
/suspend-channel/src/error.rs
|
UTF-8
| 1,647
| 3.40625
| 3
|
[
"Apache-2.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
use core::fmt::{self, Display, Formatter};
/// An error indicating that a receive operation could not be completed
#[derive(Debug, PartialEq, Eq, Hash)]
pub enum RecvError {
/// The sender dropped before producing a message
Incomplete,
/// The receiver has already produced a result
Terminated,
/// No message was received in time
TimedOut,
}
impl RecvError {
/// A helper function to check for a timeout
pub fn timed_out(&self) -> bool {
matches!(self, Self::TimedOut)
}
}
impl Display for RecvError {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::Incomplete => "Incomplete",
Self::Terminated => "Terminated",
Self::TimedOut => "Timed out",
})
}
}
#[cfg(feature = "std")]
impl ::std::error::Error for RecvError {}
/// An error indicating that a `try_send` operation could not be completed
#[derive(Debug, PartialEq, Eq, Hash)]
pub enum TrySendError<T> {
/// The receiver has been dropped
Disconnected(T),
/// The channel is full
Full(T),
}
impl<T> TrySendError<T> {
/// Determine whether the send failed because the receiver was dropped
pub fn is_disconnected(&self) -> bool {
matches!(self, Self::Disconnected(..))
}
/// Determine whether the send failed because the channel is already full
pub fn is_full(&self) -> bool {
matches!(self, Self::Full(..))
}
/// Unwrap the inner value from the error
pub fn into_inner(self) -> T {
match self {
Self::Disconnected(val) | Self::Full(val) => val,
}
}
}
| true
|
a5f1f62f8d6b1a5c1c5e4c6da7b71a05f9da300c
|
Rust
|
hawkw/mycelium
|
/maitake/src/scheduler/steal.rs
|
UTF-8
| 11,939
| 3.09375
| 3
|
[
"MIT"
] |
permissive
|
use super::*;
use crate::loom::sync::atomic::AtomicUsize;
use cordyceps::mpsc_queue::{self, MpscQueue};
use core::marker::PhantomData;
use mycelium_util::fmt;
/// An injector queue for spawning tasks on multiple [`Scheduler`] instances.
pub struct Injector<S> {
/// The queue.
queue: MpscQueue<Header>,
/// The number of tasks in the queue.
tasks: AtomicUsize,
/// An `Injector` can only be used with [`Schedule`] implementations that
/// are the same type, because the task allocation is sized based on the
/// scheduler value.
_scheduler_type: PhantomData<fn(S)>,
}
/// A handle for stealing tasks from a [`Scheduler`]'s run queue, or an
/// [`Injector`] queue.
///
/// While this handle exists, no other worker can steal tasks from the queue.
pub struct Stealer<'worker, S> {
queue: mpsc_queue::Consumer<'worker, Header>,
/// The initial task count in the target queue when this `Stealer` was created.
snapshot: usize,
/// A reference to the target queue's current task count. This is used to
/// decrement the task count when stealing.
tasks: &'worker AtomicUsize,
/// The type of the [`Schedule`] implementation that tasks are being stolen
/// from.
///
/// This must be the same type as the scheduler that is stealing tasks, as
/// the size of the scheduler value stored in the task must be the same.
_scheduler_type: PhantomData<fn(S)>,
}
/// Errors returned by [`Injector::try_steal`], [`Scheduler::try_steal`], and
/// [`StaticScheduler::try_steal`].
#[derive(Debug, Clone, Eq, PartialEq)]
#[non_exhaustive]
pub enum TryStealError {
/// Tasks could not be stolen because the targeted queue already has a
/// consumer.
Busy,
/// No tasks were available to steal.
Empty,
}
impl<S: Schedule> Injector<S> {
/// Returns a new injector queue.
///
/// # Safety
///
/// The "stub" provided must ONLY EVER be used for a single
/// `Injector` instance. Re-using the stub for multiple distributors
/// or schedulers may lead to undefined behavior.
#[must_use]
#[cfg(not(loom))]
pub const unsafe fn new_with_static_stub(stub: &'static TaskStub) -> Self {
Self {
queue: MpscQueue::new_with_static_stub(&stub.hdr),
tasks: AtomicUsize::new(0),
_scheduler_type: PhantomData,
}
}
/// Spawns a pre-allocated task on the injector queue.
///
/// The spawned task will be executed by any
/// [`Scheduler`]/[`StaticScheduler`] instance that runs tasks from this
/// queue.
///
/// This method is used to spawn a task that requires some bespoke
/// procedure of allocation, typically of a custom [`Storage`] implementor.
/// See the documentation for the [`Storage`] trait for more details on
/// using custom task storage.
///
/// When the "alloc" feature flag is available, tasks that do not require
/// custom storage may be spawned using the [`Injector::spawn`] method,
/// instead.
///
/// This method returns a [`JoinHandle`] that can be used to await the
/// task's output. Dropping the [`JoinHandle`] _detaches_ the spawned task,
/// allowing it to run in the background without awaiting its output.
///
/// [`Storage`]: crate::task::Storage
pub fn spawn_allocated<STO, F>(&self, task: STO::StoredTask) -> JoinHandle<F::Output>
where
F: Future + Send + 'static,
F::Output: Send + 'static,
STO: Storage<S, F>,
{
self.tasks.fetch_add(1, Relaxed);
let (task, join) = TaskRef::build_allocated::<S, F, STO>(TaskRef::NO_BUILDER, task);
self.queue.enqueue(task);
join
}
/// Attempt to take tasks from the injector queue.
///
/// # Returns
///
/// - `Ok(`[`Stealer`]`)) if tasks can be spawned from the injector
/// queue.
/// - `Err`([`TryStealError::Empty`]`)` if there were no tasks in this
/// injector queue.
/// - `Err`([`TryStealError::Busy`]`)` if another worker was already
/// taking tasks from this injector queue.
pub fn try_steal(&self) -> Result<Stealer<'_, S>, TryStealError> {
Stealer::try_new(&self.queue, &self.tasks)
}
}
impl<S> fmt::Debug for Injector<S> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// determine if alt-mode is enabled *before* constructing the
// `DebugStruct`, because that mutably borrows the formatter.
let alt = f.alternate();
let Self {
queue,
tasks,
_scheduler_type,
} = self;
let mut debug = f.debug_struct("Injector");
debug
.field("queue", queue)
.field("tasks", &tasks.load(Relaxed));
// only include the kind of wordy type name field if alt-mode
// (multi-line) formatting is enabled.
if alt {
debug.field(
"scheduler",
&format_args!("PhantomData<{}>", core::any::type_name::<S>()),
);
}
debug.finish()
}
}
// === impl Stealer ===
impl<'worker, S: Schedule> Stealer<'worker, S> {
fn try_new(
queue: &'worker MpscQueue<Header>,
tasks: &'worker AtomicUsize,
) -> Result<Self, TryStealError> {
let snapshot = tasks.load(Acquire);
if snapshot == 0 {
return Err(TryStealError::Empty);
}
let queue = queue.try_consume().ok_or(TryStealError::Busy)?;
Ok(Self {
queue,
snapshot,
tasks,
_scheduler_type: PhantomData,
})
}
/// Returns the number of tasks that were in the targeted queue when this
/// `Stealer` was created.
///
/// This number is *not* guaranteed to be greater than the *current* number
/// of tasks returned by [`task_count`], as new tasks may be enqueued while
/// stealing.
///
/// [`task_count`]: Self::task_count
pub fn initial_task_count(&self) -> usize {
self.snapshot
}
/// Returns the number of tasks currently in the targeted queue.
pub fn task_count(&self) -> usize {
self.tasks.load(Acquire)
}
/// Steal one task from the targeted queue and spawn it on the provided
/// `scheduler`.
///
/// # Returns
///
/// - `true` if a task was successfully stolen.
/// - `false` if the targeted queue is empty.
pub fn spawn_one(&self, scheduler: &S) -> bool {
let Some(task) = self.queue.dequeue() else { return false };
test_trace!(?task, "stole");
// decrement the target queue's task count
self.tasks.fetch_sub(1, Release);
// TODO(eliza): probably handle cancelation by throwing out canceled
// tasks here before binding them?
unsafe {
task.bind_scheduler(scheduler.clone());
}
scheduler.schedule(task);
true
}
/// Steal up to `max` tasks from the targeted queue and spawn them on the
/// provided scheduler.
///
/// # Returns
///
/// The number of tasks stolen. This may be less than `max` if the targeted
/// queue contained fewer tasks than `max`.
pub fn spawn_n(&self, scheduler: &S, max: usize) -> usize {
let mut stolen = 0;
while stolen <= max && self.spawn_one(scheduler) {
stolen += 1;
}
stolen
}
/// Steal half of the tasks currently in the targeted queue and spawn them
/// on the provided scheduler.
///
/// This is a convenience method that is equivalent to the following:
///
/// ```
/// # fn docs() {
/// # use maitake::scheduler::{StaticScheduler, Stealer};
/// # let scheduler = unimplemented!();
/// # let stealer: Stealer<'_, &'static StaticScheduler> = unimplemented!();
/// stealer.spawn_n(&scheduler, stealer.initial_task_count() / 2);
/// # }
/// ```
///
/// # Returns
///
/// The number of tasks stolen.
pub fn spawn_half(&self, scheduler: &S) -> usize {
self.spawn_n(scheduler, self.initial_task_count() / 2)
}
}
impl<S> fmt::Debug for Stealer<'_, S> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// determine if alt-mode is enabled *before* constructing the
// `DebugStruct`, because that mutably borrows the formatter.
let alt = f.alternate();
let Self {
queue,
snapshot,
tasks,
_scheduler_type,
} = self;
let mut debug = f.debug_struct("Stealer");
debug
.field("queue", queue)
.field("snapshot", snapshot)
.field("tasks", &tasks.load(Relaxed));
// only include the kind of wordy type name field if alt-mode
// (multi-line) formatting is enabled.
if alt {
debug.field(
"scheduler",
&format_args!("PhantomData<{}>", core::any::type_name::<S>()),
);
}
debug.finish()
}
}
// === impls on Scheduler types ===
impl StaticScheduler {
/// Attempt to steal tasks from this scheduler's run queue.
///
/// # Returns
///
/// - `Ok(`[`Stealer`]`)) if tasks can be stolen from this scheduler's
/// queue.
/// - `Err`([`TryStealError::Empty`]`)` if there were no tasks in this
/// scheduler's run queue.
/// - `Err`([`TryStealError::Busy`]`)` if another worker was already
/// stealing from this scheduler's run queue.
pub fn try_steal(&self) -> Result<Stealer<'_, &'static StaticScheduler>, TryStealError> {
Stealer::try_new(&self.0.run_queue, &self.0.queued)
}
}
feature! {
#![feature = "alloc"]
use alloc::boxed::Box;
use super::{BoxStorage, Task};
impl<S: Schedule> Injector<S> {
/// Returns a new `Injector` queue with a dynamically heap-allocated
/// [`TaskStub`].
#[must_use]
pub fn new() -> Self {
let stub_task = Box::new(Task::new_stub());
let (stub_task, _) =
TaskRef::new_allocated::<task::Stub, task::Stub, BoxStorage>(task::Stub, stub_task);
Self {
queue: MpscQueue::new_with_stub(stub_task),
tasks: AtomicUsize::new(0),
_scheduler_type: PhantomData,
}
}
/// Spawns a new task on the injector queue, to execute on any
/// [`Scheduler`]/[`StaticScheduler`] instance that runs tasks from this
/// queue.
///
/// This method returns a [`JoinHandle`] that can be used to await the
/// task's output. Dropping the [`JoinHandle`] _detaches_ the spawned task,
/// allowing it to run in the background without awaiting its output.
#[inline]
#[track_caller]
pub fn spawn<F>(&self, future: F) -> JoinHandle<F::Output>
where
F: Future + Send + 'static,
F::Output: Send + 'static,
{
let task = Box::new(Task::<S, _, BoxStorage>::new(future));
self.spawn_allocated::<BoxStorage, _>(task)
}
}
impl<S: Schedule> Default for Injector<S> {
fn default() -> Self {
Self::new()
}
}
impl Scheduler {
/// Attempt to steal tasks from this scheduler's run queue.
///
/// # Returns
///
/// - `Ok(`[`Stealer`]`)) if tasks can be stolen from this scheduler's
/// queue.
/// - `Err`([`TryStealError::Empty`]`)` if there were no tasks in this
/// scheduler's run queue.
/// - `Err`([`TryStealError::Busy`]`)` if another worker was already
/// stealing from this scheduler's run queue.
pub fn try_steal(&self) -> Result<Stealer<'_, Scheduler>, TryStealError> {
Stealer::try_new(&self.0.run_queue, &self.0.queued)
}
}
}
| true
|
0605e1e8daba42458b03336a1280ae23493ae9b0
|
Rust
|
dbrgn/nacl-selective-keygen
|
/src/main.rs
|
UTF-8
| 1,104
| 2.84375
| 3
|
[] |
no_license
|
extern crate sodiumoxide;
use std::env;
use std::process;
use sodiumoxide::crypto::box_;
pub fn to_hex_string(bytes: Box<[u8]>) -> String {
bytes.iter()
.map(|b| format!("{:02x}", b))
.collect::<Vec<_>>()
.join("")
}
fn main() {
// Parse args
let args: Vec<String> = env::args().collect();
if args.len() != 2 {
println!("Usage: {} <pattern>", &args[0]);
process::exit(1);
}
// Get pattern
let pattern: String = args[1].to_string();
println!("Searching for keypair that starts with {}...\n", &pattern);
// Run
let mut i = 0;
loop {
if i % 1000 == 0 {
println!("Iteration {}...", i);
}
let (pk, sk) = box_::gen_keypair();
let pk_hex = to_hex_string(Box::new(pk.0));
if pk_hex.starts_with(&pattern) {
let sk_hex = to_hex_string(Box::new(sk.0));
println!("\n==> Public: {}", pk_hex);
println!("==> Secret: {}", sk_hex);
println!("\nFound key after {} iterations.", i);
break;
}
i += 1;
}
}
| true
|
d39ccdcb758c6b47a2dd332d0f75dc3e15d2633a
|
Rust
|
alusch/flipdot
|
/libs/core/src/sign_bus.rs
|
UTF-8
| 2,663
| 3.28125
| 3
|
[
"MIT"
] |
permissive
|
use std::error::Error;
use std::fmt::{self, Debug, Formatter};
use crate::Message;
/// Abstraction over a bus containing devices that are able to send and receive [`Message`]s.
///
/// Typically `SerialSignBus` from [`flipdot`] or `VirtualSignBus` from [`flipdot-testing`] are sufficient,
/// and you do not need to implement this yourself.
///
/// # Examples
///
/// Using `SignBus` as a trait object to allow choosing the type of bus at runtime:
///
/// ```
/// use std::cell::RefCell;
/// use std::rc::Rc;
/// use flipdot::{Address, Sign, SignBus, SignType};
/// use flipdot::serial::SerialSignBus;
/// use flipdot_testing::{VirtualSign, VirtualSignBus};
///
/// # fn use_serial() -> bool { false }
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// #
/// let bus: Rc<RefCell<SignBus>> = if use_serial() {
/// let port = serial::open("/dev/ttyUSB0")?;
/// Rc::new(RefCell::new(SerialSignBus::try_new(port)?))
/// } else {
/// Rc::new(RefCell::new(VirtualSignBus::new(vec![VirtualSign::new(Address(3))])))
/// };
///
/// let sign = Sign::new(bus.clone(), Address(3), SignType::Max3000Side90x7);
/// sign.configure()?;
/// #
/// # Ok(()) }
/// ```
///
/// Implementing a custom bus:
///
/// ```
/// use flipdot_core::{Message, SignBus, State};
///
/// struct ExampleSignBus {}
///
/// impl SignBus for ExampleSignBus {
/// fn process_message<'a>(&mut self, message: Message)
/// -> Result<Option<Message<'a>>, Box<dyn std::error::Error + Send + Sync>> {
/// match message {
/// Message::Hello(address) |
/// Message::QueryState(address) =>
/// Ok(Some(Message::ReportState(address, State::Unconfigured))),
/// _ => Ok(None), // Implement rest of protocol here...
/// }
/// }
/// }
/// ```
///
/// [`flipdot`]: https://docs.rs/flipdot
/// [`flipdot-testing`]: https://docs.rs/flipdot_testing
pub trait SignBus {
/// Sends a message to the bus and returns an optional response.
///
/// The caller is the "controller" (e.g. an ODK), and this method conceptually delivers the message
/// to a certain sign on the bus and returns an optional response from it.
///
/// # Examples
///
/// See the [trait-level documentation].
///
/// [trait-level documentation]: #examples
fn process_message<'a>(&mut self, message: Message<'_>) -> Result<Option<Message<'a>>, Box<dyn Error + Send + Sync>>;
}
// Provide a Debug representation so types that contain trait objects can derive Debug.
impl Debug for dyn SignBus {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "<SignBus trait>")
}
}
| true
|
fcb0d280e2da0eda6f74a63548f6a84431aeb703
|
Rust
|
kazzix14/comment-feed
|
/comment-feed-ws-set-channel/src/main.rs
|
UTF-8
| 3,069
| 2.59375
| 3
|
[] |
no_license
|
use dynomite::{Item, Attribute, FromAttributes};
use lambda::lambda;
use lambda_runtime as lambda;
use log::{error, info};
use rusoto_core::Region;
use rusoto_dynamodb::{DynamoDb, DynamoDbClient, PutItemInput, DeleteItemInput, QueryInput, GetItemInput};
use serde_derive::{Deserialize, Serialize};
use serde_json;
use simple_logger;
use rusoto_apigatewaymanagementapi::{ApiGatewayManagementApi, ApiGatewayManagementApiClient, PostToConnectionRequest};
use futures::stream::{futures_unordered::FuturesUnordered, StreamExt};
use lambda::error::HandlerError;
use std::{error::Error, collections::HashMap};
#[derive(Item)]
struct WSConnection {
#[dynomite(partition_key)]
channel: String,
#[dynomite(sort_key)]
#[dynomite(rename = "connectionId")]
connection_id: String,
}
#[derive(Deserialize, Clone)]
struct CustomEvent {
#[serde(rename = "requestContext")]
request_context: RequestContext,
body: String,
}
#[derive(Deserialize, Clone)]
struct RequestContext {
#[serde(rename = "connectionId")]
connection_id: String,
}
#[derive(Deserialize, Clone)]
struct CustomBody {
channel: String,
new_channel: String,
}
#[derive(Serialize, Clone)]
struct CustomOutput {
#[serde(rename = "statusCode")]
status_code: u32,
}
fn main() -> Result<(), Box<dyn Error>> {
simple_logger::init_with_level(log::Level::Info)?;
lambda!(my_handler);
Ok(())
}
fn my_handler(e: CustomEvent, c: lambda::Context) -> Result<CustomOutput, HandlerError> {
let connection_id = e.request_context.connection_id;
let body = serde_json::from_str::<CustomBody>(&e.body).expect("malformed data");
let channel = body.channel;
let new_channel = body.new_channel;
// we can not update key
// so delete the item and add it again
let client = DynamoDbClient::new(Region::ApNortheast1);
let mut rt = tokio::runtime::Runtime::new().unwrap();
rt.block_on(async {
let mut item = WSConnection {
channel: channel,
connection_id: connection_id,
};
let input = DeleteItemInput {
table_name: "websocket.comment-feed".to_string(),
key: item.key(),
..DeleteItemInput::default()
};
match client.delete_item(input).await {
Ok(output) => {
info!("delete!");
}
Err(error) => {
error!("Error: {:?}", error);
}
}
item.channel = new_channel;
let input = PutItemInput {
table_name: "websocket.comment-feed".to_string(),
item: item.into(),
..PutItemInput::default()
};
match client.put_item(input).await {
Ok(output) => {
info!("ok!! put dynamodb");
Ok(CustomOutput {
status_code: 200
})
}
Err(error) => {
error!("Error: {:?}", error);
Err(c.new_error(&format!("Error: {:?}", error)))
}
}
})
}
| true
|
3345224f67d5cd7f53d25aa8ac39cc747a30f687
|
Rust
|
ruma/ruma
|
/crates/ruma-macros/src/serde/enum_from_string.rs
|
UTF-8
| 3,345
| 2.546875
| 3
|
[
"MIT"
] |
permissive
|
use proc_macro2::{Span, TokenStream};
use quote::{quote, ToTokens};
use syn::{Fields, FieldsNamed, FieldsUnnamed, ItemEnum};
use super::{
attr::EnumAttrs,
util::{get_enum_attributes, get_rename_rule},
};
pub fn expand_enum_from_string(input: &ItemEnum) -> syn::Result<TokenStream> {
let enum_name = &input.ident;
let rename_rule = get_rename_rule(input)?;
let mut fallback = None;
let branches: Vec<_> = input
.variants
.iter()
.map(|v| {
let variant_name = &v.ident;
let EnumAttrs { rename, aliases } = get_enum_attributes(v)?;
let variant_str = match (rename, &v.fields) {
(None, Fields::Unit) => Some(
rename_rule.apply_to_variant(&variant_name.to_string()).into_token_stream(),
),
(Some(rename), Fields::Unit) => Some(rename.into_token_stream()),
(None, Fields::Named(FieldsNamed { named: fields, .. }))
| (None, Fields::Unnamed(FieldsUnnamed { unnamed: fields, .. })) => {
if fields.len() != 1 {
return Err(syn::Error::new_spanned(
v,
"multiple data fields are not supported",
));
}
if fallback.is_some() {
return Err(syn::Error::new_spanned(
v,
"multiple data-carrying variants are not supported",
));
}
let member = match &fields[0].ident {
Some(name) => name.into_token_stream(),
None => quote! { 0 },
};
let ty = &fields[0].ty;
fallback = Some(quote! {
_ => #enum_name::#variant_name {
#member: #ty(s.into()),
}
});
None
}
(Some(_), _) => {
return Err(syn::Error::new_spanned(
v,
"ruma_enum(rename) is only allowed on unit variants",
));
}
};
Ok(variant_str.map(|s| {
quote! {
#( #aliases => #enum_name :: #variant_name, )*
#s => #enum_name :: #variant_name
}
}))
})
.collect::<syn::Result<_>>()?;
// Remove `None` from the iterator to avoid emitting consecutive commas in repetition
let branches = branches.iter().flatten();
if fallback.is_none() {
return Err(syn::Error::new(Span::call_site(), "required fallback variant not found"));
}
Ok(quote! {
#[automatically_derived]
#[allow(deprecated)]
impl<T> ::std::convert::From<T> for #enum_name
where
T: ::std::convert::AsRef<::std::primitive::str>
+ ::std::convert::Into<::std::boxed::Box<::std::primitive::str>>
{
fn from(s: T) -> Self {
match s.as_ref() {
#( #branches, )*
#fallback
}
}
}
})
}
| true
|
75879dbd9a7225906a13ab75935975c6e3bd5643
|
Rust
|
rust-lang-cn/book-cn
|
/listings/ch09-error-handling/no-listing-03-closures/src/main.rs
|
UTF-8
| 408
| 2.984375
| 3
|
[
"MIT",
"Apache-2.0"
] |
permissive
|
use std::fs::File;
use std::io::ErrorKind;
fn main() {
let f = File::open("hello.txt").unwrap_or_else(|error| {
if error.kind() == ErrorKind::NotFound {
File::create("hello.txt").unwrap_or_else(|error| {
panic!("Problem creating the file: {:?}", error);
})
} else {
panic!("Problem opening the file: {:?}", error);
}
});
}
| true
|
ff16840c0bdd2c938197b73dd66dfce0f0ecbe4d
|
Rust
|
jazz-lang/Jazz-jit
|
/src/dseg.rs
|
UTF-8
| 3,168
| 3.234375
| 3
|
[
"Apache-2.0"
] |
permissive
|
///! TODO: Don't use Data segment at all
use crate::align;
use core::mem::size_of;
#[derive(Debug, Clone)]
#[repr(C)]
pub struct DSeg {
entries: Vec<Entry>,
size: i32,
}
#[derive(Debug, Clone)]
#[repr(C)]
pub struct Entry {
disp: i32,
value: Value,
}
#[derive(Copy, Clone, Debug, PartialEq)]
#[repr(C)]
pub struct f32x4(pub f32, pub f32, pub f32, pub f32);
#[derive(Debug, PartialEq, Clone)]
#[repr(C)]
pub enum Value {
Ptr(*const u8),
Float(f32),
Double(f64),
Int(i32),
F4(f32x4),
}
impl Value {
pub extern "C" fn size(&self) -> i32 {
match self {
&Value::Ptr(_) => size_of::<*const u8>() as i32,
&Value::Int(_) => size_of::<i32>() as i32,
&Value::Float(_) => size_of::<f32>() as i32,
&Value::Double(_) => size_of::<f64>() as i32,
&Value::F4(_) => size_of::<f32x4>() as i32,
}
}
}
impl DSeg {
pub extern "C" fn new() -> DSeg {
DSeg { entries: Vec::new(),
size: 0 }
}
pub extern "C" fn size(&self) -> i32 { self.size }
fn add_value(&mut self, v: Value) -> i32 {
let size = v.size();
self.size = align(self.size() + size, size);
let entry = Entry { disp: self.size(),
value: v };
self.entries.push(entry);
self.size
}
pub extern "C" fn finish(&self, ptr: *const u8) {
for entry in &self.entries {
let offset = self.size - entry.disp;
unsafe {
let entry_ptr = ptr.offset(offset as isize);
match entry.value {
Value::Ptr(v) => *(entry_ptr as *mut (*const u8)) = v,
Value::Float(v) => {
*(entry_ptr as *mut f32) = v;
}
Value::Double(v) => {
*(entry_ptr as *mut f64) = v;
}
Value::Int(v) => {
*(entry_ptr as *mut i32) = v;
}
Value::F4(v) => {
*(entry_ptr as *mut f32x4) = v;
}
}
}
}
}
pub extern "C" fn add_addr_reuse(&mut self, ptr: *const u8) -> i32 {
for entry in &self.entries {
if entry.value == Value::Ptr(ptr) {
return entry.disp;
}
}
self.add_addr(ptr)
}
pub extern "C" fn add_f32x4(&mut self, value: f32x4) -> i32 { self.add_value(Value::F4(value)) }
pub extern "C" fn add_int(&mut self, value: i32) -> i32 { self.add_value(Value::Int(value)) }
pub extern "C" fn add_addr(&mut self, value: *const u8) -> i32 {
self.add_value(Value::Ptr(value))
}
pub extern "C" fn add_double(&mut self, value: f64) -> i32 {
self.add_value(Value::Double(value))
}
pub extern "C" fn add_float(&mut self, value: f32) -> i32 {
self.add_value(Value::Float(value))
}
pub extern "C" fn align(&mut self, size: i32) -> i32 {
assert!(size > 0);
self.size = align(self.size, size);
self.size
}
}
| true
|
eca0fc4debb9c15aad90f2bbfd4c495fac5a994b
|
Rust
|
mesalock-linux/rustcrypto-stream-ciphers-sgx
|
/aes-ctr/src/lib.rs
|
UTF-8
| 2,628
| 2.8125
| 3
|
[
"LicenseRef-scancode-warranty-disclaimer",
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] |
permissive
|
//! AES-CTR ciphers implementation.
//!
//! Cipher functionality is accessed using traits from re-exported
//! [`stream-cipher`](https://docs.rs/stream-cipher) crate.
//!
//! This crate will select appropriate implementation at compile time depending
//! on target architecture and enabled target features. For the best performance
//! on x86-64 CPUs enable `aes`, `sse2` and `ssse3` target features. You can do
//! it either by using `RUSTFLAGS="-C target-feature=+aes,+ssse3"` or by editing
//! your `.cargo/config`. (`sse2` target feature is usually enabled by default)
//!
//! # Security Warning
//! This crate does not ensure ciphertexts are authentic! Thus ciphertext integrity
//! is not verified, which can lead to serious vulnerabilities!
//!
//! # Usage example
//! ```
//! use aes_ctr::Aes128Ctr;
//! use aes_ctr::stream_cipher::generic_array::GenericArray;
//! use aes_ctr::stream_cipher::{
//! NewStreamCipher, SyncStreamCipher, SyncStreamCipherSeek
//! };
//!
//! let mut data = [1, 2, 3, 4, 5, 6, 7];
//!
//! let key = GenericArray::from_slice(b"very secret key.");
//! let nonce = GenericArray::from_slice(b"and secret nonce");
//! // create cipher instance
//! let mut cipher = Aes128Ctr::new(&key, &nonce);
//! // apply keystream (encrypt)
//! cipher.apply_keystream(&mut data);
//! assert_eq!(data, [6, 245, 126, 124, 180, 146, 37]);
//!
//! // seek to the keystream beginning and apply it again to the `data` (decrypt)
//! cipher.seek(0);
//! cipher.apply_keystream(&mut data);
//! assert_eq!(data, [1, 2, 3, 4, 5, 6, 7]);
//! ```
#![no_std]
#![deny(missing_docs)]
//#[cfg(not(all(
// target_feature = "aes",
// target_feature = "sse2",
// target_feature = "ssse3",
// any(target_arch = "x86_64", target_arch = "x86"),
//)))]
//extern crate aes_soft;
//#[cfg(not(all(
// target_feature = "aes",
// target_feature = "sse2",
// target_feature = "ssse3",
// any(target_arch = "x86_64", target_arch = "x86"),
//)))]
//extern crate ctr;
pub extern crate stream_cipher;
//#[cfg(not(all(
// target_feature = "aes",
// target_feature = "sse2",
// target_feature = "ssse3",
// any(target_arch = "x86_64", target_arch = "x86"),
//)))]
//mod dummy;
//#[cfg(all(
// target_feature = "aes",
// target_feature = "sse2",
// target_feature = "ssse3",
// any(target_arch = "x86_64", target_arch = "x86"),
//))]
extern crate aesni;
//#[cfg(all(
// target_feature = "aes",
// target_feature = "sse2",
// target_feature = "ssse3",
// any(target_arch = "x86_64", target_arch = "x86"),
//))]
use aesni as dummy;
pub use dummy::{Aes128Ctr, Aes192Ctr, Aes256Ctr};
| true
|
dec0dd857d3178b9cc2701864c87b789de512beb
|
Rust
|
SteadBytes/study
|
/the-rust-programming-language/projects/traits/src/main.rs
|
UTF-8
| 3,232
| 3.5
| 4
|
[] |
no_license
|
use std::fmt::Display;
pub trait Summary {
fn summarise_author(&self) -> String;
// Default implementation
fn summarise(&self) -> String {
// Can call other methods in the same trait
format!("(Read more from {}...)", self.summarise_author())
}
}
pub struct Reporter {
pub name: String,
pub age: i32,
}
pub struct NewsArticle {
pub headline: String,
pub location: String,
pub author: Reporter,
pub content: String,
}
impl Summary for NewsArticle {
fn summarise_author(&self) -> String {
format!("{}, {}", self.author.name, self.author.age)
}
fn summarise(&self) -> String {
format!(
"{}, by {}, ({})",
self.headline,
self.summarise_author(),
self.location
)
}
}
pub struct Tweet {
pub username: String,
pub content: String,
pub reply: bool,
pub retweet: bool,
}
// Use default summarise implementation
impl Summary for Tweet {
fn summarise_author(&self) -> String {
format!("@{}", self.username)
}
}
// Trait to constrain function parameter
pub fn notify(item: impl Summary) {
println!("Breaking news! {}", item.summarise())
}
// Or with trait bound syntax
// pub fn notify<T: Summary>(item: T) {
// Multiple traits
fn some_function(thing: impl Clone + Ord + Display) {}
// Using a where clause
fn some_other_function<T, U>(t: T, u: U)
where
T: Display + Ord,
U: Clone + Ord,
{
}
// Function that returns a type implementing a trait
fn returns_summarizable() -> impl Summary {
Tweet {
username: String::from("steadbytes"),
content: String::from("Never laugh at live dragons."),
reply: false,
retweet: false,
}
}
// Note: Cannot use return imple Trait if returning multiple types
// This will not compile
// fn returns_summarizable(switch: bool) -> impl Summary {
// if switch {
// NewsArticle {
// headline: String::from("Smaug wakes from slumber!"),
// location: String::from("The Lonely Mountain"),
// author: Reporter {
// name: String::from("Gandalf"),
// age: 60,
// },
// content: String::from("Bilbo woke Smaug and now he's angry."),
// }
// } else {
// Tweet {
// username: String::from("steadbytes"),
// content: String::from("Never laugh at live dragons."),
// reply: false,
// retweet: false,
// }
// }
// }
fn main() {
let tweet = Tweet {
username: String::from("steadbytes"),
content: String::from("Never laugh at live dragons."),
reply: false,
retweet: false,
};
// Uses default summarise implementation
println!("1 new tweet: {}", tweet.summarise());
let article = NewsArticle {
headline: String::from("Smaug wakes from slumber!"),
location: String::from("The Lonely Mountain"),
author: Reporter {
name: String::from("Gandalf"),
age: 60,
},
content: String::from("Bilbo woke Smaug and now he's angry."),
};
println!("1 new news article: {}", article.summarise());
}
| true
|
d375fb865034a3160b95a7aef7a8e4b00c42d154
|
Rust
|
abassibe/Gomoku
|
/src/lib.rs
|
UTF-8
| 2,988
| 2.671875
| 3
|
[] |
no_license
|
use numpy::PyArray2;
use pyo3::exceptions;
use pyo3::prelude::{pymodule, PyModule, PyResult, Python};
use pyo3::types::PyBool;
use goban::Goban;
use node::Node;
use crate::algorithm::Algorithm;
use crate::bitboard::BitBoard;
mod algorithm;
mod bitboard;
mod goban;
mod node;
const DEPTH: u32 = 5;
const WHITE: u8 = 2;
#[pymodule]
fn rust_ext(_py: Python<'_>, _m: &PyModule) -> PyResult<()> {
#[pyfn(_m, "get_next_move")]
/// Interfacing function.
/// Takes the Python GIL, the board in the shape of a 19*19 numpy 2d array, the color of the human player, a boolean that indicates if this is a hint request, and the number of captures made by the human and the ai.
#[allow(unused_variables)]
fn get_next_move(_py: Python<'_>, goban: &PyArray2<u8>, p_color: u8, hint: &PyBool, human_capture: i32, ai_capture: i32, last_move_human : Option<(u16, u16)>, last_move_ai : Option<(u16, u16)>) -> PyResult<(u32, u32)> {
let board:Vec<u8> = goban.to_vec()?;
if board.len() != 361 {
return Err(exceptions::PyTypeError::new_err(format!(
"Fatal Rust Error: Invalid board size (Expected 361, got {})",
board.len()
)));
}
let goban = assign_color_to_ai(vec_to_string(board), p_color);
if goban.get_board().is_empty() {
return Ok((9u32, 9u32));
}
let last_move = last_move_human.or(last_move_ai);
let ret = launch_ai(goban, (ai_capture / 2) as u8, (human_capture / 2) as u8, last_move);
Ok(ret)
}
Ok(())
}
/// Turns the PyArray sent by python into a string that can be turned into a bitboard.
fn vec_to_string(board: Vec<u8>) -> String {
board
.into_iter()
.enumerate()
.map(|(x, i)| {
if x % 19 == 0 {
"\n".to_owned() + &i.to_string()
} else {
i.to_string()
}
})
.collect::<String>()
}
/// Turns the string into two bitboards (player, enemy)
fn assign_color_to_ai(str: String, human: u8) -> Goban {
let player = BitBoard::from_str(&str.replace("2", "0"));
let enemy = BitBoard::from_str(&str.replace("1", "0").replace("2", "1"));
if human == WHITE {
Goban::new(enemy, player)
} else {
Goban::new(player, enemy)
}
}
fn launch_ai(input: Goban, player_captures: u8, opponent_captures: u8, last_move: Option<(u16, u16)>) -> (u32, u32) {
let mut algorithm = Algorithm::new();
let last_move = if let Some(coord) = last_move {
BitBoard::one_bit_from_coord(coord)
} else {
BitBoard::empty()
};
algorithm.update_initial_state(input, last_move, player_captures, opponent_captures);
let ret = algorithm.get_next_move(DEPTH);
get_move_coord(&ret)
}
fn get_move_coord(node: &Node) -> (u32, u32) {
let move_to_play = node.get_last_move();
let i: u32 = *move_to_play.get_bit_indexes().last().unwrap_or(&0) as u32;
(i / 20, i % 20)
}
| true
|
c9def674f766bdf465b2e189586ec362a6c6728c
|
Rust
|
ivardb/AdventOfCode2020
|
/src/days/day4/mod.rs
|
UTF-8
| 617
| 2.734375
| 3
|
[] |
no_license
|
use std::collections::HashMap;
pub mod part1;
pub mod part2;
pub fn default_input() -> &'static str {
include_str!("input")
}
pub fn run() {
part1::run();
part2::run();
}
pub fn parse_input(input : &str) -> Vec<HashMap<String, String>> {
input.split("\n\n")
.map(|p| {
let map : HashMap<String, String> = p.split(&['\n', ' '][..])
.map(|l| {
let split : Vec<_> = l.split(":").collect();
(String::from(split[0].trim()), String::from(split[1]))})
.collect();
map
})
.collect()
}
| true
|
d80a9f46208111293286bd6004f32ad3913d9f45
|
Rust
|
RadicalZephyr/rust-advent-2016
|
/src/bin/day_1.rs
|
UTF-8
| 962
| 2.65625
| 3
|
[] |
no_license
|
#[macro_use]
extern crate advent_2016;
extern crate nom;
use std::fs::File;
use std::io::Read;
use nom::IResult;
use advent_2016::day_1::Instruction;
use advent_2016::day_1::parse;
use advent_2016::day_1::navigation;
pub fn main() {
let mut f = File::open("../../data/day_1.txt").expect("File not found");
let mut s = String::new();
f.read_to_string(&mut s).expect("Couldn't read file into string");
match_parse!{
instructions = parse::instructions(s.as_bytes()) => {
part_1(&instructions);
part_2(&instructions);
}
}
}
fn part_1(instructions: &Vec<Instruction>) {
let hq_location = navigation::Location::new().follow_all_instructions(instructions);
println!("Final location is {:?}", hq_location)
}
fn part_2(instructions: &Vec<Instruction>) {
let hq_location = navigation::Location::new().first_repeated_location(instructions);
println!("Final location is {:?}", hq_location)
}
| true
|
beb51696f5a7f4a14d9941081646509c95ef67f8
|
Rust
|
Sintrastes/pure-prolog-rs
|
/src/unifiable.rs
|
UTF-8
| 2,085
| 3.21875
| 3
|
[
"MIT"
] |
permissive
|
use std::collections::HashMap;
use std::hash::Hash;
use std::fmt::Display;
#[derive(Clone, Debug)]
pub struct Unifier<'a,V,T>(pub HashMap<V, &'a T>);
impl <'a,V,T> Display for Unifier<'a,V,T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "")
}
}
pub trait Compose<V,T> {
fn compose(&self, other: Unifier<V,T>) -> Unifier<V,T>;
}
pub trait Unifiable<'a,T: Clone,V: Eq + Clone + Copy + Hash> {
fn variables(term: &T) -> Vec<V>;
fn subs(unifier: &'a Unifier<'a, V,T>, term: &'a T) -> &'a T;
fn unify(first_term: &T, second_term: &T) -> Option<&'a Unifier<'a, V,T>>;
fn unify_all(first_terms: &'a Vec<T>, second_terms: &'a Vec<T>) -> Option<&'a Unifier<'a, V,T>> {
match (&first_terms[..], &second_terms[..]) {
(&[],&[]) => {
Some(Box::leak(Box::new(Unifier(HashMap::new()))))
}
_ => {
if !(*first_terms).is_empty() && !(*second_terms).is_empty() {
let ts = first_terms[1..].iter();
let rs = second_terms[1..].iter();
let r = &second_terms[0];
let t = &first_terms[0];
use mdo::option::{bind};
mdo! {
u1 =<< Self::unify(&t,&r);
let _ts = Box::leak(Box::new(
ts.map(|x|
Self::subs(u1,x).clone()).collect()
));
let _rs = Box::leak(Box::new(
rs.map(|x|
Self::subs(u1,x).clone()).collect()
));
u2 =<< Self::unify_all(_ts, _rs);
ret Some(Self::compose(u1,u2))
}
} else {
None
}
}
}
}
fn compose(
this: &'a Unifier<'a, V,T>,
other: &'a Unifier<'a, V,T>
) -> &'a Unifier<'a, V,T> {
let Unifier(this_hm) = this;
let Unifier(other_hm) = other;
let mut unifier: HashMap<V, &'a T> = this_hm
.iter().map(|(&x,&y)| {
(x, Self::subs(other, y))
}).collect();
unifier.extend(other_hm.clone());
return Box::leak(Box::new(Unifier(unifier)));
}
}
| true
|
3e34aa537a6c04d34fc03c0bfba5db8f249735e9
|
Rust
|
tenheadedlion/nand2tetris
|
/projects/06/assembler/src/model/error.rs
|
UTF-8
| 1,110
| 2.875
| 3
|
[] |
no_license
|
#[derive(Debug)]
pub struct HackError {
pub source_line_num: Option<usize>,
pub source_line: Option<String>,
pub comment: String,
}
impl std::fmt::Display for HackError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
writeln!(
f,
"[{}]: {}: {}",
self.source_line_num.as_ref().unwrap(),
self.source_line.as_ref().unwrap(),
self.comment
)
}
}
impl std::error::Error for HackError {}
#[macro_export]
macro_rules! hack_report {
($parg:ident, $comment: expr) => {{
return Err(Box::new(HackError {
source_line_num: Some($parg.line_num()),
source_line: Some($parg.content.clone()),
comment: $comment.to_string(),
}
));
}};
}
#[macro_export]
macro_rules! hack_report_less {
($comment: expr) => {{
return Err(Box::new(
HackError {
source_line_num: None,
source_line: None,
comment: $comment.to_string(),
}
));
}};
}
| true
|
c071bf3b7f913dca7cd7c43e67b773c8d3119a95
|
Rust
|
mkhan45/flappy-macroquad
|
/src/main.rs
|
UTF-8
| 4,033
| 2.875
| 3
|
[] |
no_license
|
use macroquad::prelude::*;
use specs::{prelude::*, Component};
#[derive(Component)]
struct Bird {
pub y_pos: f32,
pub y_vel: f32,
}
impl Default for Bird {
fn default() -> Self {
Bird {
y_pos: screen_height() / 3.0,
y_vel: -50.0,
}
}
}
// just store the coordinates of the gap
#[derive(Component)]
struct PipePair {
x: f32,
y: f32,
}
impl PipePair {
fn new(x: f32) -> Self {
let y = rand::gen_range(screen_height() / 4.0, screen_height() * 3.0 / 4.0);
PipePair { x, y }
}
fn reset(&mut self) {
self.y = rand::gen_range(screen_height() / 4.0, screen_height() * 3.0 / 4.0);
self.x = screen_width();
}
}
fn pipe_gap() -> f32 {
screen_height() / 4.25
}
fn pipe_width() -> f32 {
screen_width() / 20.0
}
fn pipe_speed() -> f32 {
screen_width() / 2.0
}
fn bird_x_pos() -> f32 {
screen_width() / 15.0
}
fn bird_size() -> f32 {
screen_height() / 30.0
}
fn jump_vel() -> f32 {
screen_height() * 0.9
}
fn gravity() -> f32 {
screen_height() * 1.7
}
struct DrawSys;
impl<'a> System<'a> for DrawSys {
type SystemData = (Read<'a, Bird>, ReadStorage<'a, PipePair>);
fn run(&mut self, (bird, pipes): Self::SystemData) {
clear_background(BLACK);
draw_circle(bird_x_pos(), bird.y_pos, bird_size(), RED);
pipes.join().for_each(|PipePair { x, y }| {
// top pipe
let h = screen_height();
let gap = pipe_gap();
draw_rectangle(*x, y - h - gap / 2.0, pipe_width(), h, GREEN);
draw_rectangle(*x, *y + gap / 2.0, pipe_width(), h, GREEN);
});
}
}
struct BirdPhysicsSys;
impl<'a> System<'a> for BirdPhysicsSys {
type SystemData = Write<'a, Bird>;
fn run(&mut self, mut bird: Self::SystemData) {
let dt = macroquad::time::get_frame_time();
bird.y_vel += gravity() * dt;
bird.y_pos += bird.y_vel * dt;
}
}
struct BirdInputSys;
impl<'a> System<'a> for BirdInputSys {
type SystemData = Write<'a, Bird>;
fn run(&mut self, mut bird: Self::SystemData) {
if is_key_pressed(KeyCode::Space) {
bird.y_vel -= jump_vel();
}
}
}
struct PipeMoveSys;
impl<'a> System<'a> for PipeMoveSys {
type SystemData = WriteStorage<'a, PipePair>;
fn run(&mut self, mut pipes: Self::SystemData) {
(&mut pipes).join().for_each(|pair| {
let dt = macroquad::time::get_frame_time();
pair.x -= pipe_speed() * dt;
if pair.x + pipe_width() < 0.0 {
pair.reset();
}
});
}
}
struct BirdCollideSys;
impl<'a> System<'a> for BirdCollideSys {
type SystemData = (Read<'a, Bird>, ReadStorage<'a, PipePair>);
fn run(&mut self, (bird, pipes): Self::SystemData) {
use std::process;
if bird.y_pos + bird_size() < 0.0 || bird.y_pos - bird_size() > screen_height() {
process::exit(0);
}
pipes.join().for_each(|pair| {
if bird_x_pos() + bird_size() / 2.0 > pair.x
&& (bird.y_pos - pair.y).abs() > (pipe_gap() - bird_size()) / 2.0
{
process::exit(0);
}
});
}
}
#[macroquad::main("Bouncy Ball")]
async fn main() {
let mut world = World::new();
let mut dispatcher = DispatcherBuilder::new()
.with(DrawSys, "draw_sys", &[])
.with(BirdPhysicsSys, "bird_physics_sys", &[])
.with(BirdInputSys, "bird_input_sys", &["bird_physics_sys"])
.with(BirdCollideSys, "bird_collide_sys", &[])
.with(PipeMoveSys, "pipe_move_sys", &[])
.build();
dispatcher.setup(&mut world);
world.insert(Bird::default());
world
.create_entity()
.with(PipePair::new(screen_width()))
.build();
world
.create_entity()
.with(PipePair::new(screen_width() * 1.5))
.build();
loop {
dispatcher.dispatch(&mut world);
next_frame().await;
}
}
| true
|
c77508be2c274863da3359b49b825233980a30f3
|
Rust
|
KatsuyaKikuchi/programming_contest_rust
|
/src/AtCoder Beginner Contest/ABC075/d.rs
|
UTF-8
| 823
| 2.609375
| 3
|
[] |
no_license
|
use proconio::input;
use std::cmp::min;
fn main() {
input! {
(n,k):(usize,usize),
points:[(i64,i64);n]
}
let mut x = points
.iter()
.map(|(x, _)| x.clone())
.collect::<Vec<i64>>();
x.sort();
x.dedup();
let mut ans = 4_000_000_000_000_000_000i64;
for i in 0..x.len() {
for j in i..x.len() {
let len = x[j] - x[i];
let mut p = points
.iter()
.filter(|(xv, _)| xv.clone() <= x[j] && xv.clone() >= x[i])
.map(|v| v.clone())
.collect::<Vec<(i64, i64)>>();
p.sort_by(|(_, b), (_, d)| b.cmp(d));
for i in (k - 1)..p.len() {
ans = min(ans, len * (p[i].1 - p[i - (k - 1)].1));
}
}
}
println!("{}", ans);
}
| true
|
7ecfc615bc8eff407c93046763bf8e4b35e5ec21
|
Rust
|
bombless/rustc-chinese
|
/src/test/auxiliary/lang-item-public.rs
|
UTF-8
| 1,305
| 2.53125
| 3
|
[
"MIT",
"Apache-2.0",
"Unlicense",
"LicenseRef-scancode-other-permissive",
"BSD-3-Clause",
"bzip2-1.0.6",
"NCSA",
"ISC",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause"
] |
permissive
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// 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.
#![feature(no_std)]
#![no_std]
#![feature(lang_items)]
#[lang="sized"]
pub trait Sized { }
#[lang="panic"]
fn panic(_: &(&'static str, &'static str, usize)) -> ! { loop {} }
#[lang = "stack_exhausted"]
extern fn stack_exhausted() {}
#[lang = "eh_personality"]
extern fn eh_personality() {}
#[lang="copy"]
pub trait Copy {
// Empty.
}
#[lang="rem"]
pub trait Rem<RHS=Self> {
type Output = Self;
fn rem(self, rhs: RHS) -> Self::Output;
}
impl Rem for isize {
type Output = isize;
#[inline]
fn rem(self, other: isize) -> isize {
// if you use `self % other` here, as one would expect, you
// get back an error because of potential failure/overflow,
// which tries to invoke error fns that don't have the
// appropriate signatures anymore. So...just return 0.
0
}
}
| true
|
9c327626ce2334e420765db2402f3ef3b46940ca
|
Rust
|
wahello/parallel-disk-usage
|
/tests/tree_builder.rs
|
UTF-8
| 3,960
| 3.140625
| 3
|
[
"Apache-2.0"
] |
permissive
|
use build_fs_tree::{dir, file, FileSystemTree};
use derive_more::From;
use parallel_disk_usage::{
data_tree::{DataTree, DataTreeReflection},
size::Bytes,
tree_builder::{Info, TreeBuilder},
};
use pipe_trait::Pipe;
use pretty_assertions::assert_eq;
type SampleData = Bytes;
type SampleName = String;
const SAMPLE_SEPARATOR: char = '/';
const SAMPLE_DIR_SIZE: SampleData = Bytes::new(5);
#[derive(Debug, From)]
struct SampleTree(FileSystemTree<String, &'static str>);
const fn len(text: &str) -> SampleData {
SampleData::new(text.len() as u64)
}
impl SampleTree {
fn create_sample() -> Self {
SampleTree::from(dir! {
"flat" => dir! {
"0" => file!("")
"1" => file!("a")
"2" => file!("ab")
"3" => file!("abc")
}
"nested" => dir! {
"0" => dir! {
"1" => file!("abcdef")
}
}
"empty-dir" => dir! {}
})
}
fn tree(&self, root: &'static str) -> DataTree<SampleName, SampleData> {
TreeBuilder {
path: root.to_string(),
name: root.to_string(),
get_info: |path| {
let path: Vec<_> = path
.split(SAMPLE_SEPARATOR)
.map(ToString::to_string)
.collect();
let mut path = path.iter();
match self.0.path(&mut path) {
Some(FileSystemTree::File(content)) => Info::from((len(content), Vec::new())),
Some(FileSystemTree::Directory(content)) => Info::from((
SAMPLE_DIR_SIZE,
content.keys().map(ToString::to_string).collect(),
)),
None => panic!("Path does not exist"),
}
},
join_path: |prefix, name| format!("{}{}{}", prefix, SAMPLE_SEPARATOR, name),
}
.pipe(DataTree::from)
.into_par_sorted(|left, right| left.name().cmp(right.name()))
}
}
#[test]
fn flat() {
let actual = SampleTree::create_sample().tree("flat").into_reflection();
let expected = DataTreeReflection {
name: "flat".to_string(),
data: len("") + len("a") + len("ab") + len("abc") + SAMPLE_DIR_SIZE,
children: vec![
DataTreeReflection {
name: "0".to_string(),
data: len(""),
children: Vec::new(),
},
DataTreeReflection {
name: "1".to_string(),
data: len("a"),
children: Vec::new(),
},
DataTreeReflection {
name: "2".to_string(),
data: len("ab"),
children: Vec::new(),
},
DataTreeReflection {
name: "3".to_string(),
data: len("abc"),
children: Vec::new(),
},
],
};
assert_eq!(actual, expected);
}
#[test]
fn nested() {
let actual = SampleTree::create_sample().tree("nested").into_reflection();
let expected = DataTreeReflection {
name: "nested".to_string(),
data: len("abcdef") + SAMPLE_DIR_SIZE + SAMPLE_DIR_SIZE,
children: vec![DataTreeReflection {
name: "0".to_string(),
data: len("abcdef") + SAMPLE_DIR_SIZE,
children: vec![DataTreeReflection {
name: "1".to_string(),
data: len("abcdef"),
children: Vec::new(),
}],
}],
};
assert_eq!(actual, expected);
}
#[test]
fn empty_dir() {
let actual = SampleTree::create_sample()
.tree("empty-dir")
.into_reflection();
let expected = DataTreeReflection {
name: "empty-dir".to_string(),
data: SAMPLE_DIR_SIZE,
children: Vec::new(),
};
assert_eq!(actual, expected);
}
| true
|
1a1c83c4488c26dca2b69716d40726e3dfa7b04e
|
Rust
|
hem6/atcoder-rs
|
/abc152/src/bin/d.rs
|
UTF-8
| 708
| 2.515625
| 3
|
[] |
no_license
|
#![allow(unused_imports)]
use itertools::Itertools;
use proconio::{input, marker::*};
use std::cmp::*;
use std::collections::*;
use superslice::*;
fn main() {
input! {
n: i32,
}
let ab: Vec<(i32, i32)> = (1..=n)
.map(|i| {
let a = i % 10;
let mut b = i;
while b / 10 > 0 {
b = b / 10;
}
(a, b)
})
.collect();
let mut freq: HashMap<(i32, i32), i32> = HashMap::new();
for &p in &ab {
freq.entry(p).and_modify(|i| *i += 1).or_insert(1);
}
let mut ans = 0;
for &p in &ab {
ans += freq.get(&(p.1, p.0)).unwrap_or(&0);
}
println!("{}", ans);
}
| true
|
f91f0d584a38f5120cc1c8c5cb75113ab0d87193
|
Rust
|
gnoliyil/fuchsia
|
/third_party/rust_crates/vendor/elliptic-curve-0.11.12/src/scalar.rs
|
UTF-8
| 889
| 3.046875
| 3
|
[
"BSD-2-Clause",
"Apache-2.0",
"MIT"
] |
permissive
|
//! Scalar types.
use subtle::Choice;
pub(crate) mod core;
#[cfg(feature = "arithmetic")]
pub(crate) mod nonzero;
#[cfg(feature = "arithmetic")]
use crate::ScalarArithmetic;
/// Scalar field element for a particular elliptic curve.
#[cfg(feature = "arithmetic")]
#[cfg_attr(docsrs, doc(cfg(feature = "arithmetic")))]
pub type Scalar<C> = <C as ScalarArithmetic>::Scalar;
/// Bit representation of a scalar field element of a given curve.
#[cfg(feature = "bits")]
#[cfg_attr(docsrs, doc(cfg(feature = "bits")))]
pub type ScalarBits<C> = ff::FieldBits<<Scalar<C> as ff::PrimeFieldBits>::ReprBits>;
/// Is this scalar greater than n / 2?
///
/// # Returns
///
/// - For scalars 0 through n / 2: `Choice::from(0)`
/// - For scalars (n / 2) + 1 through n - 1: `Choice::from(1)`
pub trait IsHigh {
/// Is this scalar greater than or equal to n / 2?
fn is_high(&self) -> Choice;
}
| true
|
96c637ea5dcf26ee521a7c397239804a876427e3
|
Rust
|
Insynia/zgog-io-server
|
/src/map/map.rs
|
UTF-8
| 4,546
| 3.3125
| 3
|
[
"Apache-2.0"
] |
permissive
|
use log::debug;
use noise::NoiseFn;
use noise::OpenSimplex;
use noise::Seedable;
use rand::Rng;
use std::collections::HashMap;
use crate::coordinates::Coords;
use crate::map::{Object, ObjectType, Visual, VisualType};
lazy_static! {
/// The game map
pub static ref MAP: Map = generate_map(30, 30);
}
/// Represents the spacing between map objects. Around one object
/// every `MAP_OBJECTS_SPACING` tile (random distribution).
static MAP_OBJECTS_SPACING: usize = 30;
/// A map. The `width` and `height` fields represent the size of the map
/// and the content is a [HashMap](HashMap) containing all the squares.
/// Each square of the map is accessible through the key `x;y`, `x` and
/// `y` being the coordinates of the tile. The value is then a vector of
/// [Tile](Tile) which represent the collection of elements present on the square.
#[derive(Debug, Serialize, Clone)]
pub struct Map {
pub width: usize,
pub height: usize,
content: HashMap<String, Tile>,
}
/// Collection of elements present at a x/y position.
/// These elements can either be visuals or objects (player can't walk on objects)
#[derive(Debug, Clone, Serialize)]
pub struct Tile {
/// The x position of the tile on the map.
pub x: usize,
/// The y position of the tile on the map.
pub y: usize,
/// The objects present on the tile (rock, tree, loot...)
pub objects: Vec<Object>,
/// The objects present on the tile (grass, water, flower...)
pub visuals: Vec<Visual>,
}
/// Generate a map of a size provided in parameters.
pub fn generate_map(width: usize, height: usize) -> Map {
debug!("Generating map of size: {}", height);
let mut map = Map {
width,
height,
content: HashMap::new(),
};
let mut random = rand::thread_rng();
let seed = random.gen();
let noise_generator = OpenSimplex::new();
let noise_generator = noise_generator.set_seed(seed);
for y in 0..map.width {
for x in 0..map.height {
let depth: u32 =
((noise_generator.get([x as f64 / 20.0, y as f64 / 20.0]) + 1.0) * 10.0) as u32;
let key = format!("{};{}", x, y);
let tile_type = match depth {
5...9 => VisualType::Water,
9...10 => VisualType::Sand,
10...15 => VisualType::Grass,
_ => VisualType::Grass,
};
let mut tile = Tile {
x,
y,
objects: vec![],
visuals: vec![Visual {
size: random.gen_range(1, 5 + 1),
_type: tile_type,
}],
};
if random.gen_range(0, MAP_OBJECTS_SPACING) == 0 {
tile.objects.push(Object {
_type: match random.gen_range(1, 3 + 1) {
0 => ObjectType::Rock,
_ => ObjectType::Tree,
},
size: random.gen_range(1, 5 + 1),
});
}
map.content.insert(key, tile);
}
}
map
}
/// Either a tile is walkable or not. It loops through
/// all the subtiles of a Tile to check if one is not walkable.
/// If so, the whole tile won't be.
fn is_walkable(x: usize, y: usize) -> bool {
let tile = MAP
.content
.get(&format!("{};{}", x, y))
.expect("Tile not found");
tile.objects.len() == 0 && tile.visuals.iter().all(|v| v._type != VisualType::Water)
}
/// Returns valid coordinates to spawn a player (walkable tile).
pub fn valid_spawn() -> Coords {
let mut random = rand::thread_rng();
let (mut x, mut y) = (
random.gen::<usize>() % MAP.width,
random.gen::<usize>() % MAP.height,
);
while !is_walkable(x, y) {
x = random.gen::<usize>() % MAP.width;
y = random.gen::<usize>() % MAP.height;
}
debug!("Found a valid spawn at: {}/{}", x, y);
Coords {
x: x as f64,
y: y as f64,
}
}
use std::net::TcpStream;
use websocket::result::WebSocketError;
use websocket::sender::Writer;
use websocket::OwnedMessage;
use crate::communication::{OutgoingMessage, OutgoingMessageType};
/// Sends the map to a client.
pub fn send_map(sender: &mut Writer<TcpStream>) -> Result<(), WebSocketError> {
debug!("Sending map...");
sender.send_message(&OwnedMessage::Text(
OutgoingMessage {
_type: OutgoingMessageType::Map,
payload: Some(MAP.clone()),
}
.into(),
))
}
| true
|
ca3c058b89f4c80ec161f7f9d12c36c9c6e97b91
|
Rust
|
tertsdiepraam/vrp
|
/vrp-core/src/solver/objectives/generic_value.rs
|
UTF-8
| 4,830
| 2.65625
| 3
|
[
"Apache-2.0"
] |
permissive
|
use crate::algorithms::nsga2::Objective;
use crate::construction::constraints::*;
use crate::construction::heuristics::{InsertionContext, RouteContext, SolutionContext};
use crate::models::problem::{Job, TargetConstraint, TargetObjective};
use crate::utils::compare_floats;
use std::cmp::Ordering;
use std::ops::Deref;
use std::slice::Iter;
use std::sync::Arc;
/// A helper for building objective functions.
pub(crate) struct GenericValue {}
impl GenericValue {
/// Creates a new instance of constraint and related objective.
pub fn new_constrained_objective(
threshold: Option<f64>,
tolerance: Option<f64>,
route_value_func: Arc<dyn Fn(&RouteContext) -> f64 + Send + Sync>,
solution_value_func: Arc<dyn Fn(&SolutionContext) -> f64 + Send + Sync>,
estimate_value_func: Arc<dyn Fn(&SolutionContext, &RouteContext, &Job, f64) -> f64 + Send + Sync>,
state_key: i32,
) -> (TargetConstraint, TargetObjective) {
let objective = GenericValueObjective {
threshold,
tolerance,
state_key,
route_value_func: route_value_func.clone(),
solution_value_func: solution_value_func.clone(),
estimate_value_func,
};
let constraint = GenericValueConstraint {
constraints: vec![ConstraintVariant::SoftRoute(Arc::new(objective.clone()))],
route_value_func,
state_key,
keys: vec![state_key],
solution_value_func,
};
(Box::new(constraint), Box::new(objective))
}
}
struct GenericValueConstraint {
constraints: Vec<ConstraintVariant>,
route_value_func: Arc<dyn Fn(&RouteContext) -> f64 + Send + Sync>,
solution_value_func: Arc<dyn Fn(&SolutionContext) -> f64 + Send + Sync>,
state_key: i32,
keys: Vec<i32>,
}
impl ConstraintModule for GenericValueConstraint {
fn accept_insertion(&self, solution_ctx: &mut SolutionContext, route_index: usize, _job: &Job) {
self.accept_route_state(solution_ctx.routes.get_mut(route_index).unwrap());
}
fn accept_route_state(&self, ctx: &mut RouteContext) {
let value = self.route_value_func.deref()(ctx);
ctx.state_mut().put_route_state(self.state_key, value);
}
fn accept_solution_state(&self, ctx: &mut SolutionContext) {
let value = self.solution_value_func.deref()(ctx);
ctx.state.insert(self.state_key, Arc::new(value));
}
fn state_keys(&self) -> Iter<i32> {
self.keys.iter()
}
fn get_constraints(&self) -> Iter<ConstraintVariant> {
self.constraints.iter()
}
}
#[derive(Clone)]
struct GenericValueObjective {
threshold: Option<f64>,
tolerance: Option<f64>,
state_key: i32,
route_value_func: Arc<dyn Fn(&RouteContext) -> f64 + Send + Sync>,
solution_value_func: Arc<dyn Fn(&SolutionContext) -> f64 + Send + Sync>,
estimate_value_func: Arc<dyn Fn(&SolutionContext, &RouteContext, &Job, f64) -> f64 + Send + Sync>,
}
impl SoftRouteConstraint for GenericValueObjective {
fn estimate_job(&self, solution_ctx: &SolutionContext, route_ctx: &RouteContext, job: &Job) -> f64 {
let value = route_ctx
.state
.get_route_state::<f64>(self.state_key)
.cloned()
.unwrap_or_else(|| self.route_value_func.deref()(route_ctx));
if value.is_finite() && self.threshold.map_or(true, |threshold| value > threshold) {
self.estimate_value_func.deref()(solution_ctx, route_ctx, job, value)
} else {
0.
}
}
}
impl Objective for GenericValueObjective {
type Solution = InsertionContext;
fn total_order(&self, a: &Self::Solution, b: &Self::Solution) -> Ordering {
let fitness_a = self.fitness(a);
let fitness_b = self.fitness(b);
// TODO test it
/* if let Some(tolerance) = self.tolerance {
if (fitness_a - fitness_b).abs() < tolerance {
return Ordering::Equal;
}
}
*/
if let Some(threshold) = self.threshold {
if fitness_a < threshold && fitness_b < threshold {
return Ordering::Equal;
}
if fitness_a < threshold {
return Ordering::Less;
}
if fitness_b < threshold {
return Ordering::Greater;
}
}
compare_floats(fitness_a, fitness_b)
}
fn fitness(&self, solution: &Self::Solution) -> f64 {
solution
.solution
.state
.get(&self.state_key)
.and_then(|s| s.downcast_ref::<f64>())
.cloned()
.unwrap_or_else(|| self.solution_value_func.deref()(&solution.solution))
}
}
| true
|
089aecb9346dac43907676e3e37da5fe7a4c10c9
|
Rust
|
Joey9801/igc-rs
|
/src/records/g_record.rs
|
UTF-8
| 871
| 2.953125
| 3
|
[
"MIT"
] |
permissive
|
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
use std::fmt;
use crate::util::ParseError;
/// A security record.
///
/// The contents of the record are vendor dependent.
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub struct GRecord<'a> {
pub data: &'a str,
}
impl<'a> GRecord<'a> {
pub fn parse(line: &'a str) -> Result<Self, ParseError> {
assert_eq!(line.as_bytes()[0], b'G');
Ok(Self { data: &line[1..] })
}
}
impl<'a> fmt::Display for GRecord<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "G{}", self.data)
}
}
#[cfg(test)]
mod tests {
use super::*;
proptest! {
#[test]
#[allow(unused_must_use)]
fn parse_doesnt_crash(s in "G\\PC*") {
GRecord::parse(&s);
}
}
}
| true
|
df71c911382bc0e0f46dc867bb29efc0df8a3c74
|
Rust
|
whtahy/exercism
|
/rust/10 difference.rs
|
UTF-8
| 302
| 3.125
| 3
|
[
"CC0-1.0"
] |
permissive
|
pub fn square_of_sum(n: usize) -> usize {
let m = consec_sum(n);
m * m
}
pub fn sum_of_squares(n: usize) -> usize {
n * (n + 1) * (2 * n + 1) / 6
}
pub fn difference(n: usize) -> usize {
square_of_sum(n) - sum_of_squares(n)
}
fn consec_sum(n: usize) -> usize {
n * (n + 1) / 2
}
| true
|
5cff80e7721a4818ba04315b1f19b517d479011f
|
Rust
|
linkerd/linkerd2-proxy
|
/linkerd/http-route/src/http/match/query_param.rs
|
UTF-8
| 4,443
| 3.203125
| 3
|
[
"Apache-2.0"
] |
permissive
|
use http::uri::Uri;
use regex::Regex;
#[derive(Clone, Debug)]
pub enum MatchQueryParam {
Exact(String, String),
Regex(String, Regex),
}
// === impl MatchQueryParam ===
impl MatchQueryParam {
pub fn is_match(&self, uri: &Uri) -> bool {
uri.query().map_or(false, |qs| {
url::form_urlencoded::parse(qs.as_bytes()).any(|(q, p)| match self {
Self::Exact(n, v) => *n == *q && *v == *p,
Self::Regex(n, r) => {
if *n == *q {
if let Some(m) = r.find(&p) {
// Check that the regex is anchored at the start and
// end of the value.
return m.start() == 0 && m.end() == p.len();
}
}
false
}
})
})
}
}
impl std::hash::Hash for MatchQueryParam {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
match self {
Self::Exact(n, s) => {
n.hash(state);
s.hash(state)
}
Self::Regex(n, r) => {
n.hash(state);
r.as_str().hash(state);
}
}
}
}
impl std::cmp::Eq for MatchQueryParam {}
impl std::cmp::PartialEq for MatchQueryParam {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Self::Exact(n, s), Self::Exact(m, o)) => n == m && s == o,
(Self::Regex(n, s), Self::Regex(m, o)) => n == m && s.as_str() == o.as_str(),
_ => false,
}
}
}
#[cfg(feature = "proto")]
pub mod proto {
use super::*;
use linkerd2_proxy_api::http_route as api;
#[derive(Debug, thiserror::Error)]
pub enum InvalidQueryParamMatch {
#[error("missing a query param name")]
MissingName,
#[error("missing a query param value")]
MissingValue,
#[error("invalid regular expression: {0}")]
Regex(#[from] regex::Error),
}
// === impl MatchQueryParam ===
impl TryFrom<api::QueryParamMatch> for MatchQueryParam {
type Error = InvalidQueryParamMatch;
fn try_from(qpm: api::QueryParamMatch) -> Result<Self, Self::Error> {
if qpm.name.is_empty() {
return Err(InvalidQueryParamMatch::MissingName);
}
match qpm.value.ok_or(InvalidQueryParamMatch::MissingValue)? {
api::query_param_match::Value::Exact(v) => Ok(MatchQueryParam::Exact(qpm.name, v)),
api::query_param_match::Value::Regex(re) => {
Ok(MatchQueryParam::Regex(qpm.name, re.parse()?))
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::MatchQueryParam;
#[test]
fn query_param_exact() {
let m = MatchQueryParam::Exact("foo".to_string(), "bar".to_string());
assert!(m.is_match(&"/?foo=bar".parse().unwrap()));
assert!(m.is_match(&"/?foo=bar&fah=bah".parse().unwrap()));
assert!(m.is_match(&"/?fah=bah&foo=bar".parse().unwrap()));
assert!(!m.is_match(&"/?foo=bah".parse().unwrap()));
let m = MatchQueryParam::Exact("foo".to_string(), "".to_string());
assert!(m.is_match(&"/?foo".parse().unwrap()));
assert!(!m.is_match(&"/?foo=bah".parse().unwrap()));
assert!(!m.is_match(&"/?bar=foo".parse().unwrap()));
}
#[test]
fn query_param_regex() {
let m = MatchQueryParam::Regex("foo".to_string(), "bar*".parse().unwrap());
assert!(m.is_match(&"/?foo=bar".parse().unwrap()));
assert!(m.is_match(&"/?foo=ba&fah=bah".parse().unwrap()));
assert!(m.is_match(&"/?foo=barr&fah=bah".parse().unwrap()));
assert!(m.is_match(&"/?bar=foo&foo=bar".parse().unwrap()));
assert!(m.is_match(&"/?foo=bah&foo=bar".parse().unwrap()));
assert!(!m.is_match(&"/?foo=bah".parse().unwrap()));
assert!(!m.is_match(&"/?bar=foo".parse().unwrap()));
assert!(!m.is_match(&"/?foo=barro".parse().unwrap()));
let m = MatchQueryParam::Regex("foo".to_string(), "bar/.+".parse().unwrap());
assert!(m.is_match(&"/?foo=bar%2Fhi".parse().unwrap()));
assert!(!m.is_match(&"/?foo=bah%20hi".parse().unwrap()));
let m = MatchQueryParam::Regex("foo".to_string(), ".*".parse().unwrap());
assert!(m.is_match(&"/?foo".parse().unwrap()));
}
}
| true
|
fc9606d0067a13944ef5fe816868041f3a457110
|
Rust
|
STAR-Tsinghua/DTP
|
/tools/http3_test/src/lib.rs
|
UTF-8
| 15,971
| 3.078125
| 3
|
[
"BSD-2-Clause"
] |
permissive
|
// Copyright (C) 2019, Cloudflare, Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//! 🔧 HTTP/3 integration test utilities.
//!
//! This crate provides utilities to help integration tests against HTTP/3
//! endpoints. Structures and methods can be combined with a [`quiche`]
//! HTTP/3 client to run tests against a server. This client could be a
//! binary or run as part of cargo test.
//!
//! ## Creating a test
//!
//! A test is an instance of [`Http3Test`], which consists of a set of
//! [`Http3Req`] and a single [`Http3Assert`].
//!
//!
//! Creating a single request:
//!
//! ```no_run
//! let mut url = url::Url::parse("https://cloudflare-quic.com/b/get").unwrap();
//! let mut reqs = Vec::new();
//!
//! reqs.push(http3_test::Http3Req::new("GET", &url, None, None));
//! ```
//!
//! Assertions are used to check the received response headers and body
//! against expectations. Each test has a [`Http3Assert`] which
//! can access the received data. For example, to check the response
//! status code is a 200 we could write the function:
//!
//! ```no_run
//! fn assert_status(reqs: &[http3_test::Http3Req]) {
//! let status = reqs[0]
//! .resp_hdrs
//! .iter()
//! .find(|&x| x.name() == ":status")
//! .unwrap();
//! assert_eq!(status.value(), "200");
//! }
//! ```
//!
//! However, because checking response headers is so common, for convenience
//! the expected headers can be provided during [`Http3Assert`] construction:
//!
//! ```no_run
//! let mut url = url::Url::parse("https://cloudflare-quic.com/b/get").unwrap();
//! let mut reqs = Vec::new();
//!
//! let expect_hdrs = Some(vec![quiche::h3::Header::new(":status", "200")]);
//! reqs.push(http3_test::Http3Req::new("GET", &url, None, expect_hdrs));
//! ```
//!
//! The [`assert_headers!`] macro can be used to validate the received headers,
//! this means we can write a much simpler assertion:
//!
//! ```no_run
//! fn assert_status(reqs: &[http3_test::Http3Req]) {
//! http3_test::assert_headers!(reqs[0]);
//! }
//! ```
//!
//! Whatever methods you choose to use, once the requests and assertions are
//! made we can create the test:
//!
//! ```no_run
//! let mut url = url::Url::parse("https://cloudflare-quic.com/b/get").unwrap();
//! let mut reqs = Vec::new();
//!
//! let expect_hdrs = Some(vec![quiche::h3::Header::new(":status", "200")]);
//! reqs.push(http3_test::Http3Req::new("GET", &url, None, expect_hdrs));
//!
//! // Using a closure...
//! let assert =
//! |reqs: &[http3_test::Http3Req]| http3_test::assert_headers!(reqs[0]);
//!
//! let mut test = http3_test::Http3Test::new(url, reqs, assert, true);
//! ```
//!
//! ## Sending test requests
//!
//! Testing a server requires a quiche connection and an HTTP/3 connection.
//!
//! Request are issued with the [`send_requests()`] method. The concurrency
//! of requests within a single Http3Test is set in [`new()`]. If concurrency is
//! disabled [`send_requests()`] will to send a single request and return.
//! So call the method multiple times to issue more requests. Once all
//! requests have been sent, further calls will return `quiche::h3:Error::Done`.
//!
//! Example:
//! ```no_run
//! # let mut url = url::Url::parse("https://cloudflare-quic.com/b/get").unwrap();
//! # let mut reqs = Vec::new();
//! # let expect_hdrs = Some(vec![quiche::h3::Header::new(":status", "200")]);
//! # reqs.push(http3_test::Http3Req::new("GET", &url, None, expect_hdrs));
//! # // Using a closure...
//! # let assert = |reqs: &[http3_test::Http3Req]| {
//! # http3_test::assert_headers!(reqs[0]);
//! # };
//! let mut test = http3_test::Http3Test::new(url, reqs, assert, true);
//!
//! let mut config = quiche::Config::new(quiche::PROTOCOL_VERSION).unwrap();
//! let scid = [0xba; 16];
//! let mut conn = quiche::connect(None, &scid, &mut config).unwrap();
//! let h3_config = quiche::h3::Config::new()?;
//! let mut http3_conn = quiche::h3::Connection::with_transport(&mut conn, &h3_config)?;
//!
//! test.send_requests(&mut conn, &mut http3_conn).unwrap();
//! # Ok::<(), quiche::h3::Error>(())
//! ```
//!
//! ## Handling responses
//!
//! Response data is used to validate test cases so it is important to
//! store received data in the test object. This can be done with the
//! [`add_response_headers()`] and [`add_response_body()`] methods. Note
//! that the stream ID is used to correlate the response with the correct
//! request.
//!
//! For example, when handling HTTP/3 connection events using `poll()`:
//!
//! ```no_run
//! # let mut url = url::Url::parse("https://cloudflare-quic.com/b/get").unwrap();
//! # let mut reqs = Vec::new();
//! # let expect_hdrs = Some(vec![quiche::h3::Header::new(":status", "200")]);
//! # reqs.push(http3_test::Http3Req::new("GET", &url, None, expect_hdrs));
//! # // Using a closure...
//! # let assert = |reqs: &[http3_test::Http3Req]| {
//! # http3_test::assert_headers!(reqs[0]);
//! # };
//! # let mut test = http3_test::Http3Test::new(url, reqs, assert, true);
//! # let mut config = quiche::Config::new(quiche::PROTOCOL_VERSION).unwrap();
//! # let scid = [0xba; 16];
//! # let mut conn = quiche::connect(None, &scid, &mut config).unwrap();
//! # let h3_config = quiche::h3::Config::new()?;
//! # let mut http3_conn = quiche::h3::Connection::with_transport(&mut conn, &h3_config)?;
//! match http3_conn.poll(&mut conn) {
//! Ok((stream_id, quiche::h3::Event::Headers{list, has_body})) => {
//! test.add_response_headers(stream_id, &list);
//! },
//!
//! Ok((stream_id, quiche::h3::Event::Data)) => {
//! let mut buf = [0; 65535];
//! if let Ok(read) = http3_conn.recv_body(&mut conn, stream_id, &mut buf)
//! {
//! test.add_response_body(stream_id, &buf, read);
//! }
//! },
//!
//! _ => ()
//! }
//! # Ok::<(), quiche::h3::Error>(())
//! ```
//!
//! ## Tests assertion
//!
//! The [`assert()`] method executes the provided test assertion using the
//! entire set of [`Http3Req`]s. Calling this prematurely is likely to result
//! in failure, so it is important to store response data and track the number
//! of completed requests matches the total for a test.
//!
//! ```no_run
//! # let mut url = url::Url::parse("https://cloudflare-quic.com/b/get").unwrap();
//! # let mut reqs = Vec::new();
//! # let expect_hdrs = Some(vec![quiche::h3::Header::new(":status", "200")]);
//! # reqs.push(http3_test::Http3Req::new("GET", &url, None, expect_hdrs));
//! # // Using a closure...
//! # let assert = |reqs: &[http3_test::Http3Req]| {
//! # http3_test::assert_headers!(reqs[0]);
//! # };
//! # let mut test = http3_test::Http3Test::new(url, reqs, assert, true);
//! # let mut config = quiche::Config::new(quiche::PROTOCOL_VERSION).unwrap();
//! # let scid = [0xba; 16];
//! # let mut conn = quiche::connect(None, &scid, &mut config).unwrap();
//! # let h3_config = quiche::h3::Config::new()?;
//! # let mut http3_conn = quiche::h3::Connection::with_transport(&mut conn, &h3_config)?;
//! let mut requests_complete = 0;
//! let request_count = test.requests_count();
//! match http3_conn.poll(&mut conn) {
//! Ok((_stream_id, quiche::h3::Event::Finished)) => {
//! requests_complete += 1;
//! if requests_complete == request_count {
//! test.assert()
//! }
//! },
//! _ => ()
//! }
//! # Ok::<(), quiche::h3::Error>(())
//! ```
//!
//! [`quiche`]: https://github.com/cloudflare/quiche/
//! [test]: struct.Http3Test.html
//! [`Http3Test`]: struct.Http3Test.html
//! [`Http3Assert`]: struct.Http3Assert.html
//! [`Http3req`]: struct.Http3Req.html
//! [`assert_headers!`]: macro.assert_headers.html
//! [`new()`]: struct.Http3Test.html#method.new
//! [`send_requests()`]: struct.Http3Test.html#method.send_requests
//! [`requests_count()`]: struct.Http3Test.html#method.requests_count
//! [`assert()`]: struct.Http3Test.html#method.assert
//! [`add_response_headers()`]:
//! struct.Http3Test.html#method.add_response_headers [`add_response_body()`]:
//! struct.Http3Test.html#method.add_response_body
#[macro_use]
extern crate log;
use std::collections::HashMap;
use quiche::h3::Header;
pub const USER_AGENT: &str = "quiche-http3-integration-client";
/// Stores the request, the expected response headers, and the actual response.
///
/// The assert_headers! macro is provided for convenience to validate the
/// received headers match the expected headers.
#[derive(Clone)]
pub struct Http3Req {
pub url: url::Url,
pub hdrs: Vec<Header>,
body: Option<Vec<u8>>,
pub expect_resp_hdrs: Option<Vec<Header>>,
pub resp_hdrs: Vec<Header>,
pub resp_body: Vec<u8>,
}
impl Http3Req {
pub fn new(
method: &str, url: &url::Url, body: Option<Vec<u8>>,
expect_resp_hdrs: Option<Vec<Header>>,
) -> Http3Req {
let mut path = String::from(url.path());
if let Some(query) = url.query() {
path.push('?');
path.push_str(query);
}
let mut hdrs = vec![
Header::new(":method", method),
Header::new(":scheme", url.scheme()),
Header::new(":authority", url.host_str().unwrap()),
Header::new(":path", &path),
Header::new("user-agent", USER_AGENT),
];
if let Some(body) = &body {
hdrs.push(Header::new("content-length", &body.len().to_string()));
}
Http3Req {
url: url.clone(),
hdrs,
body,
expect_resp_hdrs,
resp_hdrs: Vec::new(),
resp_body: Vec::new(),
}
}
}
/// Asserts that the Http3Req received response headers match the expected
/// response headers.
///
/// Header values are compared with [`assert_eq!`] and this macro will panic
/// similarly.
///
/// If an expected header is not present this macro will panic and print the
/// missing header name.AsMut
///
/// [`assert_eq!`]: std/macro.assert.html
#[macro_export]
macro_rules! assert_headers {
($req:expr) => ({
if let Some(expect_hdrs) = &$req.expect_resp_hdrs {
for hdr in expect_hdrs {
match $req.resp_hdrs.iter().find(|&x| x.name() == hdr.name()) {
Some(h) => { assert_eq!(hdr.value(), h.value());},
None => {
panic!(format!("assertion failed: expected response header field {} not present!", hdr.name()));
}
}
}
}
});
($req:expr,) => ({ $crate::assert_headers!($req)});
($req:expr, $($arg:tt)+) => ({
if let Some(expect_hdrs) = &$req.expect_resp_hdrs {
for hdr in expect_hdrs {
match $req.resp_hdrs.iter().find(|&x| x.name() == hdr.name()) {
Some(h) => { assert_eq!(hdr.value(), h.value(), $($arg)+);},
None => {
panic!(format!("assertion failed: expected response header field {} not present! {}", hdr.name(), $($arg)+));
}
}
}
}
});
}
/// A helper function pointer type for assertions.
///
/// Each test assertion can check the set of Http3Req
/// however they like.
pub type Http3Assert = fn(&[Http3Req]);
/// The main object for getting things done.
///
/// The factory method new() is used to set up a vector of Http3Req objects and
/// map them to a test assertion function. The public functions are used to send
/// requests and store response data. Internally we track some other state to
/// make sure everything goes smoothly.
///
/// Many tests have similar inputs or assertions, so utility functions help
/// cover many of the common cases like testing different status codes or
/// checking that a response body is echoed back.
pub struct Http3Test {
endpoint: url::Url,
reqs: Vec<Http3Req>,
assert: Http3Assert,
issued_reqs: HashMap<u64, usize>,
concurrent: bool,
current_idx: usize,
}
impl Http3Test {
pub fn new(
endpoint: url::Url, reqs: Vec<Http3Req>, assert: Http3Assert,
concurrent: bool,
) -> Http3Test {
Http3Test {
endpoint,
reqs,
assert,
issued_reqs: HashMap::new(),
concurrent,
current_idx: 0,
}
}
/// Returns the total number of requests in a test.
pub fn requests_count(&mut self) -> usize {
self.reqs.len()
}
pub fn endpoint(&self) -> url::Url {
self.endpoint.clone()
}
/// Send one or more requests based on test type and the concurrency
/// property. If any send fails, a quiche::h3::Error is returned.
pub fn send_requests(
&mut self, conn: &mut quiche::Connection,
h3_conn: &mut quiche::h3::Connection,
) -> quiche::h3::Result<()> {
if self.reqs.len() - self.current_idx == 0 {
return Err(quiche::h3::Error::Done);
}
let reqs_to_make = if self.concurrent {
self.reqs.len() - self.current_idx
} else {
1
};
for _ in 0..reqs_to_make {
let req = &self.reqs[self.current_idx];
info!("sending HTTP request {:?}", req.hdrs);
let s =
match h3_conn.send_request(conn, &req.hdrs, req.body.is_none()) {
Ok(stream_id) => stream_id,
Err(e) => {
error!("failed to send request {:?}", e);
return Err(e);
},
};
self.issued_reqs.insert(s, self.current_idx);
if let Some(body) = &req.body {
info!("sending body {:?}", body);
if let Err(e) = h3_conn.send_body(conn, s, body, true) {
error!("failed to send request body {:?}", e);
return Err(e);
}
}
self.current_idx += 1;
}
Ok(())
}
/// Append response headers for an issued request.
pub fn add_response_headers(&mut self, stream_id: u64, headers: &[Header]) {
let i = self.issued_reqs.get(&stream_id).unwrap();
self.reqs[*i].resp_hdrs.extend_from_slice(headers);
}
/// Append data to the response body for an issued request.
pub fn add_response_body(
&mut self, stream_id: u64, data: &[u8], data_len: usize,
) {
let i = self.issued_reqs.get(&stream_id).unwrap();
self.reqs[*i].resp_body.extend_from_slice(&data[..data_len]);
}
/// Execute the test assertion(s).
pub fn assert(&mut self) {
(self.assert)(&self.reqs);
}
}
pub mod runner;
| true
|
79796a0d03a2a47a6a790322f77274a85a44d330
|
Rust
|
coopernurse/rust-delix
|
/src/node/node.rs
|
UTF-8
| 3,684
| 2.59375
| 3
|
[
"Apache-2.0"
] |
permissive
|
// Copyright 2015 The Delix Project Authors. See the AUTHORS file at the top level directory.
//
// 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 std::fmt;
use std::result;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread;
use discovery::Discovery;
use node::{ID, State, request};
use transport;
use transport::Transport;
pub struct Node {
id: ID,
transport: Arc<Box<Transport>>,
join_handle: Option<thread::JoinHandle<()>>,
running: Arc<AtomicBool>,
}
pub type Result<T> = result::Result<T, Error>;
#[derive(Debug)]
pub enum Error {
NoSocketAddr,
Transport(transport::Error),
}
impl Node {
pub fn new(d: Box<Discovery>, t: Box<Transport>) -> Result<Node> {
let node_id = ID::new_random();
try!(t.bind(node_id));
let running = Arc::new(AtomicBool::new(true));
let running_clone = running.clone();
let discovery = Arc::new(d);
let transport = Arc::new(t);
let discovery_clone = discovery.clone();
let transport_clone = transport.clone();
let join_handle = Some(thread::spawn(move || {
while running_clone.load(Ordering::SeqCst) {
if transport_clone.connection_count() == 0 {
if let Some(address) = discovery_clone.discover() {
if let Err(err) = transport_clone.join(address, node_id) {
error!("{}: failed to connect to {}: {:?}", node_id, address, err);
}
}
}
thread::sleep_ms(2000);
}
}));
Ok(Node {
id: node_id,
transport: transport,
join_handle: join_handle,
running: running,
})
}
pub fn id(&self) -> ID {
self.id
}
pub fn state(&self) -> State {
if self.transport.connection_count() == 0 {
State::Discovering
} else {
State::Joined
}
}
pub fn connection_count(&self) -> usize {
self.transport.connection_count()
}
pub fn register(&self, name: &str, f: Box<request::Handler>) -> Result<()> {
try!(self.transport.register(name, f));
Ok(())
}
pub fn deregister(&self, name: &str) -> Result<()> {
try!(self.transport.deregister(name));
Ok(())
}
pub fn service_count(&self) -> usize {
self.transport.service_count()
}
pub fn request(&self, name: &str, request: &[u8]) -> request::Response {
Ok(try!(self.transport.request(name, request)))
}
}
impl fmt::Display for Node {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f,
"(Node {} {} {} connections)",
self.id,
self.state(),
self.connection_count())
}
}
impl Drop for Node {
fn drop(&mut self) {
self.running.store(false, Ordering::SeqCst);
self.join_handle.take().unwrap().join().unwrap();
}
}
impl From<transport::Error> for Error {
fn from(error: transport::Error) -> Self {
Error::Transport(error)
}
}
| true
|
a82ddd96bb2ec6e554ff62e00ec790b509676c6e
|
Rust
|
bytecodealliance/wasmtime
|
/cranelift/codegen/src/ir/entities.rs
|
UTF-8
| 20,217
| 3.140625
| 3
|
[
"LLVM-exception",
"Apache-2.0"
] |
permissive
|
//! Cranelift IR entity references.
//!
//! Instructions in Cranelift IR need to reference other entities in the function. This can be other
//! parts of the function like basic blocks or stack slots, or it can be external entities
//! that are declared in the function preamble in the text format.
//!
//! These entity references in instruction operands are not implemented as Rust references both
//! because Rust's ownership and mutability rules make it difficult, and because 64-bit pointers
//! take up a lot of space, and we want a compact in-memory representation. Instead, entity
//! references are structs wrapping a `u32` index into a table in the `Function` main data
//! structure. There is a separate index type for each entity type, so we don't lose type safety.
//!
//! The `entities` module defines public types for the entity references along with constants
//! representing an invalid reference. We prefer to use `Option<EntityRef>` whenever possible, but
//! unfortunately that type is twice as large as the 32-bit index type on its own. Thus, compact
//! data structures use the `PackedOption<EntityRef>` representation, while function arguments and
//! return values prefer the more Rust-like `Option<EntityRef>` variant.
//!
//! The entity references all implement the `Display` trait in a way that matches the textual IR
//! format.
use crate::entity::entity_impl;
use core::fmt;
use core::u32;
#[cfg(feature = "enable-serde")]
use serde::{Deserialize, Serialize};
/// An opaque reference to a [basic block](https://en.wikipedia.org/wiki/Basic_block) in a
/// [`Function`](super::function::Function).
///
/// You can get a `Block` using
/// [`FunctionBuilder::create_block`](https://docs.rs/cranelift-frontend/*/cranelift_frontend/struct.FunctionBuilder.html#method.create_block)
///
/// While the order is stable, it is arbitrary and does not necessarily resemble the layout order.
#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
pub struct Block(u32);
entity_impl!(Block, "block");
impl Block {
/// Create a new block reference from its number. This corresponds to the `blockNN` representation.
///
/// This method is for use by the parser.
pub fn with_number(n: u32) -> Option<Self> {
if n < u32::MAX {
Some(Self(n))
} else {
None
}
}
}
/// An opaque reference to an SSA value.
///
/// You can get a constant `Value` from the following
/// [`InstBuilder`](super::InstBuilder) instructions:
///
/// - [`iconst`](super::InstBuilder::iconst) for integer constants
/// - [`f32const`](super::InstBuilder::f32const) for 32-bit float constants
/// - [`f64const`](super::InstBuilder::f64const) for 64-bit float constants
/// - [`vconst`](super::InstBuilder::vconst) for vector constants
/// - [`null`](super::InstBuilder::null) for null reference constants
///
/// Any `InstBuilder` instruction that has an output will also return a `Value`.
///
/// While the order is stable, it is arbitrary.
#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
pub struct Value(u32);
entity_impl!(Value, "v");
impl Value {
/// Create a value from its number representation.
/// This is the number in the `vNN` notation.
///
/// This method is for use by the parser.
pub fn with_number(n: u32) -> Option<Self> {
if n < u32::MAX / 2 {
Some(Self(n))
} else {
None
}
}
}
/// An opaque reference to an instruction in a [`Function`](super::Function).
///
/// Most usage of `Inst` is internal. `Inst`ructions are returned by
/// [`InstBuilder`](super::InstBuilder) instructions that do not return a
/// [`Value`], such as control flow and trap instructions, as well as instructions that return a
/// variable (potentially zero!) number of values, like call or call-indirect instructions. To get
/// the `Value` of such instructions, use [`inst_results`](super::DataFlowGraph::inst_results) or
/// its analogue in `cranelift_frontend::FuncBuilder`.
///
/// [inst_comment]: https://github.com/bjorn3/rustc_codegen_cranelift/blob/0f8814fd6da3d436a90549d4bb19b94034f2b19c/src/pretty_clif.rs
///
/// While the order is stable, it is arbitrary and does not necessarily resemble the layout order.
#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
pub struct Inst(u32);
entity_impl!(Inst, "inst");
/// An opaque reference to a stack slot.
///
/// Stack slots represent an address on the
/// [call stack](https://en.wikipedia.org/wiki/Call_stack).
///
/// `StackSlot`s can be created with
/// [`FunctionBuilder::create_sized_stack_slot`](https://docs.rs/cranelift-frontend/*/cranelift_frontend/struct.FunctionBuilder.html#method.create_sized_stack_slot)
/// or
/// [`FunctionBuilder::create_dynamic_stack_slot`](https://docs.rs/cranelift-frontend/*/cranelift_frontend/struct.FunctionBuilder.html#method.create_dynamic_stack_slot).
///
/// `StackSlot`s are most often used with
/// [`stack_addr`](super::InstBuilder::stack_addr),
/// [`stack_load`](super::InstBuilder::stack_load), and
/// [`stack_store`](super::InstBuilder::stack_store).
///
/// While the order is stable, it is arbitrary and does not necessarily resemble the stack order.
#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
pub struct StackSlot(u32);
entity_impl!(StackSlot, "ss");
impl StackSlot {
/// Create a new stack slot reference from its number.
///
/// This method is for use by the parser.
pub fn with_number(n: u32) -> Option<Self> {
if n < u32::MAX {
Some(Self(n))
} else {
None
}
}
}
/// An opaque reference to a dynamic stack slot.
#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
pub struct DynamicStackSlot(u32);
entity_impl!(DynamicStackSlot, "dss");
impl DynamicStackSlot {
/// Create a new stack slot reference from its number.
///
/// This method is for use by the parser.
pub fn with_number(n: u32) -> Option<Self> {
if n < u32::MAX {
Some(Self(n))
} else {
None
}
}
}
/// An opaque reference to a dynamic type.
#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
pub struct DynamicType(u32);
entity_impl!(DynamicType, "dt");
impl DynamicType {
/// Create a new dynamic type reference from its number.
///
/// This method is for use by the parser.
pub fn with_number(n: u32) -> Option<Self> {
if n < u32::MAX {
Some(Self(n))
} else {
None
}
}
}
/// An opaque reference to a global value.
///
/// A `GlobalValue` is a [`Value`](Value) that will be live across the entire
/// function lifetime. It can be preloaded from other global values.
///
/// You can create a `GlobalValue` in the following ways:
///
/// - When compiling to WASM, you can use it to load values from a
/// [`VmContext`](super::GlobalValueData::VMContext) using
/// [`FuncEnvironment::make_global`](https://docs.rs/cranelift-wasm/*/cranelift_wasm/trait.FuncEnvironment.html#tymethod.make_global).
/// - When compiling to native code, you can use it for objects in static memory with
/// [`Module::declare_data_in_func`](https://docs.rs/cranelift-module/*/cranelift_module/trait.Module.html#method.declare_data_in_func).
/// - For any compilation target, it can be registered with
/// [`FunctionBuilder::create_global_value`](https://docs.rs/cranelift-frontend/*/cranelift_frontend/struct.FunctionBuilder.html#method.create_global_value).
///
/// `GlobalValue`s can be retrieved with
/// [`InstBuilder:global_value`](super::InstBuilder::global_value).
///
/// While the order is stable, it is arbitrary.
#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
pub struct GlobalValue(u32);
entity_impl!(GlobalValue, "gv");
impl GlobalValue {
/// Create a new global value reference from its number.
///
/// This method is for use by the parser.
pub fn with_number(n: u32) -> Option<Self> {
if n < u32::MAX {
Some(Self(n))
} else {
None
}
}
}
/// An opaque reference to a constant.
///
/// You can store [`ConstantData`](super::ConstantData) in a
/// [`ConstantPool`](super::ConstantPool) for efficient storage and retrieval.
/// See [`ConstantPool::insert`](super::ConstantPool::insert).
///
/// While the order is stable, it is arbitrary and does not necessarily resemble the order in which
/// the constants are written in the constant pool.
#[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]
#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
pub struct Constant(u32);
entity_impl!(Constant, "const");
impl Constant {
/// Create a const reference from its number.
///
/// This method is for use by the parser.
pub fn with_number(n: u32) -> Option<Self> {
if n < u32::MAX {
Some(Self(n))
} else {
None
}
}
}
/// An opaque reference to an immediate.
///
/// Some immediates (e.g. SIMD shuffle masks) are too large to store in the
/// [`InstructionData`](super::instructions::InstructionData) struct and therefore must be
/// tracked separately in [`DataFlowGraph::immediates`](super::dfg::DataFlowGraph). `Immediate`
/// provides a way to reference values stored there.
///
/// While the order is stable, it is arbitrary.
#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
pub struct Immediate(u32);
entity_impl!(Immediate, "imm");
impl Immediate {
/// Create an immediate reference from its number.
///
/// This method is for use by the parser.
pub fn with_number(n: u32) -> Option<Self> {
if n < u32::MAX {
Some(Self(n))
} else {
None
}
}
}
/// An opaque reference to a [jump table](https://en.wikipedia.org/wiki/Branch_table).
///
/// `JumpTable`s are used for indirect branching and are specialized for dense,
/// 0-based jump offsets. If you want a jump table which doesn't start at 0,
/// or is not contiguous, consider using a [`Switch`](https://docs.rs/cranelift-frontend/*/cranelift_frontend/struct.Switch.html) instead.
///
/// `JumpTable` are used with [`br_table`](super::InstBuilder::br_table).
///
/// `JumpTable`s can be created with
/// [`create_jump_table`](https://docs.rs/cranelift-frontend/*/cranelift_frontend/struct.FunctionBuilder.html#method.create_jump_table).
///
/// While the order is stable, it is arbitrary.
#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
pub struct JumpTable(u32);
entity_impl!(JumpTable, "jt");
impl JumpTable {
/// Create a new jump table reference from its number.
///
/// This method is for use by the parser.
pub fn with_number(n: u32) -> Option<Self> {
if n < u32::MAX {
Some(Self(n))
} else {
None
}
}
}
/// An opaque reference to another [`Function`](super::Function).
///
/// `FuncRef`s are used for [direct](super::InstBuilder::call) function calls
/// and by [`func_addr`](super::InstBuilder::func_addr) for use in
/// [indirect](super::InstBuilder::call_indirect) function calls.
///
/// `FuncRef`s can be created with
///
/// - [`FunctionBuilder::import_function`](https://docs.rs/cranelift-frontend/*/cranelift_frontend/struct.FunctionBuilder.html#method.import_function)
/// for external functions
/// - [`Module::declare_func_in_func`](https://docs.rs/cranelift-module/*/cranelift_module/trait.Module.html#method.declare_func_in_func)
/// for functions declared elsewhere in the same native
/// [`Module`](https://docs.rs/cranelift-module/*/cranelift_module/trait.Module.html)
/// - [`FuncEnvironment::make_direct_func`](https://docs.rs/cranelift-wasm/*/cranelift_wasm/trait.FuncEnvironment.html#tymethod.make_direct_func)
/// for functions declared in the same WebAssembly
/// [`FuncEnvironment`](https://docs.rs/cranelift-wasm/*/cranelift_wasm/trait.FuncEnvironment.html#tymethod.make_direct_func)
///
/// While the order is stable, it is arbitrary.
#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
pub struct FuncRef(u32);
entity_impl!(FuncRef, "fn");
impl FuncRef {
/// Create a new external function reference from its number.
///
/// This method is for use by the parser.
pub fn with_number(n: u32) -> Option<Self> {
if n < u32::MAX {
Some(Self(n))
} else {
None
}
}
}
/// A reference to an `UserExternalName`, declared with `Function::declare_imported_user_function`.
#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
pub struct UserExternalNameRef(u32);
entity_impl!(UserExternalNameRef, "userextname");
/// An opaque reference to a function [`Signature`](super::Signature).
///
/// `SigRef`s are used to declare a function with
/// [`FunctionBuilder::import_function`](https://docs.rs/cranelift-frontend/*/cranelift_frontend/struct.FunctionBuilder.html#method.import_function)
/// as well as to make an [indirect function call](super::InstBuilder::call_indirect).
///
/// `SigRef`s can be created with
/// [`FunctionBuilder::import_signature`](https://docs.rs/cranelift-frontend/*/cranelift_frontend/struct.FunctionBuilder.html#method.import_signature).
///
/// You can retrieve the [`Signature`](super::Signature) that was used to create a `SigRef` with
/// [`FunctionBuilder::signature`](https://docs.rs/cranelift-frontend/*/cranelift_frontend/struct.FunctionBuilder.html#method.signature) or
/// [`func.dfg.signatures`](super::dfg::DataFlowGraph::signatures).
///
/// While the order is stable, it is arbitrary.
#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
pub struct SigRef(u32);
entity_impl!(SigRef, "sig");
impl SigRef {
/// Create a new function signature reference from its number.
///
/// This method is for use by the parser.
pub fn with_number(n: u32) -> Option<Self> {
if n < u32::MAX {
Some(Self(n))
} else {
None
}
}
}
/// An opaque reference to a [WebAssembly
/// table](https://developer.mozilla.org/en-US/docs/WebAssembly/Understanding_the_text_format#WebAssembly_tables).
///
/// `Table`s are used to store a list of function references.
/// They can be created with [`FuncEnvironment::make_table`](https://docs.rs/cranelift-wasm/*/cranelift_wasm/trait.FuncEnvironment.html#tymethod.make_table).
/// They can be used with
/// [`FuncEnvironment::translate_call_indirect`](https://docs.rs/cranelift-wasm/*/cranelift_wasm/trait.FuncEnvironment.html#tymethod.translate_call_indirect).
///
/// While the order is stable, it is arbitrary.
#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
pub struct Table(u32);
entity_impl!(Table, "table");
impl Table {
/// Create a new table reference from its number.
///
/// This method is for use by the parser.
pub fn with_number(n: u32) -> Option<Self> {
if n < u32::MAX {
Some(Self(n))
} else {
None
}
}
}
/// An opaque reference to any of the entities defined in this module that can appear in CLIF IR.
#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
pub enum AnyEntity {
/// The whole function.
Function,
/// a basic block.
Block(Block),
/// An instruction.
Inst(Inst),
/// An SSA value.
Value(Value),
/// A stack slot.
StackSlot(StackSlot),
/// A dynamic stack slot.
DynamicStackSlot(DynamicStackSlot),
/// A dynamic type
DynamicType(DynamicType),
/// A Global value.
GlobalValue(GlobalValue),
/// A jump table.
JumpTable(JumpTable),
/// A constant.
Constant(Constant),
/// An external function.
FuncRef(FuncRef),
/// A function call signature.
SigRef(SigRef),
/// A table.
Table(Table),
/// A function's stack limit
StackLimit,
}
impl fmt::Display for AnyEntity {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Self::Function => write!(f, "function"),
Self::Block(r) => r.fmt(f),
Self::Inst(r) => r.fmt(f),
Self::Value(r) => r.fmt(f),
Self::StackSlot(r) => r.fmt(f),
Self::DynamicStackSlot(r) => r.fmt(f),
Self::DynamicType(r) => r.fmt(f),
Self::GlobalValue(r) => r.fmt(f),
Self::JumpTable(r) => r.fmt(f),
Self::Constant(r) => r.fmt(f),
Self::FuncRef(r) => r.fmt(f),
Self::SigRef(r) => r.fmt(f),
Self::Table(r) => r.fmt(f),
Self::StackLimit => write!(f, "stack_limit"),
}
}
}
impl fmt::Debug for AnyEntity {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
(self as &dyn fmt::Display).fmt(f)
}
}
impl From<Block> for AnyEntity {
fn from(r: Block) -> Self {
Self::Block(r)
}
}
impl From<Inst> for AnyEntity {
fn from(r: Inst) -> Self {
Self::Inst(r)
}
}
impl From<Value> for AnyEntity {
fn from(r: Value) -> Self {
Self::Value(r)
}
}
impl From<StackSlot> for AnyEntity {
fn from(r: StackSlot) -> Self {
Self::StackSlot(r)
}
}
impl From<DynamicStackSlot> for AnyEntity {
fn from(r: DynamicStackSlot) -> Self {
Self::DynamicStackSlot(r)
}
}
impl From<DynamicType> for AnyEntity {
fn from(r: DynamicType) -> Self {
Self::DynamicType(r)
}
}
impl From<GlobalValue> for AnyEntity {
fn from(r: GlobalValue) -> Self {
Self::GlobalValue(r)
}
}
impl From<JumpTable> for AnyEntity {
fn from(r: JumpTable) -> Self {
Self::JumpTable(r)
}
}
impl From<Constant> for AnyEntity {
fn from(r: Constant) -> Self {
Self::Constant(r)
}
}
impl From<FuncRef> for AnyEntity {
fn from(r: FuncRef) -> Self {
Self::FuncRef(r)
}
}
impl From<SigRef> for AnyEntity {
fn from(r: SigRef) -> Self {
Self::SigRef(r)
}
}
impl From<Table> for AnyEntity {
fn from(r: Table) -> Self {
Self::Table(r)
}
}
#[cfg(test)]
mod tests {
use super::*;
use alloc::string::ToString;
use core::u32;
#[test]
fn value_with_number() {
assert_eq!(Value::with_number(0).unwrap().to_string(), "v0");
assert_eq!(Value::with_number(1).unwrap().to_string(), "v1");
assert_eq!(Value::with_number(u32::MAX / 2), None);
assert!(Value::with_number(u32::MAX / 2 - 1).is_some());
}
#[test]
fn memory() {
use crate::packed_option::PackedOption;
use core::mem;
// This is the whole point of `PackedOption`.
assert_eq!(
mem::size_of::<Value>(),
mem::size_of::<PackedOption<Value>>()
);
}
#[test]
fn memory_option() {
use core::mem;
// PackedOption is used because Option<EntityRef> is twice as large
// as EntityRef. If this ever fails to be the case, this test will fail.
assert_eq!(mem::size_of::<Value>() * 2, mem::size_of::<Option<Value>>());
}
#[test]
fn constant_with_number() {
assert_eq!(Constant::with_number(0).unwrap().to_string(), "const0");
assert_eq!(Constant::with_number(1).unwrap().to_string(), "const1");
}
}
| true
|
a1fed542734f016501fa79f1c2a1b727162425a6
|
Rust
|
winjoexd/winweb
|
/client/src/lib.rs
|
UTF-8
| 1,784
| 2.671875
| 3
|
[] |
no_license
|
#![recursion_limit="10000"]
use wasm_bindgen::prelude::*;
use yew::prelude::*;
use yew::services::websocket::{WebSocketService, WebSocketStatus, WebSocketTask};
struct Model {
link: ComponentLink<Self>,
value: i64,
ws: Option<WebSocketTask>,
}
enum Msg {
AddOne,
MinusOne,
ConnectClick,
}
fn handle_connect(){
}
impl Component for Model {
type Message = Msg;
type Properties = ();
fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self {
Self {
link,
value: 0,
ws: None,
}
}
fn update(&mut self, msg: Self::Message) -> ShouldRender {
match msg {
Msg::AddOne => self.value += 1,
Msg::MinusOne => self.value -= 1,
Msg::ConnectClick => handle_connect(),
}
true
}
fn change(&mut self, _props: Self::Properties) -> ShouldRender {
false
}
fn view(&self) -> Html {
html! {
<div>
<div>
<button onclick=self.link.callback(|_| Msg::AddOne)>{ "+1" }</button>
<button onclick=self.link.callback(|_| Msg::MinusOne)>{ "-1" }</button>
<p>{ self.value }</p>
</div>
<p>
<button onclick=self.link.callback(|_| Msg::ConnectClick)>{ "Connect" }</button>
<button id="disconnect">{ "Disconnect" }</button>
</p>
<p>{ "Connected: " } { !self.ws.is_none() } </p><br/>
<button id="send">{ "Send" }</button>
<input id="text" type="text"/>
</div>
}
}
}
#[wasm_bindgen(start)]
pub fn run_app() {
App::<Model>::new().mount_to_body();
}
| true
|
d028277ecb2a75d41f35800b7ba475828337b3ec
|
Rust
|
AaronC81/flamegraph
|
/src/bin/flamegraph.rs
|
UTF-8
| 916
| 2.578125
| 3
|
[
"Apache-2.0",
"MIT"
] |
permissive
|
use anyhow::anyhow;
use structopt::StructOpt;
use flamegraph::Workload;
#[derive(Debug, StructOpt)]
#[structopt(
setting = structopt::clap::AppSettings::TrailingVarArg
)]
struct Opt {
/// Profile a running process by pid
#[structopt(short = "p", long = "pid")]
pid: Option<u32>,
#[structopt(flatten)]
graph: flamegraph::Options,
trailing_arguments: Vec<String>,
}
fn main() -> anyhow::Result<()> {
let opt = Opt::from_args();
let workload = match (opt.pid, opt.trailing_arguments.is_empty()) {
(Some(p), true) => Workload::Pid(p),
(None, false) => Workload::Command(opt.trailing_arguments.clone()),
(Some(_), false) => return Err(anyhow!("cannot pass in command with --pid")),
(None, true) => return Err(anyhow!("no workload given to generate a flamegraph for")),
};
flamegraph::generate_flamegraph_for_workload(workload, opt.graph)
}
| true
|
698eca2b342c63c31471c6f07228ab8d30f5e319
|
Rust
|
bryanburgers/advent-of-code-2017.rs
|
/day-9/src/main.rs
|
UTF-8
| 1,025
| 3.5625
| 4
|
[] |
no_license
|
use std::io::Read;
mod lexer;
fn main() {
let mut buffer = String::new();
// Get the input
std::io::stdin().read_to_string(&mut buffer)
.expect("Read stdin");
let buffer = buffer.trim();
let result = day9a(&buffer);
println!("One: {}", result);
let result = day9b(&buffer);
println!("Two: {}", result);
}
fn day9a(input: &str) -> u32 {
let lexer = lexer::Lexer::new(input.chars());
let mut score = 0;
let mut current_level = 0;
for i in lexer {
match i {
lexer::Token::GroupStart => {
current_level += 1;
score += current_level;
},
lexer::Token::GroupEnd => {
current_level -= 1;
},
_ => {},
}
}
score
}
fn day9b(input: &str) -> usize {
let lexer = lexer::Lexer::new(input.chars());
let filtered = lexer.filter(|x| match *x {
lexer::Token::Garbage(_) => true,
_ => false,
});
filtered.count()
}
| true
|
42a81fa07be61e02e309b36e1bec17ded3ca6975
|
Rust
|
TummeliRuonakoski/CodeWars
|
/8 kyu/Do I get a bonus?/Rust.rs
|
UTF-8
| 624
| 3.6875
| 4
|
[] |
no_license
|
fn bonus_time(salary: u64, bonus: bool) -> String {
if bonus{
format!("¥{}0",salary)
}else{
format!("¥{}",salary)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_basic_cases() {
assert_eq!(bonus_time(10000, true), "¥100000");
assert_eq!(bonus_time(25000, true), "¥250000");
assert_eq!(bonus_time(10000, false), "¥10000");
assert_eq!(bonus_time(60000, false), "¥60000");
assert_eq!(bonus_time(2, true), "¥20");
assert_eq!(bonus_time(78, false), "¥78");
assert_eq!(bonus_time(67890, true), "¥678900");
}
}
| true
|
d35c8095aa7c69af587de429d1828b0e75ddc4ee
|
Rust
|
occar421/real-world-http-2-example-in-rust
|
/chapter-3/src/list-3-5.rs
|
UTF-8
| 380
| 2.71875
| 3
|
[
"MIT"
] |
permissive
|
//! リスト 3-5: HEAD メソッドを送信してヘッダーを取得する
use reqwest::Client;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = Client::new();
let resp = client.head("http://localhost:18888").send().await?;
println!("Status:{}", resp.status());
println!("Headers:{:?}", resp.headers());
Ok(())
}
| true
|
c858a90f97f9978aa9028cc6563b0e3c4f3a25bd
|
Rust
|
ityy/rust_study
|
/src/book_study_notes/book01_the_tao_of_programming/src/c02_outline/t2_4_5_closure.rs
|
UTF-8
| 1,818
| 4.21875
| 4
|
[] |
no_license
|
//! # 闭包 closure
//! ## 闭包的特点:
//! 1. 可以像匿名函数一样被调用
//! 2. 可以捕获上下文环境中的自由变量 (而函数不可以)
//! 3. 可以自动推断输入和返回的类型
//!
//! ## Rust中闭包的原理:
//! Rust中的闭包是由一个匿名结构体和trait组合实现的。本质上是一个实现了指定特性的结构体。了解本质,对闭包的使用会更加清晰明了。
/// ## 闭包的声明
#[test]
fn test_closure() {
let out = 42;
// 函数捕获out报错:
//fn add(i: i32, j: i32) -> i32 { i + j + out } //error[E0434]: can't capture dynamic environment in a fn item 无法在fn项中捕获动态环境
//闭包 带类型注解
let closure_annotated = |i: i32, j: i32| -> i32{ i + j + out };//使用外部变量
//闭包 不带类型注解,可以自动推断
let closure_inferred = |i, j| i + j + out;
//调用闭包
assert_eq!(45, closure_annotated(1, 2));
assert_eq!(45, closure_inferred(1, 2));
}
/// ## 闭包作为参数
#[test]
fn closure_as_parameter() {
fn math<F>(op: F) -> i32
//泛型F 受Fn()->i32特性限制
//注意:约束泛型的是Fn特性,fn可以作为类型注解,但不能约束泛型。
where F: Fn() -> i32 {
op()
}
assert_eq!(3, math(|| 1 + 2));
assert_eq!(2, math(|| 1 * 2));
}
/// ## 闭包作为返回值
#[test]
fn closure_as_returned() {
//返回闭包 也就是返回实现了 “impl Fn(i32) -> i32” 特性的结构体 细节由编译器实现
fn two_times_impl() -> impl Fn(i32) -> i32 {
let i = 1;
//声明一个闭包
//move表示将被捕获变量的所有权移动给闭包
move |j| j + i
}
let closure_ = two_times_impl();
assert_eq!(3, closure_(2));
}
| true
|
a1b3318fd59b0d0e502cc570176d68bd9ced6158
|
Rust
|
pbl-2018-hillclimb/burning-pro-server
|
/burning-pro-server/src/models/update.rs
|
UTF-8
| 3,986
| 2.609375
| 3
|
[] |
no_license
|
//! Data types insertable to DB.
// Temporal silence until diesel-1.4.
// See <https://github.com/diesel-rs/diesel/issues/1785#issuecomment-422579609>.
#![allow(proc_macro_derive_resolution_fallback)]
use chrono::NaiveDateTime;
use schema::*;
/// GoodPhrase tag.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash, Serialize, Identifiable, Insertable)]
#[table_name = "good_phrase_tags"]
#[primary_key(good_phrase_tag_id)]
pub struct NewGoodPhraseTag<'a> {
/// Row ID.
pub good_phrase_tag_id: Option<i32>,
/// UTC datetime the row is created at.
pub created_at: &'a NaiveDateTime,
/// UTC datetime the row is last modified at.
pub modified_at: &'a NaiveDateTime,
/// Tag name.
pub name: &'a str,
/// Tag description.
pub description: Option<&'a str>,
}
/// GoodPhrase.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash, Serialize, Identifiable, Insertable)]
#[table_name = "good_phrases"]
#[primary_key(good_phrase_id)]
pub struct NewGoodPhrase<'a> {
/// Row ID.
pub good_phrase_id: Option<i32>,
/// UTC datetime the row is created at.
pub created_at: &'a NaiveDateTime,
/// UTC datetime the row is last modified at.
pub modified_at: &'a NaiveDateTime,
/// Title.
pub title: &'a str,
/// Phrase.
pub phrase: &'a str,
/// Person ID of the author.
pub person_id: i32,
/// URL of the phrase if exists.
pub url: Option<&'a str>,
/// Whether the phrase is deleted.
pub deleted: bool,
/// UTC datetime the phrase is published at (if known).
pub published_at: Option<&'a NaiveDateTime>,
}
/// GoodPhraseRequest.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash, Serialize, Identifiable, Insertable)]
#[table_name = "good_phrase_requests"]
#[primary_key(good_phrase_request_id)]
pub struct NewGoodPhraseRequest<'a> {
/// Row ID.
pub good_phrase_request_id: Option<i32>,
/// Phrase.
pub phrase: &'a str,
/// Author.
pub person: &'a str,
/// URL of the phrase if exists.
pub url: Option<&'a str>,
/// Whether the phrase is deleted.
pub deleted: bool,
/// UTC datetime the phrase is published at (if known).
pub published_at: Option<&'a NaiveDateTime>,
}
/// GoodPhrase and tag.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash, Serialize, Identifiable, Insertable)]
#[table_name = "good_phrases_and_tags"]
#[primary_key(good_phrase_and_tag_id)]
pub struct NewGoodPhraseAndTag<'a> {
/// Row ID.
pub good_phrase_and_tag_id: Option<i32>,
/// UTC datetime the row is created at.
pub created_at: &'a NaiveDateTime,
/// UTC datetime the row is last modified at.
pub modified_at: &'a NaiveDateTime,
/// GoodPhrase ID.
pub good_phrase_id: i32,
/// GoodPhrase tag ID.
pub good_phrase_tag_id: i32,
}
/// Person and URL.
#[derive(
Debug, Clone, PartialEq, Eq, PartialOrd, Hash, Serialize, Identifiable, Queryable, Insertable,
)]
#[table_name = "person_urls"]
#[primary_key(person_url_id)]
pub struct NewPersonUrl<'a> {
/// Row ID.
pub person_url_id: Option<i32>,
/// UTC datetime the row is created at.
pub created_at: &'a NaiveDateTime,
/// UTC datetime the row is last modified at.
pub modified_at: &'a NaiveDateTime,
/// Person ID.
pub person_id: i32,
/// URL.
pub url: &'a str,
}
/// Person.
#[derive(
Debug, Clone, PartialEq, Eq, PartialOrd, Hash, Serialize, Identifiable, Queryable, Insertable,
)]
#[table_name = "persons"]
#[primary_key(person_id)]
pub struct NewPerson<'a> {
/// Row ID.
pub person_id: Option<i32>,
/// UTC datetime the row is created at.
pub created_at: &'a NaiveDateTime,
/// UTC datetime the row is last modified at.
pub modified_at: &'a NaiveDateTime,
/// Real name.
pub real_name: Option<&'a str>,
/// Display name.
///
/// This can be unofficial name.
pub display_name: &'a str,
/// Twitter account (if known).
pub twitter: Option<&'a str>,
}
| true
|
9c8c5d04b452bba5fc8de7bc939a4d2f6ff49fbb
|
Rust
|
tengrommel/leetcode_in_rust
|
/leetcode/8_string_to_integer/main.rs
|
UTF-8
| 1,530
| 3.5625
| 4
|
[] |
no_license
|
struct Solution;
impl Solution {
pub fn my_atoi(str: String) -> i32 {
let mut str = str.trim();
let mut ret: i64 = 0;
let mut sign: bool = false;
match str.chars().nth(0) {
Some(c) => match c {
'-' => {
sign = true;
str = &str[1..];
}
'+' => {
str = &str[1..];
}
c if c >= '0' && c <= '9' => {}
_ => {
return 0;
}
},
None => {
return 0;
}
}
for c in str.chars() {
if c >= '0' && c <= '9' {
ret = ret * 10 + c as i64 - '0' as i64;
} else {
break;
}
match sign {
true if -ret < i32::MIN as i64 => return i32::MIN,
false if ret > i32::MAX as i64 => return i32::MAX,
_ => {}
}
}
if sign {
ret = -ret
}
ret as i32
}
}
#[test]
fn test() {
assert_eq!(Solution::my_atoi("aa".to_string()), 0);
assert_eq!(Solution::my_atoi("-91283472332".to_string()), -2147483648);
assert_eq!(Solution::my_atoi("words and 987".to_string()), 0);
assert_eq!(Solution::my_atoi("4193 with words".to_string()), 4193);
assert_eq!(Solution::my_atoi("42".to_string()), 42);
assert_eq!(Solution::my_atoi("004193333".to_string()), 4193333);
}
| true
|
45626ea16354020c3459b5bc49dc5dc6ed0256b6
|
Rust
|
MinusGix/hiex
|
/src/truncate.rs
|
UTF-8
| 2,309
| 3.171875
| 3
|
[] |
no_license
|
use std::{fs::File, io::Cursor};
use usize_cast::IntoUsize;
// TODO: tests
/// A trait for objects which can be truncated
/// Mainly meant to be used in conjunction with `Write` (and maybe `Seek`)
/// NOTE: This can be also used for increasing the available size.
/// Of which the default should be `0` in cases where it is for bytes.
/// If `Seek` is implemented then it should preserve the position if it is before the end
/// if the position is after the end then it should be set to the last valid position
pub trait Truncate {
fn truncate(&mut self, new_len: u64) -> std::io::Result<()>;
}
impl Truncate for File {
fn truncate(&mut self, new_len: u64) -> std::io::Result<()> {
self.set_len(new_len)
}
}
impl Truncate for Cursor<&mut Vec<u8>> {
fn truncate(&mut self, new_len: u64) -> std::io::Result<()> {
let position = self.position();
if position >= new_len {
// TODO: check this. Is 0 a sensible value? also will this be good?
self.set_position(new_len.saturating_sub(1));
}
let new_len = new_len.into_usize();
// SANITY: Since messing with the underlying vector as we do can mess with the position
// we manually make sure the position is within bounds above.
self.get_mut().resize(new_len, 0);
Ok(())
}
}
impl Truncate for Cursor<Vec<u8>> {
fn truncate(&mut self, new_len: u64) -> std::io::Result<()> {
let position = self.position();
if position >= new_len {
// TODO: check this. Is 0 a sensible value? also will this be good?
self.set_position(new_len.saturating_sub(1));
}
let new_len = new_len.into_usize();
// SANITY: Since messing with the underlying vector as we do can mess with the position
// we manually make sure the position is within bounds above.
self.get_mut().resize(new_len, 0);
Ok(())
}
}
#[cfg(feature = "tempfile")]
impl Truncate for tempfile::NamedTempFile {
fn truncate(&mut self, new_len: u64) -> std::io::Result<()> {
self.as_file_mut().truncate(new_len)
}
}
#[cfg(feature = "tempfile")]
impl Truncate for tempfile::SpooledTempFile {
fn truncate(&mut self, new_len: u64) -> std::io::Result<()> {
self.set_len(new_len)
}
}
| true
|
d97dccb734ab93d501910e19d9808d9e0fec84f1
|
Rust
|
bjorn3/yk
|
/ykpack/src/types.rs
|
UTF-8
| 31,193
| 3.28125
| 3
|
[
"Apache-2.0",
"MIT"
] |
permissive
|
//! Types for the Yorick intermediate language.
use serde::{Deserialize, Serialize};
use std::{
convert::TryFrom,
fmt::{self, Display},
mem,
};
pub type CrateHash = u64;
pub type DefIndex = u32;
pub type BasicBlockIndex = u32;
pub type StatementIndex = usize;
pub type LocalIndex = u32;
pub type TyIndex = u32;
pub type FieldIndex = u32;
pub type TypeId = (u64, TyIndex); // Crate hash and vector index.
/// The type of a local variable.
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone, Hash)]
pub enum Ty {
/// Signed integers.
SignedInt(SignedIntTy),
/// Unsigned integers.
UnsignedInt(UnsignedIntTy),
/// A structure type.
Struct(StructTy),
/// A tuple type.
Tuple(TupleTy),
/// A reference to something.
Ref(TypeId),
/// A Boolean.
Bool,
/// Anything that we've not yet defined a lowering for.
Unimplemented(String),
}
impl Display for Ty {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Ty::SignedInt(si) => write!(f, "{}", si),
Ty::UnsignedInt(ui) => write!(f, "{}", ui),
Ty::Struct(sty) => write!(f, "{}", sty),
Ty::Tuple(tty) => write!(f, "{}", tty),
Ty::Ref(rty) => write!(f, "&{:?}", rty),
Ty::Bool => write!(f, "bool"),
Ty::Unimplemented(m) => write!(f, "Unimplemented: {}", m),
}
}
}
impl Ty {
pub fn size(&self) -> u64 {
match self {
Ty::UnsignedInt(ui) => match ui {
UnsignedIntTy::U8 => 1,
UnsignedIntTy::U16 => 2,
UnsignedIntTy::U32 => 4,
UnsignedIntTy::U64 => 8,
UnsignedIntTy::Usize => u64::try_from(mem::size_of::<usize>()).unwrap(),
UnsignedIntTy::U128 => 16,
},
Ty::SignedInt(ui) => match ui {
SignedIntTy::I8 => 1,
SignedIntTy::I16 => 2,
SignedIntTy::I32 => 4,
SignedIntTy::I64 => 8,
SignedIntTy::Isize => u64::try_from(mem::size_of::<isize>()).unwrap(),
SignedIntTy::I128 => 16,
},
Ty::Struct(sty) => u64::try_from(sty.size_align.size).unwrap(),
Ty::Tuple(tty) => u64::try_from(tty.size_align.size).unwrap(),
Ty::Ref(_) => u64::try_from(mem::size_of::<usize>()).unwrap(),
Ty::Bool => u64::try_from(mem::size_of::<bool>()).unwrap(),
_ => todo!("{:?}", self),
}
}
pub fn align(&self) -> u64 {
match self {
Ty::UnsignedInt(ui) => match ui {
UnsignedIntTy::U8 => 1,
UnsignedIntTy::U16 => 2,
UnsignedIntTy::U32 => 4,
UnsignedIntTy::U64 => 8,
UnsignedIntTy::Usize =>
{
#[cfg(target_arch = "x86_64")]
8
}
UnsignedIntTy::U128 => 16,
},
Ty::SignedInt(ui) => match ui {
SignedIntTy::I8 => 1,
SignedIntTy::I16 => 2,
SignedIntTy::I32 => 4,
SignedIntTy::I64 => 8,
SignedIntTy::Isize =>
{
#[cfg(target_arch = "x86_64")]
8
}
SignedIntTy::I128 => 16,
},
Ty::Struct(sty) => u64::try_from(sty.size_align.align).unwrap(),
Ty::Tuple(tty) => u64::try_from(tty.size_align.align).unwrap(),
Ty::Ref(_) =>
{
#[cfg(target_arch = "x86_64")]
8
}
Ty::Bool => u64::try_from(mem::size_of::<bool>()).unwrap(),
_ => todo!("{:?}", self),
}
}
}
/// Describes the various signed integer types.
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone, Hash)]
pub enum SignedIntTy {
Isize,
I8,
I16,
I32,
I64,
I128,
}
impl Display for SignedIntTy {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let s = match self {
Self::Isize => "isize",
Self::I8 => "i8",
Self::I16 => "i16",
Self::I32 => "i32",
Self::I64 => "i64",
Self::I128 => "i128",
};
write!(f, "{}", s)
}
}
/// Describes the various unsigned integer types.
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone, Hash)]
pub enum UnsignedIntTy {
Usize,
U8,
U16,
U32,
U64,
U128,
}
impl Display for UnsignedIntTy {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let s = match self {
Self::Usize => "usize",
Self::U8 => "u8",
Self::U16 => "u16",
Self::U32 => "u32",
Self::U64 => "u64",
Self::U128 => "u128",
};
write!(f, "{}", s)
}
}
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone, Hash)]
pub struct Fields {
/// Field offsets.
pub offsets: Vec<u64>,
/// The type of each field.
pub tys: Vec<TypeId>,
}
impl Display for Fields {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"offsets: [{}], tys: [{}]",
self.offsets
.iter()
.map(|o| o.to_string())
.collect::<Vec<String>>()
.join(", "),
self.tys
.iter()
.map(|t| format!("{:?}", t))
.collect::<Vec<String>>()
.join(", ")
)
}
}
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone, Hash)]
pub struct SizeAndAlign {
/// The alignment, in bytes.
pub align: i32, // i32 for use as a dynasm operand.
/// The size, in bytes.
pub size: i32, // Also i32 for dynasm.
}
impl Display for SizeAndAlign {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "align: {}, size: {}", self.align, self.size)
}
}
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone, Hash)]
pub struct TupleTy {
/// The fields of the tuple.
pub fields: Fields,
/// The size and alignment of the tuple.
pub size_align: SizeAndAlign,
}
impl Display for TupleTy {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "TupleTy {{ {}, {} }}", self.fields, self.size_align)
}
}
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone, Hash)]
pub struct StructTy {
/// The fields of the struct.
pub fields: Fields,
/// The size and alignment of the struct.
pub size_align: SizeAndAlign,
}
impl Display for StructTy {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "StructTy {{ {}, {} }}", self.fields, self.size_align)
}
}
/// rmp-serde serialisable 128-bit numeric types, to work around:
/// https://github.com/3Hren/msgpack-rust/issues/169
macro_rules! new_ser128 {
($n: ident, $t: ty) => {
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)]
pub struct $n {
hi: u64,
lo: u64,
}
impl $n {
pub fn new(val: $t) -> Self {
Self {
hi: (val >> 64) as u64,
lo: val as u64,
}
}
pub fn val(&self) -> $t {
(self.hi as $t) << 64 | self.lo as $t
}
}
impl Display for $n {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}{}", self.val(), stringify!($t))
}
}
};
}
new_ser128!(SerU128, u128);
new_ser128!(SerI128, i128);
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone, Copy, Hash, Ord, PartialOrd)]
pub struct Local(pub LocalIndex);
impl Display for Local {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "${}", self.0)
}
}
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone, Hash)]
pub struct Place {
pub local: Local,
pub projection: Vec<Projection>,
}
impl Place {
fn push_maybe_defined_locals(&self, locals: &mut Vec<Local>) {
locals.push(self.local);
}
fn push_used_locals(&self, locals: &mut Vec<Local>) {
locals.push(self.local);
}
}
impl Display for Place {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.projection.is_empty() {
write!(f, "{}", self.local)?;
} else {
let mut s = format!("({})", self.local);
for p in &self.projection {
match p {
Projection::Deref => {
s = format!("*({})", s);
}
_ => {
s.push_str(&format!("{}", p));
}
}
}
write!(f, "{}", s)?;
}
Ok(())
}
}
impl From<Local> for Place {
fn from(local: Local) -> Self {
Self {
local,
projection: Vec::new(),
}
}
}
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone, Hash)]
pub enum PlaceBase {
Local(Local),
Static, // FIXME not implemented
}
impl Display for PlaceBase {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Local(l) => write!(f, "{}", l),
Self::Static => write!(f, "Static"),
}
}
}
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone, Hash)]
pub enum Projection {
Field(FieldIndex),
Deref,
Unimplemented(String),
}
impl Display for Projection {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Field(idx) => write!(f, ".{}", idx),
Self::Deref => write!(f, ""),
Self::Unimplemented(s) => write!(f, ".(unimplemented projection: {:?})", s),
}
}
}
/// Bits in the `flags` bitfield in `Body`.
pub mod bodyflags {
pub const TRACE_HEAD: u8 = 1;
pub const TRACE_TAIL: u8 = 1 << 1;
pub const DO_NOT_TRACE: u8 = 1 << 2;
}
/// The definition of a local variable, including its type.
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)]
pub struct LocalDecl {
pub ty: TypeId,
}
impl Display for LocalDecl {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}", self.ty)
}
}
/// A tracing IR pack.
/// Each Body maps to exactly one MIR Body.
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)]
pub struct Body {
pub symbol_name: String,
pub blocks: Vec<BasicBlock>,
pub flags: u8,
pub trace_inputs_local: Option<Local>,
pub local_decls: Vec<LocalDecl>,
}
impl Display for Body {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
writeln!(f, "symbol: {}", self.symbol_name)?;
writeln!(f, " flags: {}", self.flags)?;
writeln!(f, " local_decls:")?;
for (di, d) in self.local_decls.iter().enumerate() {
writeln!(f, " {}: {}", di, d)?;
}
let mut block_strs = Vec::new();
for (i, b) in self.blocks.iter().enumerate() {
block_strs.push(format!(" bb{}:\n{}", i, b));
}
writeln!(f, " blocks:")?;
writeln!(f, "{}", block_strs.join("\n"))?;
Ok(())
}
}
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)]
pub struct BasicBlock {
pub stmts: Vec<Statement>,
pub term: Terminator,
}
impl BasicBlock {
pub fn new(stmts: Vec<Statement>, term: Terminator) -> Self {
Self { stmts, term }
}
}
impl Display for BasicBlock {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for s in self.stmts.iter() {
write!(f, " {}\n", s)?;
}
write!(f, " {}", self.term)
}
}
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)]
pub enum Statement {
/// Do nothing.
Nop,
/// An assignment.
Assign(Place, Rvalue),
/// Marks the entry of an inlined function call in a TIR trace. This does not appear in SIR.
Enter(CallOperand, Vec<Operand>, Option<Place>, u32),
/// Marks the exit of an inlined function call in a TIR trace. This does not appear in SIR.
Leave,
/// Marks a local variable dead.
/// Note that locals are implicitly live at first use.
StorageDead(Local),
/// A (non-inlined) call from a TIR trace to a binary symbol using the system ABI. This does
/// not appear in SIR.
Call(CallOperand, Vec<Operand>, Option<Place>),
/// Any unimplemented lowering maps to this variant.
/// The string inside is the stringified MIR statement.
Unimplemented(String),
}
impl Statement {
/// Returns a vector of locals that this SIR statement *may* define.
/// Whether or not the local is actually defined depends upon whether this is the first write
/// into the local (there is no explicit liveness marker in SIR/TIR).
pub fn maybe_defined_locals(&self) -> Vec<Local> {
let mut ret = Vec::new();
match self {
Statement::Nop => (),
Statement::Assign(place, _rval) => place.push_maybe_defined_locals(&mut ret),
// `Enter` doesn't define the destination, as that will be defined by an inlined assignment.
Statement::Enter(_target, args, _dest_place, start_idx) => {
for idx in 0..args.len() {
// + 1 to skip return value.
ret.push(Local(start_idx + u32::try_from(idx).unwrap() + 1));
}
}
Statement::Leave => (),
Statement::StorageDead(_) => (),
Statement::Call(_target, _args, dest) => {
if let Some(dest) = dest {
dest.push_maybe_defined_locals(&mut ret);
}
}
Statement::Unimplemented(_) => (),
}
ret
}
/// Returns a vector of locals that this SIR statement uses but does not define.
pub fn used_locals(&self) -> Vec<Local> {
let mut ret = Vec::new();
match self {
Statement::Nop => (),
Statement::Assign(place, rval) => {
rval.push_used_locals(&mut ret);
place.push_used_locals(&mut ret);
}
// `Enter` doesn't use the callee args. Inlined statements will use them instead.
Statement::Enter(_target, _args, _opt_place, _idx) => (),
Statement::Leave => (),
Statement::StorageDead(_) => (),
Statement::Call(_target, args, _dest) => {
for a in args {
a.push_used_locals(&mut ret);
}
}
Statement::Unimplemented(_) => (),
}
ret
}
/// Returns a vector of locals either used or defined by this statement.
pub fn referenced_locals(&self) -> Vec<Local> {
let mut ret = self.maybe_defined_locals();
ret.extend(self.used_locals());
ret
}
}
impl Display for Statement {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Statement::Nop => write!(f, "nop"),
Statement::Assign(l, r) => write!(f, "{} = {}", l, r),
Statement::Enter(op, args, dest, off) => {
let args_s = args
.iter()
.map(|a| format!("{}", a))
.collect::<Vec<String>>()
.join(", ");
let dest_s = if let Some(dest) = dest {
format!("{}", dest)
} else {
String::from("none")
};
write!(f, "enter({}, [{}], {}, {})", op, args_s, dest_s, off)
}
Statement::Leave => write!(f, "leave"),
Statement::StorageDead(local) => write!(f, "dead({})", local),
Statement::Call(op, args, dest) => {
let args_s = args
.iter()
.map(|a| format!("{}", a))
.collect::<Vec<String>>()
.join(", ");
let dest_s = if let Some(dest) = dest {
format!("{}", dest)
} else {
String::from("none")
};
write!(f, "{} = call({}, [{}])", dest_s, op, args_s)
}
Statement::Unimplemented(mir_stmt) => write!(f, "unimplemented_stmt: {}", mir_stmt),
}
}
}
/// The right-hand side of an assignment.
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)]
pub enum Rvalue {
Use(Operand),
BinaryOp(BinOp, Operand, Operand),
CheckedBinaryOp(BinOp, Operand, Operand),
Ref(Place),
Unimplemented(String),
}
impl Rvalue {
pub fn push_used_locals(&self, locals: &mut Vec<Local>) {
match self {
Rvalue::Use(opnd) => opnd.push_used_locals(locals),
Rvalue::BinaryOp(_op, opnd1, opnd2) => {
opnd1.push_used_locals(locals);
opnd2.push_used_locals(locals);
}
Rvalue::CheckedBinaryOp(_op, opnd1, opnd2) => {
opnd1.push_used_locals(locals);
opnd2.push_used_locals(locals);
}
Rvalue::Ref(plc) => plc.push_used_locals(locals),
Rvalue::Unimplemented(_) => (),
}
}
}
impl Display for Rvalue {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Use(p) => write!(f, "{}", p),
Self::BinaryOp(op, oper1, oper2) => write!(f, "{}({}, {})", op, oper1, oper2),
Self::CheckedBinaryOp(op, oper1, oper2) => {
write!(f, "checked_{}({}, {})", op, oper1, oper2)
}
Self::Ref(p) => write!(f, "&{}", p),
Self::Unimplemented(s) => write!(f, "unimplemented rvalue: {}", s),
}
}
}
impl From<Local> for Rvalue {
fn from(l: Local) -> Self {
Self::Use(Operand::from(l))
}
}
/// Unlike in MIR, we don't track move/copy semantics in operands.
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)]
pub enum Operand {
Place(Place),
Constant(Constant),
}
impl Operand {
fn push_used_locals(&self, locals: &mut Vec<Local>) {
match self {
Operand::Place(plc) => plc.push_used_locals(locals),
Operand::Constant(_) => (),
}
}
}
impl Display for Operand {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Operand::Place(p) => write!(f, "{}", p),
Operand::Constant(c) => write!(f, "{}", c),
}
}
}
impl From<Local> for Operand {
fn from(l: Local) -> Self {
Operand::Place(Place::from(l))
}
}
impl From<Place> for Operand {
fn from(p: Place) -> Self {
Operand::Place(p)
}
}
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)]
pub enum Constant {
Int(ConstantInt),
Bool(bool),
Unimplemented(String),
}
impl Constant {
pub fn i64_cast(&self) -> i64 {
match self {
Self::Int(ci) => ci.i64_cast(),
Self::Bool(b) => *b as i64,
Self::Unimplemented(_) => unreachable!(),
}
}
}
impl Display for Constant {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Constant::Int(i) => write!(f, "{}", i),
Constant::Bool(b) => write!(f, "{}", b),
Constant::Unimplemented(s) => write!(f, "unimplemented constant: {:?}", s),
}
}
}
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)]
pub enum ConstantInt {
UnsignedInt(UnsignedInt),
SignedInt(SignedInt),
}
impl From<bool> for ConstantInt {
fn from(b: bool) -> Self {
if b {
ConstantInt::UnsignedInt(UnsignedInt::Usize(1))
} else {
ConstantInt::UnsignedInt(UnsignedInt::Usize(0))
}
}
}
impl ConstantInt {
/// Returns an i64 value suitable for loading into a register.
/// If the constant is signed, then it will be sign-extended.
pub fn i64_cast(&self) -> i64 {
match self {
ConstantInt::UnsignedInt(ui) => match ui {
UnsignedInt::U8(i) => *i as i64,
UnsignedInt::U16(i) => *i as i64,
UnsignedInt::U32(i) => *i as i64,
UnsignedInt::U64(i) => *i as i64,
#[cfg(target_pointer_width = "64")]
UnsignedInt::Usize(i) => *i as i64,
UnsignedInt::U128(_) => panic!("i64_cast: u128 to isize"),
},
ConstantInt::SignedInt(si) => match si {
SignedInt::I8(i) => *i as i64,
SignedInt::I16(i) => *i as i64,
SignedInt::I32(i) => *i as i64,
SignedInt::I64(i) => *i as i64,
#[cfg(target_pointer_width = "64")]
SignedInt::Isize(i) => *i as i64,
SignedInt::I128(_) => panic!("i64_cast: i128 to isize"),
},
}
}
}
/// Generate a method that constructs a ConstantInt variant from bits in u128 form.
/// This can't be used to generate methods for 128-bit integers due to SerU128/SerI128.
macro_rules! const_int_from_bits {
($fn_name: ident, $rs_t: ident, $yk_t: ident, $yk_variant: ident) => {
pub fn $fn_name(bits: u128) -> Self {
ConstantInt::$yk_t($yk_t::$yk_variant(bits as $rs_t))
}
};
}
impl ConstantInt {
const_int_from_bits!(u8_from_bits, u8, UnsignedInt, U8);
const_int_from_bits!(u16_from_bits, u16, UnsignedInt, U16);
const_int_from_bits!(u32_from_bits, u32, UnsignedInt, U32);
const_int_from_bits!(u64_from_bits, u64, UnsignedInt, U64);
const_int_from_bits!(usize_from_bits, usize, UnsignedInt, Usize);
pub fn u128_from_bits(bits: u128) -> Self {
ConstantInt::UnsignedInt(UnsignedInt::U128(SerU128::new(bits)))
}
const_int_from_bits!(i8_from_bits, i8, SignedInt, I8);
const_int_from_bits!(i16_from_bits, i16, SignedInt, I16);
const_int_from_bits!(i32_from_bits, i32, SignedInt, I32);
const_int_from_bits!(i64_from_bits, i64, SignedInt, I64);
const_int_from_bits!(isize_from_bits, isize, SignedInt, Isize);
pub fn i128_from_bits(bits: u128) -> Self {
ConstantInt::SignedInt(SignedInt::I128(SerI128::new(bits as i128)))
}
}
impl Display for ConstantInt {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ConstantInt::UnsignedInt(u) => write!(f, "{}", u),
ConstantInt::SignedInt(s) => write!(f, "{}", s),
}
}
}
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)]
pub enum UnsignedInt {
Usize(usize),
U8(u8),
U16(u16),
U32(u32),
U64(u64),
U128(SerU128),
}
impl Display for UnsignedInt {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Usize(v) => write!(f, "{}usize", v),
Self::U8(v) => write!(f, "{}u8", v),
Self::U16(v) => write!(f, "{}u16", v),
Self::U32(v) => write!(f, "{}u32", v),
Self::U64(v) => write!(f, "{}u64", v),
Self::U128(v) => write!(f, "{}u128", v),
}
}
}
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)]
pub enum SignedInt {
Isize(isize),
I8(i8),
I16(i16),
I32(i32),
I64(i64),
I128(SerI128),
}
impl Display for SignedInt {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Isize(v) => write!(f, "{}isize", v),
Self::I8(v) => write!(f, "{}i8", v),
Self::I16(v) => write!(f, "{}i16", v),
Self::I32(v) => write!(f, "{}i32", v),
Self::I64(v) => write!(f, "{}i64", v),
Self::I128(v) => write!(f, "{}i128", v),
}
}
}
/// A call target.
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)]
pub enum CallOperand {
/// A call to a binary symbol by name.
Fn(String),
/// An unknown or unhandled callable.
Unknown, // FIXME -- Find out what else. Closures jump to mind.
}
impl CallOperand {
pub fn symbol(&self) -> Option<&str> {
if let Self::Fn(sym) = self {
Some(sym)
} else {
None
}
}
}
impl Display for CallOperand {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
CallOperand::Fn(sym_name) => write!(f, "{}", sym_name),
CallOperand::Unknown => write!(f, "<unknown>"),
}
}
}
/// A basic block terminator.
/// Note that we assume an the abort strategy, so there are no unwind or cleanup edges present.
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)]
pub enum Terminator {
Goto(BasicBlockIndex),
SwitchInt {
discr: Place,
values: Vec<SerU128>,
target_bbs: Vec<BasicBlockIndex>,
otherwise_bb: BasicBlockIndex,
},
Return,
Unreachable,
Drop {
location: Place,
target_bb: BasicBlockIndex,
},
DropAndReplace {
location: Place,
target_bb: BasicBlockIndex,
value: Operand,
},
Call {
operand: CallOperand,
args: Vec<Operand>,
/// The return value and basic block to continue at, if the call converges.
destination: Option<(Place, BasicBlockIndex)>,
},
/// The value in `cond` must equal to `expected` to advance to `target_bb`.
Assert {
cond: Place,
expected: bool,
target_bb: BasicBlockIndex,
},
Unimplemented(String), // FIXME will eventually disappear.
}
impl Display for Terminator {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Terminator::Goto(bb) => write!(f, "goto bb{}", bb),
Terminator::SwitchInt {
discr,
values,
target_bbs,
otherwise_bb,
} => write!(
f,
"switch_int {}, [{}], [{}], {}",
discr,
values
.iter()
.map(|b| format!("{}", b))
.collect::<Vec<String>>()
.join(", "),
target_bbs
.iter()
.map(|b| format!("{}", b))
.collect::<Vec<String>>()
.join(", "),
otherwise_bb
),
Terminator::Return => write!(f, "return"),
Terminator::Unreachable => write!(f, "unreachable"),
Terminator::Drop {
location,
target_bb,
} => write!(f, "drop {}, bb{}", target_bb, location,),
Terminator::DropAndReplace {
location,
value,
target_bb,
} => write!(
f,
"drop_and_replace {}, {}, bb{}",
location, value, target_bb,
),
Terminator::Call {
operand,
args,
destination,
} => {
let ret_bb = if let Some((ret_val, bb)) = destination {
write!(f, "{} = ", ret_val)?;
format!(" -> bb{}", bb)
} else {
String::from("")
};
let args_str = args
.iter()
.map(|a| format!("{}", a))
.collect::<Vec<String>>()
.join(", ");
write!(f, "call {}({}){}", operand, args_str, ret_bb)
}
Terminator::Assert {
cond,
target_bb,
expected,
} => write!(f, "assert {}, {}, bb{}", cond, target_bb, expected),
Terminator::Unimplemented(s) => write!(f, "unimplemented: {}", s),
}
}
}
/// Binary operations.
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)]
pub enum BinOp {
Add,
Sub,
Mul,
Div,
Rem,
BitXor,
BitAnd,
BitOr,
Shl,
Shr,
Eq,
Lt,
Le,
Ne,
Ge,
Gt,
Offset,
}
impl Display for BinOp {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let s = match self {
BinOp::Add => "add",
BinOp::Sub => "sub",
BinOp::Mul => "mul",
BinOp::Div => "div",
BinOp::Rem => "rem",
BinOp::BitXor => "bit_xor",
BinOp::BitAnd => "bit_and",
BinOp::BitOr => "bit_or",
BinOp::Shl => "shl",
BinOp::Shr => "shr",
BinOp::Eq => "eq",
BinOp::Lt => "lt",
BinOp::Le => "le",
BinOp::Ne => "ne",
BinOp::Ge => "ge",
BinOp::Gt => "gt",
BinOp::Offset => "offset",
};
write!(f, "{}", s)
}
}
/// The top-level pack type.
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)]
pub enum Pack {
Body(Body),
Types(Types),
}
impl Display for Pack {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Pack::Body(sir) => write!(f, "{}", sir),
Pack::Types(tys) => write!(f, "{:?}", tys),
}
}
}
/// The types used in the SIR for one specific crate.
/// Types of SIR locals reference these types using (crate-hash, array-index) pairs.
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone, Hash)]
pub struct Types {
pub crate_hash: u64,
pub types: Vec<Ty>,
/// Indices of `types` which are thread tracers.
pub thread_tracers: Vec<u32>,
}
#[cfg(test)]
mod tests {
use super::{ConstantInt, SerI128, SerU128, SignedInt, UnsignedInt};
#[test]
fn seru128_round_trip() {
let val: u128 = std::u128::MAX - 427819;
assert_eq!(SerU128::new(val).val(), val);
}
#[test]
fn seri128_round_trip() {
let val = std::i128::MIN + 77;
assert_eq!(SerI128::new(val).val(), val);
}
#[test]
fn const_u8_from_bits() {
let v = 233;
let cst = ConstantInt::u8_from_bits(v as u128);
assert_eq!(cst, ConstantInt::UnsignedInt(UnsignedInt::U8(v)));
}
#[test]
fn const_i32_from_bits() {
let v = -42i32;
let cst = ConstantInt::i32_from_bits(v as u128);
assert_eq!(cst, ConstantInt::SignedInt(SignedInt::I32(v)));
}
#[test]
fn const_u64_from_bits() {
let v = std::u64::MAX;
let cst = ConstantInt::u64_from_bits(v as u128);
assert_eq!(cst, ConstantInt::UnsignedInt(UnsignedInt::U64(v)));
}
#[test]
fn const_i128_from_bits() {
let v = -100001i128;
let cst = ConstantInt::i128_from_bits(v as u128);
match &cst {
ConstantInt::SignedInt(SignedInt::I128(seri128)) => assert_eq!(seri128.val(), v),
_ => panic!(),
}
}
}
| true
|
c27f11399769d217f94017badcc1016e8c7f01a9
|
Rust
|
erickt/cargobomb
|
/src/report.rs
|
UTF-8
| 4,446
| 2.875
| 3
|
[
"MIT",
"Apache-2.0"
] |
permissive
|
use errors::*;
use ex;
use ex_run;
use file;
use gh_mirrors;
use serde_json;
use std::path::{Path, PathBuf};
fn results_file(ex_name: &str) -> PathBuf {
ex::ex_dir(ex_name).join("results.json")
}
#[derive(Serialize, Deserialize)]
struct TestResults {
crates: Vec<CrateResult>,
}
#[derive(Serialize, Deserialize)]
struct CrateResult {
name: String,
res: Comparison,
runs: [Option<BuildTestResult>; 2],
}
#[derive(Serialize, Deserialize)]
enum Comparison {
Regressed,
Fixed,
Unknown,
SameBuildFail,
SameTestFail,
SameTestPass,
}
#[derive(Serialize, Deserialize)]
struct BuildTestResult {
res: ex_run::TestResult,
log: String,
}
pub fn gen(ex_name: &str) -> Result<()> {
let config = ex::load_config(ex_name)?;
assert_eq!(config.toolchains.len(), 2);
let ex_dir = ex::ex_dir(ex_name);
let res = ex::ex_crates_and_dirs(ex_name)?
.into_iter()
.map(|(krate, _)| {
// Any errors here will turn into unknown results
let crate_results = config
.toolchains
.iter()
.map(|tc| -> Result<BuildTestResult> {
let res = ex_run::get_test_result(ex_name, &krate, tc)?;
// If there was no test result return an error
let res = res.ok_or_else(|| Error::from("no result"))?;
let result_log = ex_run::result_log(ex_name, &krate, tc)?;
let rel_log = relative(&ex_dir, &result_log)?;
Ok(BuildTestResult {
res: res,
log: format!("{}", rel_log.display()),
})
});
// Convert errors to Nones
let mut crate_results = crate_results.map(|r| r.ok()).collect::<Vec<_>>();
let crate2 = crate_results.pop().expect("");
let crate1 = crate_results.pop().expect("");
let comp = compare(&crate1, &crate2);
CrateResult {
name: crate_to_name(&krate).unwrap_or_else(|_| "<unknown>".into()),
res: comp,
runs: [crate1, crate2],
}
})
.collect::<Vec<_>>();
let res = TestResults { crates: res };
let json = serde_json::to_string(&res)?;
info!("writing results to {}", results_file(ex_name).display());
file::write_string(&results_file(ex_name), &json)?;
write_html_files(&ex_dir)?;
Ok(())
}
fn crate_to_name(c: &ex::ExCrate) -> Result<String> {
match *c {
ex::ExCrate::Version {
ref name,
ref version,
} => Ok(format!("{}-{}", name, version)),
ex::ExCrate::Repo { ref url, ref sha } => {
let (org, name) = gh_mirrors::gh_url_to_org_and_name(url)?;
Ok(format!("{}.{}.{}", org, name, sha))
}
}
}
fn relative(parent: &Path, child: &Path) -> Result<PathBuf> {
Ok(child
.strip_prefix(parent)
.chain_err(|| "calculating relative log file")?
.into())
}
fn compare(r1: &Option<BuildTestResult>, r2: &Option<BuildTestResult>) -> Comparison {
use ex_run::TestResult::*;
match (r1, r2) {
(&Some(BuildTestResult { res: ref res1, .. }),
&Some(BuildTestResult { res: ref res2, .. })) => {
match (res1, res2) {
(&BuildFail, &BuildFail) => Comparison::SameBuildFail,
(&TestFail, &TestFail) => Comparison::SameTestFail,
(&TestPass, &TestPass) => Comparison::SameTestPass,
(&BuildFail, &TestFail) |
(&BuildFail, &TestPass) |
(&TestFail, &TestPass) => Comparison::Fixed,
(&TestPass, &TestFail) |
(&TestPass, &BuildFail) |
(&TestFail, &BuildFail) => Comparison::Regressed,
}
}
_ => Comparison::Unknown,
}
}
fn write_html_files(dir: &Path) -> Result<()> {
let html_in = include_str!("report.html");
let js_in = include_str!("report.js");
let css_in = include_str!("report.css");
let html_out = dir.join("index.html");
let js_out = dir.join("report.js");
let css_out = dir.join("report.css");
info!("writing report to {}", html_out.display());
file::write_string(&html_out, html_in)?;
file::write_string(&js_out, js_in)?;
file::write_string(&css_out, css_in)?;
Ok(())
}
| true
|
47d0cb09a01eaa39e36c904460a7c96d7325fb9b
|
Rust
|
jkinkead/tinconf
|
/src/parser/located.rs
|
UTF-8
| 8,717
| 2.953125
| 3
|
[] |
no_license
|
// Nom 4.0 implementation of nom_located.
// TODO: Separate out the CompleteStr implementations.
use std;
use std::ops::{Range, RangeFrom, RangeFull, RangeTo};
use std::str::{CharIndices, Chars, FromStr};
use bytecount;
use memchr;
use memchr::Memchr;
use nom::{AsBytes, AtEof, Compare, CompareResult, FindSubstring, FindToken, InputIter,
InputLength, InputTake, Offset, ParseTo, Slice, UnspecializedInput};
use nom::types::CompleteStr;
/// A LocatedSpan is a set of meta information about the location of a token.
///
/// The `LocatedSpan` structure can be used as an input of the nom parsers.
#[derive(PartialEq, Debug, Clone, Copy)]
pub struct LocatedSpan<T> {
/// The offset represents the position of the fragment relatively to
/// the input of the parser. It starts at offset 0.
pub offset: usize,
/// The line number of the fragment relatively to the input of the
/// parser. It starts at line 1.
pub line: u32,
/// The fragment that is spanned.
/// The fragment represents a part of the input of the parser.
pub fragment: T,
}
impl<T: AsBytes> LocatedSpan<T> {
/// Create a span for a particular input with default `offset` and
/// `line` values. You can compute the column through the `get_column` or `get_utf8_column`
/// methods.
///
/// `offset` starts at 0, `line` starts at 1, and `column` starts at 1.
pub fn new(program: T) -> LocatedSpan<T> {
LocatedSpan {
line: 1,
offset: 0,
fragment: program,
}
}
/// Returns the column index and the full current line, excluding newlines.
pub fn get_column_and_line(&self) -> (usize, String) {
let self_bytes = self.fragment.as_bytes();
let self_ptr = self_bytes.as_ptr();
let before_self = unsafe {
assert!(
self.offset <= isize::max_value() as usize,
"offset is too big"
);
let orig_input_ptr = self_ptr.offset(-(self.offset as isize));
std::slice::from_raw_parts(orig_input_ptr, self.offset)
};
let column = match memchr::memrchr(b'\n', before_self) {
None => self.offset + 1,
Some(pos) => self.offset - pos,
};
let line_end = match memchr::memchr(b'\n', self_bytes) {
None => self_bytes.len(),
Some(pos) => pos,
};
let line_start = &before_self[self.offset - (column - 1)..];
let mut line_text = String::from_utf8(line_start.to_vec()).unwrap();
line_text.push_str(&String::from_utf8(self_bytes[..line_end].to_vec()).unwrap());
let char_column = bytecount::naive_num_chars(line_start) + 1;
(char_column, line_text)
}
}
impl<T: InputLength> InputLength for LocatedSpan<T> {
fn input_len(&self) -> usize {
self.fragment.input_len()
}
}
impl<'a> InputIter for LocatedSpan<CompleteStr<'a>> {
type Item = char;
type RawItem = char;
type Iter = CharIndices<'a>;
type IterElem = Chars<'a>;
#[inline]
fn iter_indices(&self) -> Self::Iter {
self.fragment.iter_indices()
}
#[inline]
fn iter_elements(&self) -> Self::IterElem {
self.fragment.iter_elements()
}
#[inline]
fn position<P>(&self, predicate: P) -> Option<usize>
where
P: Fn(Self::RawItem) -> bool,
{
self.fragment.position(predicate)
}
#[inline]
fn slice_index(&self, count: usize) -> Option<usize> {
self.fragment.slice_index(count)
}
}
#[macro_export]
macro_rules! impl_compare {
( $fragment_type:ty, $compare_to_type:ty ) => {
impl<'a,'b> Compare<$compare_to_type> for LocatedSpan<$fragment_type> {
#[inline(always)]
fn compare(&self, t: $compare_to_type) -> CompareResult {
self.fragment.compare(t)
}
#[inline(always)]
fn compare_no_case(&self, t: $compare_to_type) -> CompareResult {
self.fragment.compare_no_case(t)
}
}
}
}
impl_compare!(CompleteStr<'a>, &'a str);
macro_rules! impl_slice_range {
( $fragment_type:ty, $range_type:ty ) => {
impl<'a> Slice<$range_type> for LocatedSpan<$fragment_type> {
fn slice(&self, range: $range_type) -> Self {
let next_fragment = self.fragment.slice(range);
self.new_from_fragment(next_fragment)
}
}
}
}
#[macro_export]
macro_rules! impl_slice_ranges {
( $fragment_type:ty ) => {
impl<'a> LocatedSpan<$fragment_type> {
fn new_from_fragment(&self, next_fragment: $fragment_type) -> Self {
if next_fragment == self.fragment {
return *self;
}
let consumed_len = self.fragment.offset(&next_fragment);
if consumed_len == 0 {
return LocatedSpan {
line: self.line,
offset: self.offset,
fragment: next_fragment
};
}
let consumed = self.fragment.slice(..consumed_len);
let next_offset = self.offset + consumed_len;
let consumed_as_bytes = consumed.as_bytes();
let iter = Memchr::new(b'\n', consumed_as_bytes);
let number_of_lines = iter.count() as u32;
let next_line = self.line + number_of_lines;
LocatedSpan {
line: next_line,
offset: next_offset,
fragment: next_fragment
}
}
}
impl_slice_range! {$fragment_type, Range<usize>}
impl_slice_range! {$fragment_type, RangeTo<usize>}
impl_slice_range! {$fragment_type, RangeFrom<usize>}
impl_slice_range! {$fragment_type, RangeFull}
}
}
impl_slice_ranges! {CompleteStr<'a>}
impl<'a> FindToken<char> for LocatedSpan<CompleteStr<'a>> {
fn find_token(&self, token: char) -> bool {
self.fragment.find_token(token)
}
}
impl<'a, T> FindSubstring<&'a str> for LocatedSpan<T>
where
T: FindSubstring<&'a str>,
{
#[inline]
fn find_substring(&self, substr: &'a str) -> Option<usize> {
self.fragment.find_substring(substr)
}
}
impl<T: AtEof> AtEof for LocatedSpan<T> {
#[inline]
fn at_eof(&self) -> bool {
self.fragment.at_eof()
}
}
impl<R: FromStr, T> ParseTo<R> for LocatedSpan<T>
where
T: ParseTo<R>,
{
#[inline]
fn parse_to(&self) -> Option<R> {
self.fragment.parse_to()
}
}
impl<'a> Offset for LocatedSpan<CompleteStr<'a>> {
fn offset(&self, second: &LocatedSpan<CompleteStr>) -> usize {
self.fragment.offset(&second.fragment)
}
}
// NOTE: This requires the new_from_fragment implementation generated by impl_slice_ranges.
impl<'a> InputTake for LocatedSpan<CompleteStr<'a>> {
fn take(&self, count: usize) -> Self {
let next_fragment = self.fragment.take(count);
self.new_from_fragment(next_fragment)
}
fn take_split(&self, count: usize) -> (Self, Self) {
let (left_fragment, right_fragment) = self.fragment.take_split(count);
// Confusingly, this returns the taken items on the right, remaining on the left.
let right_span = LocatedSpan {
line: self.line,
offset: self.offset,
fragment: right_fragment,
};
let left_span = self.new_from_fragment(left_fragment);
(left_span, right_span)
}
}
impl<'a> ToString for LocatedSpan<CompleteStr<'a>> {
fn to_string(&self) -> String {
self.fragment.0.to_string()
}
}
impl<'a> UnspecializedInput for LocatedSpan<CompleteStr<'a>> {}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn span_get_column_and_line_works() {
let base = "foo\nbar\ngaz\n";
let span = LocatedSpan {
fragment: CompleteStr(&base[9..]),
offset: 9,
line: 3,
};
let (col, line) = span.get_column_and_line();
assert_eq!(col, 2, "get_column_and_line returned bad column");
assert_eq!(
line,
String::from("gaz"),
"get_column_and_line returned line"
);
}
#[test]
fn span_get_column_and_line_works_no_newline() {
let base = "fooble";
let span = LocatedSpan {
fragment: CompleteStr(&base[2..]),
offset: 2,
line: 1,
};
let (col, line) = span.get_column_and_line();
assert_eq!(col, 3, "get_column_and_line returned bad column");
assert_eq!(
line,
String::from("fooble"),
"get_column_and_line returned line"
);
}
}
| true
|
14b789c23b7a9d437d2813cb1782998f6b7db38b
|
Rust
|
floschnell/pi-darts
|
/src/main.rs
|
UTF-8
| 1,342
| 3.46875
| 3
|
[] |
no_license
|
extern crate rand;
use std::thread;
use rand::Rng;
fn main() {
let mut hits_total = 0;
let number_threads = 4;
let number_throws_per_thread = 1000000;
let mut handles = Vec::<thread::JoinHandle<usize>>::new();
for _i in 0..number_threads {
handles.push(thread::spawn(
move || perform_throws(number_throws_per_thread),
));
}
while !handles.is_empty() {
let handle_option = handles.pop();
hits_total += handle_option.unwrap().join().unwrap();
}
let total_throws = number_throws_per_thread * number_threads;
println!(
"estimation of PI: {:.32}",
4. * (hits_total as f64 / total_throws as f64),
);
println!("PI's actual value: {:.32}", std::f32::consts::PI);
}
fn perform_throws(number_of_throws: usize) -> usize {
let mut hits = 0;
for _ in 0..number_of_throws {
let (x, y) = throw();
// using sqrt here would give us the real length
// but sqrt only distorts the function's curve
// it will not change the number of results that are below or above 1.
if x * x + y * y <= 1f64 {
hits += 1;
}
}
hits
}
fn throw() -> (f64, f64) {
(
rand::thread_rng().gen::<f64>().abs() % 1.0f64,
rand::thread_rng().gen::<f64>().abs() % 1.0f64,
)
}
| true
|
0da9020f82717b39b1f2e3dd41eebc86c220125e
|
Rust
|
rust-console/rrt0
|
/examples/n64lib/src/vi.rs
|
UTF-8
| 3,241
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
//! Video Interface
//!
//! Provides low level access to the N64 vi hardware.
use core::ptr::read_volatile;
// TODO: Heap allocate (needs std and global_allocator)
const FRAME_BUFFER: *mut u16 = 0xA010_0000 as *mut u16;
pub const WIDTH: usize = 320;
pub const HEIGHT: usize = 240;
pub const FRAME_BUFFER_SIZE: usize = WIDTH * HEIGHT * 2;
const VI_BASE: usize = 0xA440_0000;
const VI_STATUS: *mut u32 = VI_BASE as *mut u32;
const VI_DRAM_ADDR: *mut usize = (VI_BASE + 0x04) as *mut usize;
const VI_H_WIDTH: *mut u32 = (VI_BASE + 0x08) as *mut u32;
const VI_V_INTR: *mut u32 = (VI_BASE + 0x0C) as *mut u32;
const VI_CURRENT: *const u32 = (VI_BASE + 0x10) as *const u32;
const VI_TIMING: *mut u32 = (VI_BASE + 0x14) as *mut u32;
const VI_V_SYNC: *mut u32 = (VI_BASE + 0x18) as *mut u32;
const VI_H_SYNC: *mut u32 = (VI_BASE + 0x1C) as *mut u32;
const VI_H_SYNC_LEAP: *mut u32 = (VI_BASE + 0x20) as *mut u32;
const VI_H_VIDEO: *mut u32 = (VI_BASE + 0x24) as *mut u32;
const VI_V_VIDEO: *mut u32 = (VI_BASE + 0x28) as *mut u32;
const VI_V_BURST: *mut u32 = (VI_BASE + 0x2C) as *mut u32;
const VI_X_SCALE: *mut u32 = (VI_BASE + 0x30) as *mut u32;
const VI_Y_SCALE: *mut u32 = (VI_BASE + 0x34) as *mut u32;
const VIDEO_MODE: *const u32 = 0x8000_0300 as *const u32;
pub enum VideoMode {
PAL,
NTSC,
MPAL,
}
/// Video frequency in Hertz
pub fn get_video_frequency() -> u32 {
match get_video_mode() {
VideoMode::PAL => 49_656_530,
VideoMode::NTSC => 48_681_812,
VideoMode::MPAL => 48_628_316,
}
}
/// Returns the current video mode
pub fn get_video_mode() -> VideoMode {
match unsafe { read_volatile(VIDEO_MODE) } {
0 => VideoMode::PAL,
1 => VideoMode::NTSC,
_ => VideoMode::MPAL,
}
}
/// Busy-wait for VBlank
pub fn wait_for_ready() {
loop {
let current_halfline = unsafe { read_volatile(VI_CURRENT) };
if current_halfline <= 10 {
break;
}
}
}
/// Return a raw pointer to the back buffer
pub fn next_buffer() -> *mut u16 {
let current_fb = unsafe { read_volatile(VI_DRAM_ADDR) };
if current_fb & 0xFFFFF != 0 {
FRAME_BUFFER
} else {
(FRAME_BUFFER as usize + FRAME_BUFFER_SIZE) as *mut u16
}
}
/// Swap frame buffers (display the back buffer)
pub fn swap_buffer() {
unsafe {
*VI_DRAM_ADDR = next_buffer() as usize;
}
}
/// Initialize Video Interface with 320x240x16 resolution and double buffering
pub fn init() {
// Clear both frame buffers to black, writing two pixels at a time
let frame_buffer = FRAME_BUFFER as usize;
for i in 0..WIDTH * HEIGHT {
let p = (frame_buffer + i * 4) as *mut u32;
unsafe {
*p = 0x0001_0001;
}
}
// Initialize VI
unsafe {
*VI_STATUS = 0x0000_320E;
*VI_DRAM_ADDR = frame_buffer;
*VI_H_WIDTH = WIDTH as u32;
*VI_V_INTR = 2;
*VI_TIMING = 0x03E5_2239;
*VI_V_SYNC = 0x0000_020D;
*VI_H_SYNC = 0x0000_0C15;
*VI_H_SYNC_LEAP = 0x0C15_0C15;
*VI_H_VIDEO = 0x006C_02EC;
*VI_V_VIDEO = 0x0025_01FF;
*VI_V_BURST = 0x000E_0204;
*VI_X_SCALE = 0x0000_0200;
*VI_Y_SCALE = 0x0000_0400;
}
}
| true
|
9b6eb41f5ddeeb795890adaa937d26fca2341d27
|
Rust
|
takebayashi/git-calver
|
/src/repo.rs
|
UTF-8
| 1,500
| 3.015625
| 3
|
[
"Apache-2.0"
] |
permissive
|
use git2::Commit;
use git2::Oid;
use git2::Repository;
pub trait RepositoryExt {
fn walk_history<C, T>(&self, commit_id: Oid, callback: C) -> Option<T>
where
C: Fn(Oid) -> Option<T>;
fn iter_commit_id<'repo>(&'repo self, commit: &'repo Commit) -> CommitIdIter<'repo>;
}
impl RepositoryExt for Repository {
fn walk_history<C, T>(&self, commit_id: Oid, callback: C) -> Option<T>
where
C: Fn(Oid) -> Option<T>,
{
if let Some(result) = callback(commit_id) {
Some(result)
} else {
let parent_id = self.find_commit(commit_id).ok()?.parent(0).ok()?.id();
self.walk_history(parent_id, callback)
}
}
fn iter_commit_id<'repo>(&'repo self, commit: &'repo Commit) -> CommitIdIter<'repo> {
CommitIdIter {
repo: self,
started: false,
cursor: commit.id(),
}
}
}
pub struct CommitIdIter<'a> {
repo: &'a Repository,
started: bool,
cursor: Oid,
}
impl<'a> Iterator for CommitIdIter<'a> {
type Item = Oid;
fn next(&mut self) -> Option<Oid> {
if !self.started {
self.started = true;
Some(self.cursor)
} else {
let current = self.repo.find_commit(self.cursor).ok()?;
if let Ok(next_commit) = current.parent(0) {
self.cursor = next_commit.id();
Some(self.cursor)
} else {
None
}
}
}
}
| true
|
a754ca3daf2fd8cde8e46b95a2c86e89a538eff5
|
Rust
|
duytai/ssa
|
/src/core/dfg/variable.rs
|
UTF-8
| 5,040
| 2.703125
| 3
|
[] |
no_license
|
use std::collections::HashSet;
use std::cmp;
use crate::core::{
Walker,
Dictionary,
Member,
VariableComparison,
FlatVariable,
DataLink,
};
#[derive(Debug, Hash, PartialEq, Eq, Clone)]
pub struct Variable {
members: Vec<Member>,
source: String,
kind: String,
unflat: String,
}
impl Variable {
pub fn new(members: Vec<Member>, source: String, kind: String, unflat: String) -> Self {
Variable { members, source, kind, unflat }
}
pub fn get_members(&self) -> &Vec<Member> {
&self.members
}
pub fn get_source(&self) -> &str {
&self.source
}
pub fn get_kind(&self) -> &str {
&self.kind
}
pub fn get_unflat(&self) -> &str {
&self.unflat
}
pub fn parse(walker: &Walker, dict: &Dictionary) -> HashSet<Self> {
let mut ret = HashSet::new();
let fi = |walker: &Walker, _: &Vec<Walker>| {
walker.node.name == "MemberAccess"
|| walker.node.name == "Identifier"
|| walker.node.name == "IndexAccess"
|| walker.node.name == "FunctionCall"
};
let ig = |walker: &Walker, _: &Vec<Walker>| {
walker.node.name == "VariableDeclaration"
|| walker.node.name == "VariableDeclarationStatement"
|| walker.node.name == "Assignment"
};
for walker in walker.walk(true, ig, fi) {
let flat_variable = FlatVariable::new(&walker, dict);
ret.extend(flat_variable.get_variables());
}
ret
}
pub fn equal_property(&self, other: &Variable) -> bool {
if self.get_kind() == other.get_kind() {
let mut members = self.members.clone();
let mut other_members = other.members.clone();
members.reverse();
other_members.reverse();
let mut idx = 0;
while idx < cmp::min(members.len(), other_members.len()) {
let member = &members[idx];
let other_member = &other_members[idx];
match member == other_member {
true => match member == &Member::IndexAccess {
true => idx += 1,
false => return true,
},
false => return false,
}
}
}
false
}
pub fn contains(&self, other: &Variable) -> VariableComparison {
if other.members.len() > self.members.len() {
let sub = &other.members[..self.members.len()];
match sub.iter().eq(self.members.iter()) {
true => VariableComparison::Partial,
false => VariableComparison::NotEqual,
}
} else {
let sub = &self.members[..other.members.len()];
match sub.iter().eq(other.members.iter()) {
true => {
match other.members.len() == self.members.len() {
true => VariableComparison::Equal,
false => VariableComparison::Partial,
}
},
false => VariableComparison::NotEqual,
}
}
}
pub fn links(
kill_variables_tup: (HashSet<Variable>, u32),
use_variables_tup: (HashSet<Variable>, u32),
) -> HashSet<DataLink> {
let mut assignment_links = HashSet::new();
let (kill_variables, kill_id) = kill_variables_tup;
let (use_variables, use_id) = use_variables_tup;
let mut kill_unflats = HashSet::new();
let mut use_unflats = HashSet::new();
for kill_variable in kill_variables.iter() {
kill_unflats.insert(kill_variable.get_unflat());
}
for use_variable in use_variables.iter() {
use_unflats.insert(use_variable.get_unflat());
}
for kill_unflat in kill_unflats.iter() {
for use_unflat in use_unflats.iter() {
for kill_variable in kill_variables.iter() {
for use_variable in use_variables.iter() {
let kill_source = kill_variable.get_source();
let use_source = use_variable.get_source();
if kill_source.starts_with(kill_unflat) && use_source.starts_with(use_unflat) {
let kill_prop_source = &kill_source[kill_unflat.len()..];
let use_prop_source = &use_source[use_unflat.len()..];
if kill_prop_source == use_prop_source {
let data_link = DataLink::new(
(kill_variable.clone(), kill_id),
(use_variable.clone(), use_id),
);
assignment_links.insert(data_link);
}
}
}
}
}
}
assignment_links
}
}
| true
|
cf502f1ab05552ca671bfa09ff7dff6c5cd120f6
|
Rust
|
cudbg/khameleon-core
|
/src/backend/inmem.rs
|
UTF-8
| 2,003
| 2.828125
| 3
|
[] |
no_license
|
extern crate image;
use sled::{Db};
extern crate base64;
#[derive(Clone)]
pub struct InMemBackend {
dbname: String,
db: sled::Db,
}
impl InMemBackend {
pub fn new(dbname: String) -> Self {
// initialize backend server
let config = sled::ConfigBuilder::new()
.path(&dbname)
.build();
InMemBackend{dbname: dbname, db:Db::start(config).unwrap()}
}
pub fn set(&mut self, key:Vec<u8>, val: Vec<u8>) {
let _ = self.db.set(key, val);
}
pub fn drop(&mut self) {
drop(&mut self.db);
}
// get values stored at key @key
// if it doesnt exist return None+ warning?
pub fn get(&self, key:Vec<u8>) -> Option<Vec<u8>> {
if let Some(bytes) = self.db.get(&key).unwrap() {
Some(bytes.to_vec())
} else {
error!("key {:?} is not in db", &key);
None
}
}
pub fn get_iter(&self) -> sled::Iter {
self.db.iter()
}
pub fn flush(&mut self) {
match self.db.flush() {
Ok(result) => debug!("flushed successfully {:?}", result),
Err(err) => error!("flush error: {:?}", err),
};
}
pub fn collect_blocks_per_query(&self, f: fn(&Vec<u8>) -> usize) -> indexmap::IndexMap<String, usize> {
let mut blocks_per_query: indexmap::IndexMap<String, usize> = indexmap::IndexMap::new();
let iter = self.get_iter();
for result in iter {
match result {
Ok((k,v)) => {
let blocks_count = f(&v.to_vec());
let key = std::str::from_utf8(&k).unwrap();
debug!("k: {:?} count: {:?}", key.to_string(), blocks_count);
blocks_per_query.insert(
key.to_string(),
blocks_count
);
},
Err(err) => error!("{:?}", err),
}
}
blocks_per_query
}
}
| true
|
350cae894a588745b6fea29eaf551f9afdc0553a
|
Rust
|
BeatButton/aoc2019
|
/day07/src/main.rs
|
UTF-8
| 1,153
| 2.515625
| 3
|
[] |
no_license
|
use std::sync::mpsc;
use itertools::Itertools;
use intcode::{Computer, Rx, Tx};
const SOURCE: [i64; 503] = include!("input");
fn main() {
let mut max = 0;
for settings_vec in (5..=9).permutations(5) {
let mut last_signal = 0;
let mut send: Vec<Option<Tx>> = vec![];
let mut recv: Vec<Option<Rx>> = vec![];
for _ in 0..6 {
let (tx, rx) = mpsc::sync_channel(0);
send.push(Some(tx));
recv.push(Some(rx));
}
for i in (0..5).rev() {
let cpu = Computer::from_data_with_custom_io(
SOURCE.to_vec(),
recv[i].take().unwrap(),
send[i + 1].take().unwrap(),
);
cpu.run_threaded();
send[i].as_ref().unwrap().send(settings_vec[i]).unwrap();
}
let tx = send[0].take().unwrap();
let rx = recv[5].take().unwrap();
while let Ok(()) = tx.send(last_signal) {
last_signal = rx.recv().expect("failed to receive signal");
}
if last_signal > max {
max = last_signal;
}
}
println!("{}", max);
}
| true
|
9ced47dde10a599bc77d15de6da86736f98466de
|
Rust
|
yzc1114/puddle
|
/src/stdio.rs
|
UTF-8
| 2,531
| 3.046875
| 3
|
[
"MIT"
] |
permissive
|
use super::core::str::as_bytes;
use super::core::slice::iter;
use super::core::iter::Iterator;
use super::core::option::{Some, None};
static VGA_ADDRESS: uint = 0xb8000;
static VGA_WIDTH : u16 = 80;
static VGA_HEIGHT : u16 = 24;
static mut curr_x: u16 = 0;
static mut curr_y: u16 = 0;
static mut fg_color: Color = Green;
static mut bg_color: Color = Black;
pub enum Color {
Black = 0,
Blue = 1,
Green = 2,
Cyan = 3,
Red = 4,
Pink = 5,
Brown = 6,
LightGray = 7,
DarkGray = 8,
LightBlue = 9,
LightGreen = 10,
LightCyan = 11,
LightRed = 12,
LightPink = 13,
Yellow = 14,
White = 15,
}
fn range(lo: uint, hi: uint, it: |uint| ) {
let mut iter = lo;
while iter < hi {
it(iter);
iter += 1;
}
}
pub fn clear_screen() {
unsafe {
range(0, 80*25, |i| {
*((VGA_ADDRESS + i * 2) as *mut u16) = make_vgaentry(0, fg_color, bg_color);
});
}
}
pub fn backspace() {
unsafe {
if (curr_x == 0) {
curr_y -= 1;
curr_x = VGA_WIDTH - 1;
} else {
curr_x -= 1;
}
putchar(curr_x, curr_y, 0);
}
}
pub fn putc(c: u8) {
unsafe {
putchar(curr_x, curr_y, c);
curr_x += 1;
if (curr_x > VGA_WIDTH) {
curr_x -= VGA_WIDTH;
curr_y += 1;
}
}
}
pub fn newline() {
unsafe {
curr_x = 0;
curr_y += 1;
}
}
pub fn print_num(x: uint) {
putc('|' as u8);
putc(' ' as u8);
putc((((x / 1000000) % 10) as u8) + ('0' as u8));
putc((((x / 100000) % 10) as u8) + ('0' as u8));
putc((((x / 10000) % 10) as u8) + ('0' as u8));
putc((((x / 1000) % 10) as u8) + ('0' as u8));
putc((((x / 100) % 10) as u8) + ('0' as u8));
putc((((x / 10) % 10) as u8) + ('0' as u8));
putc(((x % 10) as u8) + ('0' as u8));
putc(' ' as u8);
}
pub fn putchar(x: u16, y: u16, c: u8) {
if (x >= VGA_WIDTH || y >= VGA_HEIGHT) {
return;
}
let idx : uint = (y * VGA_WIDTH * 2 + x * 2) as uint;
unsafe {
*((VGA_ADDRESS + idx) as *mut u16) = make_vgaentry(c, fg_color, bg_color);
}
}
fn make_vgaentry(c: u8, fg: Color, bg: Color) -> u16 {
let color = fg as u16 | (bg as u16 << 4);
return c as u16 | (color << 8);
}
pub fn write(s: &str) {
let bytes : &[u8] = as_bytes(s);
for b in super::core::slice::iter(bytes) {
putc(*b);
}
}
| true
|
a6e17ecbb93769c238835db1ac6409d213494521
|
Rust
|
matuzalemsteles/rust-prometheus
|
/src/process_collector.rs
|
UTF-8
| 6,203
| 2.59375
| 3
|
[
"Apache-2.0"
] |
permissive
|
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
//! Monitor a process.
//!
//! This module only supports **Linux** platform.
use std::sync::Mutex;
use crate::counter::Counter;
use crate::desc::Desc;
use crate::gauge::Gauge;
use crate::metrics::{Collector, Opts};
use crate::proto;
/// The `pid_t` data type represents process IDs.
pub use libc::pid_t;
// Six metrics per ProcessCollector.
const MERTICS_NUMBER: usize = 6;
/// A collector which exports the current state of
/// process metrics including cpu, memory and file descriptor usage as well as
/// the process start time for the given process id.
#[derive(Debug)]
pub struct ProcessCollector {
pid: pid_t,
descs: Vec<Desc>,
cpu_total: Mutex<Counter>,
open_fds: Gauge,
max_fds: Gauge,
vsize: Gauge,
rss: Gauge,
start_time: Gauge,
}
impl ProcessCollector {
/// Create a `ProcessCollector` with the given process id and namespace.
pub fn new<S: Into<String>>(pid: pid_t, namespace: S) -> ProcessCollector {
let namespace = namespace.into();
let mut descs = Vec::new();
let cpu_total = Counter::with_opts(
Opts::new(
"process_cpu_seconds_total",
"Total user and system CPU time spent in \
seconds.",
)
.namespace(namespace.clone()),
)
.unwrap();
descs.extend(cpu_total.desc().into_iter().cloned());
let open_fds = Gauge::with_opts(
Opts::new("process_open_fds", "Number of open file descriptors.")
.namespace(namespace.clone()),
)
.unwrap();
descs.extend(open_fds.desc().into_iter().cloned());
let max_fds = Gauge::with_opts(
Opts::new(
"process_max_fds",
"Maximum number of open file descriptors.",
)
.namespace(namespace.clone()),
)
.unwrap();
descs.extend(max_fds.desc().into_iter().cloned());
let vsize = Gauge::with_opts(
Opts::new(
"process_virtual_memory_bytes",
"Virtual memory size in bytes.",
)
.namespace(namespace.clone()),
)
.unwrap();
descs.extend(vsize.desc().into_iter().cloned());
let rss = Gauge::with_opts(
Opts::new(
"process_resident_memory_bytes",
"Resident memory size in bytes.",
)
.namespace(namespace.clone()),
)
.unwrap();
descs.extend(rss.desc().into_iter().cloned());
let start_time = Gauge::with_opts(
Opts::new(
"process_start_time_seconds",
"Start time of the process since unix epoch \
in seconds.",
)
.namespace(namespace.clone()),
)
.unwrap();
descs.extend(start_time.desc().into_iter().cloned());
ProcessCollector {
pid,
descs,
cpu_total: Mutex::new(cpu_total),
open_fds,
max_fds,
vsize,
rss,
start_time,
}
}
/// Return a `ProcessCollector` of the calling process.
pub fn for_self() -> ProcessCollector {
let pid = unsafe { libc::getpid() };
ProcessCollector::new(pid, "")
}
}
impl Collector for ProcessCollector {
fn desc(&self) -> Vec<&Desc> {
self.descs.iter().collect()
}
fn collect(&self) -> Vec<proto::MetricFamily> {
let p = match procfs::process::Process::new(self.pid) {
Ok(p) => p,
Err(..) => {
// we can't construct a Process object, so there's no stats to gather
return Vec::new();
}
};
// file descriptors
if let Ok(fd_list) = p.fd() {
self.open_fds.set(fd_list.len() as f64);
}
if let Ok(limits) = p.limits() {
if let procfs::process::LimitValue::Value(max) = limits.max_open_files.soft_limit {
self.max_fds.set(max as f64)
}
}
// memory
self.vsize.set(p.stat.vsize as f64);
self.rss.set(p.stat.rss as f64 * *PAGESIZE);
// proc_start_time
if let Some(boot_time) = *BOOT_TIME {
self.start_time
.set(p.stat.starttime as f64 / *CLK_TCK + boot_time);
}
// cpu
let cpu_total_mfs = {
let cpu_total = self.cpu_total.lock().unwrap();
let total = (p.stat.utime + p.stat.stime) as f64 / *CLK_TCK;
let past = cpu_total.get();
let delta = total - past;
if delta > 0.0 {
cpu_total.inc_by(delta);
}
cpu_total.collect()
};
// collect MetricFamilys.
let mut mfs = Vec::with_capacity(MERTICS_NUMBER);
mfs.extend(cpu_total_mfs);
mfs.extend(self.open_fds.collect());
mfs.extend(self.max_fds.collect());
mfs.extend(self.vsize.collect());
mfs.extend(self.rss.collect());
mfs.extend(self.start_time.collect());
mfs
}
}
lazy_static! {
// getconf CLK_TCK
static ref CLK_TCK: f64 = {
unsafe {
libc::sysconf(libc::_SC_CLK_TCK) as f64
}
};
// getconf PAGESIZE
static ref PAGESIZE: f64 = {
unsafe {
libc::sysconf(libc::_SC_PAGESIZE) as f64
}
};
}
lazy_static! {
static ref BOOT_TIME: Option<f64> = procfs::boot_time_secs().ok().map(|i| i as f64);
}
#[cfg(test)]
mod tests {
use super::*;
use crate::metrics::Collector;
use crate::registry;
#[test]
fn test_process_collector() {
let pc = ProcessCollector::for_self();
{
// Six metrics per process collector.
let descs = pc.desc();
assert_eq!(descs.len(), super::MERTICS_NUMBER);
let mfs = pc.collect();
assert_eq!(mfs.len(), super::MERTICS_NUMBER);
}
let r = registry::Registry::new();
let res = r.register(Box::new(pc));
assert!(res.is_ok());
}
}
| true
|
3b890824d3e05e9e94282a8e12093213ee9ac8c7
|
Rust
|
Anupam-Ashish-Minz/aoc2020_rust
|
/src/day2.rs
|
UTF-8
| 2,859
| 3.3125
| 3
|
[] |
no_license
|
use std::fs;
#[allow(dead_code)]
pub fn run() {
let filepath = "input/day2.input";
let input: Vec<String> = read_input_from_file(filepath);
read_input_from_file(filepath);
let output: Vec<_> = input.iter().map(|x| parse_input_string_to_tuples(x)).collect();
// testing is_valid_password
assert_eq!(true, is_valid_password_part1(1, 3, "a", "abcde"));
assert_eq!(false, is_valid_password_part1(1, 3, "b", "cdefg"));
// testing ends
let count = count_valid_passwords(&output, &is_valid_password_part1);
println!("The total number of valid passwords in part 1 are {}", count);
// testing part2
assert_eq!(true, is_valid_password_part2(1, 3, "a", "abcde"));
assert_eq!(false, is_valid_password_part2(1, 3, "b", "cdefg"));
assert_eq!(false, is_valid_password_part2(2, 9, "c", "ccccccccc"));
// testing ends
let count = count_valid_passwords(&output, &is_valid_password_part2);
println!("The total number of valid passwords in part 2 are {}", count);
}
fn read_input_from_file(filepath: &str) -> Vec<String> {
let data_from_file = fs::read_to_string(filepath).expect("Failed to red data");
data_from_file
.trim()
.split("\n")
.map(|x| x.to_string())
.collect()
}
fn parse_input_string_to_tuples <'a> (input_str: &'a str) -> (i32, i32, &'a str, &'a str) {
let idx1 = input_str.find("-").expect("Oops some error");
let idx2 = input_str.find(" ").expect("Oops some error");
let idx3 = input_str.find(":").expect("Oops some error");
(
input_str[0..idx1].parse::<i32>().unwrap(),
input_str[idx1+1..idx2].parse::<i32>().unwrap(),
&input_str[idx2+1..idx3],
&input_str[idx3+1..].trim()
)
}
fn is_valid_password_part1(n_min: i32, n_max: i32, cc: &str, input_passwd: &str) -> bool {
let cc_arr: Vec<_> = input_passwd.chars().filter(|x| x == &cc.chars().next().unwrap()).collect();
let cc_occurance = cc_arr.len() as i32;
n_max >= cc_occurance && cc_occurance>= n_min
}
fn count_valid_passwords(input: &Vec<(i32, i32, &str, &str)>, is_valid_password: &dyn Fn(i32, i32, &str, &str) -> bool ) -> i32{
let mut count=0;
for i in input {
let (n1, n2, cc, string) = i;
if is_valid_password(*n1, *n2, cc, string) {
count+=1;
}
}
return count
}
fn is_valid_password_part2(n1: i32, n2: i32, cc: &str, input_passwd: &str) -> bool {
let cc_arr: Vec<char> = input_passwd.chars().collect();
let n1: usize = (n1 - 1) as usize;
let n2: usize = (n2 - 1) as usize;
if cc_arr[n1] == cc.chars().next().unwrap() && cc_arr[n2] == cc.chars().next().unwrap() {
return false
} else if cc_arr[n1] == cc.chars().next().unwrap() || cc_arr[n2] == cc.chars().next().unwrap() {
return true
}
return false
}
| true
|
8026530f5450f3fa03a6bf8150a8153e9990c145
|
Rust
|
termoshtt/cagra
|
/cagra/tests/math.rs
|
UTF-8
| 3,768
| 2.671875
| 3
|
[
"MIT"
] |
permissive
|
use approx::abs_diff_eq;
use cagra::{error::Result, graph::Graph, tensor::*};
#[test]
fn test_exp() -> Result<()> {
let mut g = Graph::new();
let x0: f32 = 1.234;
let x = g.scalar("x", x0)?;
let y = g.exp(x);
abs_diff_eq!(g.eval_value(y)?.as_scalar()?, x0.exp());
g.eval_deriv(y)?;
abs_diff_eq!(g.get_deriv(x)?.as_scalar()?, x0.exp());
Ok(())
}
#[test]
fn test_ln() -> Result<()> {
let mut g = Graph::new();
let x0: f32 = 1.234;
let x = g.scalar("x", x0)?;
let y = g.ln(x);
abs_diff_eq!(g.eval_value(y)?.as_scalar()?, x0.ln());
g.eval_deriv(y)?;
abs_diff_eq!(g.get_deriv(x)?.as_scalar()?, 1.0 / x0);
Ok(())
}
#[test]
fn test_ln_exp() -> Result<()> {
let mut g = Graph::new();
let x0: f32 = 1.234;
let x = g.scalar("x", x0)?;
let y = g.exp(x);
let z = g.exp(y);
abs_diff_eq!(g.eval_value(z)?.as_scalar()?, x0);
g.eval_deriv(z)?;
abs_diff_eq!(g.get_deriv(x)?.as_scalar()?, 0.0);
Ok(())
}
#[test]
fn test_sin() -> Result<()> {
let mut g = Graph::new();
let x0: f32 = 1.234;
let x = g.scalar("x", x0)?;
let y = g.sin(x);
abs_diff_eq!(g.eval_value(y)?.as_scalar()?, x0.sin());
g.eval_deriv(y)?;
abs_diff_eq!(g.get_deriv(x)?.as_scalar()?, x0.cos());
Ok(())
}
#[test]
fn test_cos() -> Result<()> {
let mut g = Graph::new();
let x0: f32 = 1.234;
let x = g.scalar("x", x0)?;
let y = g.cos(x);
abs_diff_eq!(g.eval_value(y)?.as_scalar()?, x0.cos());
g.eval_deriv(y)?;
abs_diff_eq!(g.get_deriv(x)?.as_scalar()?, -x0.sin());
Ok(())
}
#[test]
fn test_sin_cos() -> Result<()> {
let mut g = Graph::new();
let x0: f32 = 1.234;
let x = g.scalar("x", x0)?;
let s = g.sin(x);
let ss = g.square(s);
let c = g.cos(x);
let cc = g.square(c);
let z = g.add(ss, cc);
abs_diff_eq!(g.eval_value(z)?.as_scalar()?, 1.0);
g.eval_deriv(z)?;
abs_diff_eq!(g.get_deriv(x)?.as_scalar()?, 0.0);
Ok(())
}
#[test]
fn test_tan() -> Result<()> {
let mut g = Graph::new();
let x0: f32 = 1.234;
let x = g.scalar("x", x0)?;
let t = g.tan(x);
let s = g.sin(x);
let c = g.cos(x);
let tc = g.mul(t, c);
let z = g.div(tc, s);
abs_diff_eq!(g.eval_value(z)?.as_scalar()?, 1.0);
g.eval_deriv(z)?;
abs_diff_eq!(g.get_deriv(x)?.as_scalar()?, 0.0);
Ok(())
}
#[test]
fn test_sinh() -> Result<()> {
let mut g = Graph::new();
let x0: f32 = 1.234;
let x = g.scalar("x", x0)?;
let y = g.sinh(x);
abs_diff_eq!(g.eval_value(y)?.as_scalar()?, x0.sinh());
g.eval_deriv(y)?;
abs_diff_eq!(g.get_deriv(x)?.as_scalar()?, x0.cosh());
Ok(())
}
#[test]
fn test_cosh() -> Result<()> {
let mut g = Graph::new();
let x0: f32 = 1.234;
let x = g.scalar("x", x0)?;
let y = g.cosh(x);
abs_diff_eq!(g.eval_value(y)?.as_scalar()?, x0.cosh());
g.eval_deriv(y)?;
abs_diff_eq!(g.get_deriv(x)?.as_scalar()?, x0.sinh());
Ok(())
}
#[test]
fn test_sinh_cosh() -> Result<()> {
let mut g = Graph::new();
let x0: f32 = 1.234;
let x = g.scalar("x", x0)?;
let s = g.sinh(x);
let ss = g.square(s);
let c = g.cosh(x);
let cc = g.square(c);
let z = g.sub(cc, ss);
abs_diff_eq!(g.eval_value(z)?.as_scalar()?, 1.0);
g.eval_deriv(z)?;
abs_diff_eq!(g.get_deriv(x)?.as_scalar()?, 0.0);
Ok(())
}
#[test]
fn test_tanh() -> Result<()> {
let mut g = Graph::new();
let x0: f32 = 1.234;
let x = g.scalar("x", x0)?;
let t = g.tanh(x);
let s = g.sinh(x);
let c = g.cosh(x);
let tc = g.mul(t, c);
let z = g.div(tc, s);
abs_diff_eq!(g.eval_value(z)?.as_scalar()?, 1.0);
g.eval_deriv(z)?;
abs_diff_eq!(g.get_deriv(x)?.as_scalar()?, 0.0);
Ok(())
}
| true
|
02d7906a7babf9a1f04f8331a71f4d9a953b3cf0
|
Rust
|
ttiurani/automerge-rs
|
/automerge-frontend/src/value_ref/text.rs
|
UTF-8
| 927
| 2.96875
| 3
|
[
"MIT"
] |
permissive
|
use smol_str::SmolStr;
use crate::{state_tree::StateTreeText, Value};
#[derive(Clone, Debug)]
pub struct TextRef<'a> {
stt: &'a StateTreeText,
}
impl<'a> TextRef<'a> {
pub(crate) fn new(stt: &'a StateTreeText) -> Self {
Self { stt }
}
pub fn len(&self) -> usize {
self.stt.graphemes.len()
}
pub fn is_empty(&self) -> bool {
self.stt.graphemes.is_empty()
}
pub fn get(&self, index: usize) -> Option<&SmolStr> {
self.stt
.graphemes
.get(index)
.map(|(_, mg)| mg.default_grapheme())
}
pub fn iter(&self) -> impl Iterator<Item = &SmolStr> {
self.stt.graphemes.iter().map(|mg| mg.default_grapheme())
}
pub fn value(&self) -> Value {
let mut v = Vec::new();
for e in self.stt.graphemes.iter() {
v.push(e.default_grapheme().clone())
}
Value::Text(v)
}
}
| true
|
8a96a8386c8cca7cc5c74520fa099dc46cbcb896
|
Rust
|
stormzy/ecc-bp
|
/src/verification.rs
|
UTF-8
| 2,292
| 2.5625
| 3
|
[] |
no_license
|
use crate::curve::{bn_mul_mod, bn_point_add, bn_point_mul, bn_scalar_add_mod, bn_scalar_sub_mod};
use crate::error::KeyRejected;
use crate::exchange::verify_jacobian_point_is_on_the_curve;
use crate::param::CurveCtx;
use crate::public::{Point, PublicKey, BN_LENGTH};
use num_bigint::BigUint;
pub struct Signature {
r: BigUint,
s: BigUint,
}
impl Signature {
pub fn new(r: &[u8; BN_LENGTH], s: &[u8; BN_LENGTH]) -> Result<Self, KeyRejected> {
let r = BigUint::from_bytes_be(r);
let s = BigUint::from_bytes_be(s);
Ok(Signature { r, s })
}
pub fn from_scalars(r: BigUint, s: BigUint) -> Self {
Signature { r, s }
}
pub fn r(&self) -> [u8; BN_LENGTH] {
let mut r_out = [0; BN_LENGTH];
r_out.copy_from_slice(&self.r.to_bytes_be()[..BN_LENGTH]);
r_out
}
pub fn s(&self) -> [u8; BN_LENGTH] {
let mut s_out = [0; BN_LENGTH];
s_out.copy_from_slice(&self.s.to_bytes_be()[..BN_LENGTH]);
s_out
}
pub fn sm2_verify(
&self,
pk: &PublicKey,
msg: &[u8],
cctx: &CurveCtx,
) -> Result<(), KeyRejected> {
let digest = (cctx.hasher)(&pk, msg)?;
self.sm2_verify_digest(pk, &digest, cctx)
}
pub fn sm2_verify_digest(
&self,
pk: &PublicKey,
digest: &[u8],
cctx: &CurveCtx,
) -> Result<(), KeyRejected> {
let e = BigUint::from_bytes_be(digest) % &cctx.n;
let u = bn_scalar_add_mod(&self.r, &self.s, cctx);
let r = bn_scalar_sub_mod(&self.r, &e, cctx);
let g_point = bn_point_mul(&cctx.g_point, &self.s, cctx);
let p_point = bn_point_mul(&pk.to_point().to_bns(), &u, cctx);
let point = Point::new(bn_point_add(&g_point, &p_point, cctx));
verify_jacobian_point_is_on_the_curve(&point, cctx)?;
fn sig_r_equals_x(r: &BigUint, point: &Point, cctx: &CurveCtx) -> bool {
let x = point.point_x();
let z = point.point_z();
let z2 = bn_mul_mod(&z, &z, cctx);
let r_jacobian = bn_mul_mod(&z2, &r, cctx);
r_jacobian == x
}
if sig_r_equals_x(&r, &point, cctx) {
return Ok(());
}
Err(KeyRejected::verify_digest_error())
}
}
| true
|
3ede4ac901215dd36aa4be3d385dec5c21ffe51b
|
Rust
|
pbzweihander/daily-BOJ
|
/src/bin/2750.rs
|
UTF-8
| 894
| 2.96875
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"Beerware"
] |
permissive
|
extern crate daily_boj;
use std::io;
use std::io::BufRead;
use daily_boj::utils;
fn quick_sort(v: &mut [i32]) {
let len = v.len();
if len >= 2 {
let pivot_index = partition(v);
quick_sort(&mut v[0..pivot_index]);
quick_sort(&mut v[pivot_index + 1..len]);
}
}
fn partition(v: &mut [i32]) -> usize {
let len = v.len();
let pivot_index = len / 2;
v.swap(pivot_index, len - 1);
let mut store_index = 0;
for i in 0..len - 1 {
if (&v[i] < &v[len - 1]) {
v.swap(i, store_index);
store_index += 1;
}
}
v.swap(store_index, len - 1);
store_index
}
fn main() {
let count = utils::expect_i32();
let mut numbers: Vec<_> = (0..count).map(|_| { utils::expect_i32() }).collect();
quick_sort(&mut numbers);
for number in numbers.iter() {
println!("{}", number);
}
}
| true
|
834a71a1493e463762b388050efca0715193fc65
|
Rust
|
dhalf/melange
|
/src/scalar_traits.rs
|
UTF-8
| 6,643
| 3.0625
| 3
|
[] |
no_license
|
//! Defines traits that provide useful features
//! for numeric types.
//!
//! This includes identity elements.
//!
//! Relevant traits are implemented for all primitive
//! numeric types.
use num_complex::{Complex, Complex32, Complex64};
/// Defines the additive identity.
pub trait Zero {
/// Additive identity element.
const ZERO: Self;
}
macro_rules! zero_impl_float {
($($t:ty)*) => ($(
impl Zero for $t {
const ZERO: $t = 0.0;
}
)*)
}
zero_impl_float! { f64 f32 }
macro_rules! zero_impl_integer {
($($t:ty)*) => ($(
impl Zero for $t {
const ZERO: $t = 0;
}
)*)
}
zero_impl_integer! { u128 u64 u32 u16 u8 i128 i64 i32 i16 i8 }
macro_rules! zero_impl_complex {
($($t:ty)*) => ($(
impl Zero for $t {
const ZERO: $t = Complex::new(0.0, 0.0);
}
)*)
}
zero_impl_complex! { Complex64 Complex32 }
/// Defines the multiplicative identity.
pub trait One {
/// Multiplicative identity element.
const ONE: Self;
}
macro_rules! one_impl_float {
($($t:ty)*) => ($(
impl One for $t {
const ONE: $t = 1.0;
}
)*)
}
one_impl_float! { f64 f32 }
macro_rules! one_impl_integer {
($($t:ty)*) => ($(
impl One for $t {
const ONE: $t = 1;
}
)*)
}
one_impl_integer! { u128 u64 u32 u16 u8 i128 i64 i32 i16 i8 }
macro_rules! zero_impl_complex {
($($t:ty)*) => ($(
impl One for $t {
const ONE: $t = Complex::new(1.0, 0.0);
}
)*)
}
zero_impl_complex! { Complex64 Complex32 }
/// Defines the identity element of minimum operation.
pub trait Infinity {
/// Multiplicative identity element.
const INFINITY: Self;
}
macro_rules! infinity_impl_float {
($($t:ty)*) => ($(
impl Infinity for $t {
const INFINITY: $t = <$t>::INFINITY;
}
)*)
}
infinity_impl_float! { f64 f32 }
macro_rules! infinity_impl_integer {
($($t:ty)*) => ($(
impl Infinity for $t {
const INFINITY: $t = <$t>::MAX;
}
)*)
}
infinity_impl_integer! { u128 u64 u32 u16 u8 i128 i64 i32 i16 i8 }
/// Defines the identity element of minimum operation.
pub trait NegInfinity {
/// Multiplicative identity element.
const NEG_INFINITY: Self;
}
macro_rules! neg_infinity_impl_float {
($($t:ty)*) => ($(
impl NegInfinity for $t {
const NEG_INFINITY: $t = <$t>::NEG_INFINITY;
}
)*)
}
neg_infinity_impl_float! { f64 f32 }
macro_rules! neg_infinity_impl_integer {
($($t:ty)*) => ($(
impl NegInfinity for $t {
const NEG_INFINITY: $t = <$t>::MIN;
}
)*)
}
neg_infinity_impl_integer! { u128 u64 u32 u16 u8 i128 i64 i32 i16 i8 }
/// Provides a natural logarithm of 2 constant.
pub trait Ln2 {
/// Natural logarithm of 2.
const LN_2: Self;
}
impl Ln2 for f64 {
const LN_2: f64 = std::f64::consts::LN_2;
}
impl Ln2 for f32 {
const LN_2: f32 = std::f32::consts::LN_2;
}
impl Ln2 for Complex64 {
const LN_2: Complex64 = Complex::new(std::f64::consts::LN_2, 0.0);
}
impl Ln2 for Complex32 {
const LN_2: Complex32 = Complex::new(std::f32::consts::LN_2, 0.0);
}
/// Provides a natural logarithm of 10 constant.
pub trait Ln10 {
/// Natural logarithm of 10.
const LN_10: Self;
}
impl Ln10 for f64 {
const LN_10: f64 = std::f64::consts::LN_10;
}
impl Ln10 for f32 {
const LN_10: f32 = std::f32::consts::LN_10;
}
impl Ln10 for Complex64 {
const LN_10: Complex64 = Complex::new(std::f64::consts::LN_10, 0.0);
}
impl Ln10 for Complex32 {
const LN_10: Complex32 = Complex::new(std::f32::consts::LN_10, 0.0);
}
/// Provides radians/degrees conversion constants.
pub trait RadDeg {
/// Radians to degrees constant.
const RAD_TO_DEG: Self;
/// Degrees to radians constant.
const DEG_TO_RAD: Self;
}
impl RadDeg for f64 {
const RAD_TO_DEG: f64 = 180.0f64 / std::f64::consts::PI;
const DEG_TO_RAD: f64 = std::f64::consts::PI / 180.0f64;
}
impl RadDeg for f32 {
const RAD_TO_DEG: f32 = 57.2957795130823208767981548141051703_f32;
const DEG_TO_RAD: f32 = std::f32::consts::PI / 180.0f32;
}
//
/// Extends numeric cast to [`Complex`](num_complex::Complex)
/// types.
///
/// Casts from `T` to `Complex<U>` create a complex
/// number whose real portion is the cast of the `T` value
/// and whose imaginary portion is [`U::ZERO`](Zero::ZERO) from the
/// [`Zero`] trait. The cast for the real part is as exact
/// as a cast from `T` to `U` is.
///
/// Casts from `Complex<T>` to `U` drop the imaginary
/// portion and cast the real portion to `U`. The real portion
/// cast is as exact as a cast from `T` to `U` is.
///
/// Cast from `Complex<T>` to `Complex<U>` cast both
/// the real and imaginary portions. Those two casts
/// are as exact as a cast from `T` to `U` is.
pub trait Cast<U> {
/// Casts `self` as `U`.
fn as_(self) -> U;
}
macro_rules! cast_impl {
($($t:ty as $u:ty)*) => {$(
impl Cast<$u> for $t {
fn as_(self) -> $u {
self as $u
}
}
impl Cast<Complex<$u>> for $t
where
$u: Zero,
{
fn as_(self) -> Complex<$u> {
Complex::new(self as $u, <$u>::ZERO)
}
}
impl Cast<$u> for Complex<$t> {
fn as_(self) -> $u {
self.re as $u
}
}
impl Cast<Complex<$u>> for Complex<$t> {
fn as_(self) -> Complex<$u> {
Complex::new(self.re as $u, self.im as $u)
}
}
)*};
}
macro_rules! expand_right {
($callback:ident! $u:ty as $($t:ty)*) => {
$callback! { $($u as $t)* }
};
}
macro_rules! list_to_pairs {
($callback:ident! $($t:ty,)*; $u:ty; $v:ty, $($w:ty,)*) => {
expand_right! { $callback! $u as $($t)* $v $($w)* }
list_to_pairs! { $callback! $($t,)* $u,; $v; $($w,)* }
};
($callback:ident! $($t:ty,)*; $u:ty;) => {
expand_right! { $callback! $u as $($t)* }
};
($callback:ident! ;;$v:ty, $($w:ty,)*) => {
list_to_pairs! { $callback! ; $v; $($w,)* }
};
($callback:ident! $($t:ty)*) => {
list_to_pairs! {$callback! ;;$($t,)*}
};
}
list_to_pairs! { cast_impl! u128 u64 u32 u16 u8 i128 i64 i32 i16 i8 f64 f32 }
/// Marker traits for scalar types that can be used with
/// backpropagation.
pub trait Differentiable {}
macro_rules! differentiable_impl {
($($t:ty)*) => ($(
impl Differentiable for $t {}
)*)
}
differentiable_impl! { f64 f32 Complex64 Complex32 }
| true
|
e3fc8930ac67c53612a1486c3601871a62a5608b
|
Rust
|
clfs/aoc2020
|
/p04/src/main.rs
|
UTF-8
| 4,332
| 3.046875
| 3
|
[
"MIT"
] |
permissive
|
use lazy_static::lazy_static;
use regex::Regex;
use std::default::Default;
use std::io::{self, Read};
use std::str::FromStr;
lazy_static! {
static ref KEY_VAL_RE: Regex = Regex::new(r"^(?P<key>.+?):(?P<val>.+)").unwrap();
static ref HEIGHT_RE: Regex = Regex::new(r"^(?P<magnitude>\d+)(?P<unit>cm|in)$").unwrap();
static ref HAIR_COLOR_RE: Regex = Regex::new(r"^#[a-f0-9]{6}$").unwrap();
static ref EYE_COLOR_RE: Regex = Regex::new(r"^(amb|blu|brn|gry|grn|hzl|oth)$").unwrap();
static ref PASSPORT_ID_RE: Regex = Regex::new(r"^\d{9}$").unwrap();
}
#[derive(Default, Debug)]
struct Passport {
birth_year: Option<u32>,
issue_year: Option<u32>,
expiry_year: Option<u32>,
height: Option<Height>,
hair_color: Option<String>,
eye_color: Option<String>,
passport_id: Option<String>,
}
#[derive(Debug)]
enum Height {
Cm(u32),
In(u32),
}
impl FromStr for Height {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let captures = HEIGHT_RE
.captures(s)
.ok_or_else(|| format!("invalid height {}", s))?;
let magnitude = captures
.name("magnitude")
.ok_or_else(|| "no magnitude found")?
.as_str()
.parse::<u32>()
.unwrap(); // lol
let unit = captures
.name("unit")
.ok_or_else(|| "no unit found")?
.as_str();
match unit {
"cm" => Ok(Height::Cm(magnitude)),
"in" => Ok(Height::In(magnitude)),
_ => Err(format!("invalid unit {}", unit)),
}
}
}
impl FromStr for Passport {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut passport = Passport::default();
for field in s.split_whitespace() {
let captures = KEY_VAL_RE
.captures(field)
.ok_or_else(|| format!("invalid field {}", field))?;
let key = captures.name("key").ok_or_else(|| "no key found")?.as_str();
let val = captures.name("val").ok_or_else(|| "no val found")?.as_str();
match key {
"byr" => passport.birth_year = val.parse().ok(),
"iyr" => passport.issue_year = val.parse().ok(),
"eyr" => passport.expiry_year = val.parse().ok(),
"hgt" => passport.height = val.parse().ok(),
"hcl" => passport.hair_color = Some(val.to_string()),
"ecl" => passport.eye_color = Some(val.to_string()),
"pid" => passport.passport_id = Some(val.to_string()),
_ => (),
}
}
Ok(passport)
}
}
impl Passport {
fn is_valid_inner(&self) -> Option<bool> {
let valid = (1920..=2002).contains(&self.birth_year?)
&& (2010..=2020).contains(&self.issue_year?)
&& (2020..=2030).contains(&self.expiry_year?)
&& match &self.height.as_ref()? {
Height::Cm(v) => (150..=193).contains(v),
Height::In(v) => (59..=76).contains(v),
}
&& HAIR_COLOR_RE.is_match(&self.hair_color.as_ref()?)
&& EYE_COLOR_RE.is_match(&self.eye_color.as_ref()?)
&& PASSPORT_ID_RE.is_match(&self.passport_id.as_ref()?);
Some(valid)
}
fn is_valid(&self) -> bool {
match self.is_valid_inner() {
Some(v) => v,
None => false,
}
}
}
fn main() -> Result<(), io::Error> {
let mut input = String::new();
io::stdin().read_to_string(&mut input)?;
let passports = parse(&input);
println!("part 1: {}", part1(&input));
println!("part 2: {}", part2(&passports));
Ok(())
}
fn parse(input: &str) -> Vec<Passport> {
return input.split("\n\n").filter_map(|x| x.parse().ok()).collect();
}
fn part1(input: &str) -> i32 {
let mut n = 0;
let required = vec!["byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid"];
for p in input.split("\n\n") {
let mut x = 0;
for r in &required {
if p.contains(r) {
x += 1;
}
}
if x == required.len() {
n += 1;
}
}
n
}
fn part2(passports: &Vec<Passport>) -> usize {
return passports.iter().filter(|x| x.is_valid()).count();
}
| true
|
7c8b9df041ae366d3582d19f9d60f0f6396b7e0f
|
Rust
|
jakobkmar/whale-warden-rs
|
/src/service.rs
|
UTF-8
| 659
| 2.65625
| 3
|
[] |
no_license
|
use std::convert::Infallible;
use std::env;
use hyper::{Body, Method, Request, Response, StatusCode};
use lazy_static::lazy_static;
lazy_static! {
static ref WEBHOOK_NAME: String = env::var("WEBHOOK_NAME").unwrap_or("/default".into());
}
pub async fn hello_world(req: Request<Body>) -> Result<Response<Body>, Infallible> {
match (req.method(), req.uri().path()) {
(&Method::GET, path) if path == *WEBHOOK_NAME =>
Ok(Response::new("Hello world".into())),
_ => {
let mut not_found = Response::default();
*not_found.status_mut() = StatusCode::NOT_FOUND;
Ok(not_found)
}
}
}
| true
|
46646c9bdb5f7ad969555fd6abaffa642d218451
|
Rust
|
pietroalbini/handlebars-fluent
|
/src/loader.rs
|
UTF-8
| 9,201
| 2.9375
| 3
|
[
"MIT",
"Apache-2.0"
] |
permissive
|
use std::collections::HashMap;
use std::fs::read_dir;
use std::fs::File;
use std::io;
use std::io::prelude::*;
use std::path::Path;
use fluent_bundle::{FluentBundle, FluentResource, FluentValue};
use fluent_locale::negotiate_languages;
/// Something capable of looking up Fluent keys fiven a language
///
/// Use [SimpleLoader] if you just need the basics
pub trait Loader {
fn lookup(
&self,
lang: &str,
text_id: &str,
args: Option<&HashMap<&str, FluentValue>>,
) -> String;
}
/// Loads Fluent data at runtime via `lazy_static` to produce a loader.
///
/// Usage:
///
/// ```rust
/// use handlebars_fluent::*;
///
/// simple_loader!(create_loader, "./tests/locales/", "en-US");
///
/// fn init() {
/// let loader = create_loader();
/// let helper = FluentHelper::new(loader);
/// }
/// ```
///
/// `$constructor` is the name of the constructor function for the loader, `$location` is
/// the location of a folder containing individual locale folders, `$fallback` is the language to use
/// for fallback strings.
///
/// Some Fluent users have a share "core.ftl" file that contains strings used by all locales,
/// for example branding information. They also may want to define custom functions on the bundle.
///
/// This can be done with an extended invocation:
///
/// ```rust
/// use handlebars_fluent::*;
///
/// simple_loader!(create_loader, "./tests/locales/", "en-US", core: "./tests/core.ftl",
/// customizer: |bundle| {bundle.add_function("FOOBAR", |_values, _named| {unimplemented!()}); });
///
/// fn init() {
/// let loader = create_loader();
/// let helper = FluentHelper::new(loader);
/// }
/// ```
///
/// The constructor function is cheap to call multiple times since all the heavy duty stuff is stored in shared statics.
///
#[macro_export]
macro_rules! simple_loader {
($constructor:ident, $location:expr, $fallback:expr) => {
$crate::lazy_static::lazy_static! {
static ref RESOURCES: std::collections::HashMap<String, Vec<$crate::fluent_bundle::FluentResource>> = $crate::loader::build_resources($location);
static ref BUNDLES: std::collections::HashMap<String, $crate::fluent_bundle::FluentBundle<'static>> = $crate::loader::build_bundles(&&RESOURCES, None, |_bundle| {});
static ref LOCALES: Vec<&'static str> = RESOURCES.iter().map(|(l, _)| &**l).collect();
static ref FALLBACKS: std::collections::HashMap<String, Vec<String>> = $crate::loader::build_fallbacks(&LOCALES);
}
pub fn $constructor() -> $crate::loader::SimpleLoader {
$crate::loader::SimpleLoader::new(&*BUNDLES, &*FALLBACKS, $fallback.into())
}
};
($constructor:ident, $location:expr, $fallback:expr, core: $core:expr, customizer: $custom:expr) => {
$crate::lazy_static::lazy_static! {
static ref CORE_RESOURCE: $crate::fluent_bundle::FluentResource = $crate::loader::load_core_resource($core);
static ref RESOURCES: std::collections::HashMap<String, Vec<$crate::fluent_bundle::FluentResource>> = $crate::loader::build_resources($location);
static ref BUNDLES: std::collections::HashMap<String, $crate::fluent_bundle::FluentBundle<'static>> = $crate::loader::build_bundles(&*RESOURCES, Some(&CORE_RESOURCE), $custom);
static ref LOCALES: Vec<&'static str> = RESOURCES.iter().map(|(l, _)| &**l).collect();
static ref FALLBACKS: std::collections::HashMap<String, Vec<String>> = $crate::loader::build_fallbacks(&LOCALES);
}
pub fn $constructor() -> $crate::loader::SimpleLoader {
$crate::loader::SimpleLoader::new(&*BUNDLES, &*FALLBACKS, $fallback.into())
}
};
}
pub fn build_fallbacks(locales: &[&str]) -> HashMap<String, Vec<String>> {
locales
.iter()
.map(|locale| {
(
locale.to_string(),
negotiate_languages(
&[locale],
&locales,
None,
&fluent_locale::NegotiationStrategy::Filtering,
)
.into_iter()
.map(|x| x.to_string())
.collect(),
)
})
.collect()
}
/// A simple Loader implementation, with statically-loaded fluent data.
/// Typically created with the [`simple_loader!()`] macro
pub struct SimpleLoader {
bundles: &'static HashMap<String, FluentBundle<'static>>,
fallbacks: &'static HashMap<String, Vec<String>>,
fallback: String,
}
impl SimpleLoader {
/// Construct a SimpleLoader
///
/// You should probably be using the constructor from `simple_loader!()`
pub fn new(
bundles: &'static HashMap<String, FluentBundle<'static>>,
fallbacks: &'static HashMap<String, Vec<String>>,
fallback: String,
) -> Self {
Self {
bundles,
fallbacks,
fallback,
}
}
/// Convenience function to look up a string for a single language
pub fn lookup_single_language(
&self,
lang: &str,
text_id: &str,
args: Option<&HashMap<&str, FluentValue>>,
) -> Option<String> {
if let Some(bundle) = self.bundles.get(lang) {
if bundle.has_message(text_id) {
let (value, _errors) = bundle.format(text_id, args).unwrap_or_else(|| {
panic!(
"Failed to format a message for locale {} and id {}",
lang, text_id
)
});
Some(value)
} else {
None
}
} else {
panic!("Unknown language {}", lang)
}
}
/// Convenience function to look up a string without falling back to the default fallback language
pub fn lookup_no_default_fallback(
&self,
lang: &str,
text_id: &str,
args: Option<&HashMap<&str, FluentValue>>,
) -> Option<String> {
for l in self.fallbacks.get(lang).expect("language not found") {
if let Some(val) = self.lookup_single_language(l, text_id, args) {
return Some(val);
}
}
None
}
}
impl Loader for SimpleLoader {
// Traverse the fallback chain,
fn lookup(
&self,
lang: &str,
text_id: &str,
args: Option<&HashMap<&str, FluentValue>>,
) -> String {
for l in self.fallbacks.get(lang).expect("language not found") {
if let Some(val) = self.lookup_single_language(l, text_id, args) {
return val;
}
}
if lang != self.fallback {
if let Some(val) = self.lookup_single_language(&self.fallback, text_id, args) {
return val;
}
}
format!("Unknown localization {}", text_id)
}
}
fn read_from_file<P: AsRef<Path>>(filename: P) -> io::Result<FluentResource> {
let mut file = File::open(filename)?;
let mut string = String::new();
file.read_to_string(&mut string)?;
Ok(FluentResource::try_new(string).expect("File did not parse!"))
}
fn read_from_dir<P: AsRef<Path>>(dirname: P) -> io::Result<Vec<FluentResource>> {
let mut result = Vec::new();
for dir_entry in read_dir(dirname)? {
let entry = dir_entry?;
let resource = read_from_file(entry.path())?;
result.push(resource);
}
Ok(result)
}
pub fn create_bundle(
lang: &str,
resources: &'static Vec<FluentResource>,
core_resource: Option<&'static FluentResource>,
customizer: &impl Fn(&mut FluentBundle<'static>),
) -> FluentBundle<'static> {
let mut bundle = FluentBundle::new(&[lang]);
if let Some(core) = core_resource {
bundle
.add_resource(core)
.expect("Failed to add core resource to bundle");
}
for res in resources {
bundle
.add_resource(res)
.expect("Failed to add FTL resources to the bundle.");
}
customizer(&mut bundle);
bundle
}
pub fn build_resources(dir: &str) -> HashMap<String, Vec<FluentResource>> {
let mut all_resources = HashMap::new();
let entries = read_dir(dir).unwrap();
for entry in entries {
let entry = entry.unwrap();
if entry.file_type().unwrap().is_dir() {
if let Ok(lang) = entry.file_name().into_string() {
let resources = read_from_dir(entry.path()).unwrap();
all_resources.insert(lang, resources);
}
}
}
all_resources
}
pub fn build_bundles(
resources: &'static HashMap<String, Vec<FluentResource>>,
core_resource: Option<&'static FluentResource>,
customizer: impl Fn(&mut FluentBundle<'static>),
) -> HashMap<String, FluentBundle<'static>> {
let mut bundles = HashMap::new();
for (ref k, ref v) in &*resources {
bundles.insert(
k.to_string(),
create_bundle(&k, &v, core_resource, &customizer),
);
}
bundles
}
pub fn load_core_resource(path: &str) -> FluentResource {
read_from_file(path).expect("cannot find core resource")
}
| true
|
9a7a693f89aaccb0af5bdd8b6e7ac6edd9625a8b
|
Rust
|
fede1024/rust-rdkafka
|
/rdkafka-sys/simple_producer.rs
|
UTF-8
| 2,907
| 2.59375
| 3
|
[
"MIT"
] |
permissive
|
use std::time::Duration;
use clap::{App, Arg};
use log::info;
use rdkafka::config::ClientConfig;
use rdkafka::message::OwnedHeaders;
use rdkafka::producer::{FutureProducer, FutureRecord};
use rdkafka::util::get_rdkafka_version;
use crate::example_utils::setup_logger;
mod example_utils;
async fn produce(brokers: &str, topic_name: &str) {
let producer: &FutureProducer = &ClientConfig::new()
.set("bootstrap.servers", brokers)
.set("message.timeout.ms", "5000")
.create()
.expect("Producer creation error");
// This loop is non blocking: all messages will be sent one after the other, without waiting
// for the results.
let futures = (0..5)
.map(|i| async move {
// The send operation on the topic returns a future, which will be
// completed once the result or failure from Kafka is received.
let delivery_status = producer
.send(
FutureRecord::to(topic_name)
.payload(&format!("Message {}", i))
.key(&format!("Key {}", i))
.headers(OwnedHeaders::new().add("header_key", "header_value")),
Duration::from_secs(0),
)
.await;
// This will be executed when the result is received.
info!("Delivery status for message {} received", i);
delivery_status
})
.collect::<Vec<_>>();
// This loop will wait until all delivery statuses have been received.
for future in futures {
info!("Future completed. Result: {:?}", future.await);
}
}
#[tokio::main]
async fn main() {
let matches = App::new("producer example")
.version(option_env!("CARGO_PKG_VERSION").unwrap_or(""))
.about("Simple command line producer")
.arg(
Arg::with_name("brokers")
.short("b")
.long("brokers")
.help("Broker list in kafka format")
.takes_value(true)
.default_value("localhost:9092"),
)
.arg(
Arg::with_name("log-conf")
.long("log-conf")
.help("Configure the logging format (example: 'rdkafka=trace')")
.takes_value(true),
)
.arg(
Arg::with_name("topic")
.short("t")
.long("topic")
.help("Destination topic")
.takes_value(true)
.required(true),
)
.get_matches();
setup_logger(true, matches.value_of("log-conf"));
let (version_n, version_s) = get_rdkafka_version();
info!("rd_kafka_version: 0x{:08x}, {}", version_n, version_s);
let topic = matches.value_of("topic").unwrap();
let brokers = matches.value_of("brokers").unwrap();
produce(brokers, topic).await;
}
| true
|
ff47f4e3f350d836737a4194ca0921b621dba63e
|
Rust
|
petersgrandadventure/devcamp8-tragedy-of-commons
|
/zome/zomes/tragedy_of_commons/src/player_profile.rs
|
UTF-8
| 3,595
| 3.0625
| 3
|
[
"CC-BY-SA-4.0",
"CAL-1.0-Combined-Work-Exception",
"CAL-1.0",
"LicenseRef-scancode-free-unknown"
] |
permissive
|
use crate::game_code::get_game_code_anchor;
use hdk::prelude::*;
pub const PLAYER_LINK_TAG: &str = "PLAYER";
/// Actual Holochain entry that stores user's profile
/// for the specific game
#[hdk_entry(id = "player_profile", visibility = "public")]
#[derive(Clone)]
pub struct PlayerProfile {
pub player_id: AgentPubKey,
pub nickname: String,
}
/// Struct to receive user input from the UI when user
/// wants to join the game
#[derive(Clone, Debug, Serialize, Deserialize, SerializedBytes)]
pub struct JoinGameInfo {
pub gamecode: String,
pub nickname: String,
}
/// Creates a PlayerProfile instance, commits it as a Holochain entry
/// and returns a hash value of this entry
pub fn create_and_hash_entry_player_profile(nickname: String) -> ExternResult<EntryHash> {
let agent = agent_info()?;
debug!(
"create_and_hash_entry_player_profile | nickname: {}, agent {:?}",
nickname,
agent.clone()
);
let player_profile = PlayerProfile {
player_id: agent.agent_initial_pubkey, // bad design for real apps 1/ initial_pubkey is linked to app itself, so no roaming profile 2/ lost if app is reinstalled (= basicly new user)
nickname,
};
create_entry(&player_profile)?;
debug!("create_and_hash_entry_player_profile | profile created, hashing");
hash_entry(&player_profile)
}
/// Creates user's profile for the game and registers this user as one of the game players
pub fn join_game_with_code(input: JoinGameInfo) -> ExternResult<EntryHash> {
info!("join_game_with_code | input: {:?}", input);
let anchor = get_game_code_anchor(input.gamecode)?;
debug!("join_game_with_code | anchor created {:?}", &anchor);
let player_profile_entry_hash = create_and_hash_entry_player_profile(input.nickname)?;
debug!(
"join_game_with_code | profile entry hash {:?}",
&player_profile_entry_hash
);
create_link(
anchor.clone().into(),
player_profile_entry_hash.into(),
LinkTag::new(String::from(PLAYER_LINK_TAG)),
)?;
debug!("join_game_with_code | link created");
Ok(anchor) // or more Rust like: anchor.into())
}
pub fn get_player_profiles_for_game_code(
short_unique_code: String,
) -> ExternResult<Vec<PlayerProfile>> {
let anchor = get_game_code_anchor(short_unique_code)?;
debug!("anchor: {:?}", anchor);
let links: Links = get_links(anchor, Some(LinkTag::new(String::from(PLAYER_LINK_TAG))))?;
debug!("links: {:?}", links);
let mut players = vec![];
for link in links.into_inner() {
debug!("link: {:?}", link);
let element: Element = get(link.target, GetOptions::default())?
.ok_or(WasmError::Guest(String::from("Entry not found")))?;
let entry_option = element.entry().to_app_option()?;
let entry: PlayerProfile = entry_option.ok_or(WasmError::Guest(
"The targeted entry is not agent pubkey".into(),
))?;
players.push(entry);
}
Ok(players) // or more Rust like: anchor.into())
}
pub fn get_players_for_game_code(short_unique_code: String) -> ExternResult<Vec<PlayerProfile>> {
// Ok(vec!["Anipur".into(), "Bob".into()]);
debug!("get profiles");
let player_profiles = get_player_profiles_for_game_code(short_unique_code)?;
// debug!("filter profiles to extract nickname");
let players: Vec<String> = player_profiles.iter().map(|x| x.nickname.clone()).collect();
debug!("players: {:?}", players);
debug!("profiles {:?}", player_profiles);
Ok(player_profiles) // or more Rust like: anchor.into())
}
| true
|
cb7d3a4fa47363e708d408d3b7d72fb8f813f3cd
|
Rust
|
sigds/ticky
|
/src/data_handler/quote_handler.rs
|
UTF-8
| 1,149
| 2.625
| 3
|
[] |
no_license
|
use super::AssetHandler;
///! Data handler trait for market quotes
use super::DataError;
use crate::quote::{Quote, Ticker};
use chrono::{DateTime, Utc};
/// Handler for globally available market quotes data
pub trait QuoteHandler: AssetHandler {
fn get_ticker_by_name(&mut self, name: &str) -> Result<Ticker, DataError>;
fn get_latest_quote(&mut self, ticker_name: &str) -> Option<Quote>;
fn get_oldest_quote(&mut self, ticker_name: &str) -> Option<Quote>;
fn insert_ticker(&mut self, ticker: &Ticker) -> Result<(), DataError>;
fn update_ticker(&mut self, ticker: &Ticker) -> Result<(), DataError>;
fn delete_ticker(&mut self, ticker: &Ticker) -> Result<(), DataError>;
fn insert_quote(&mut self, quote: &Quote) -> Result<(), DataError>;
fn update_quote(&mut self, quote: &Quote) -> Result<(), DataError>;
fn delete_quote(&mut self, quote: &Quote) -> Result<(), DataError>;
fn quote_cursor_forward(&mut self, ticker: &Ticker, time: DateTime<Utc>) -> Box<dyn Iterator<Item=Quote> + '_>;
fn quote_cursor_reverse(&mut self, ticker: &Ticker, time: DateTime<Utc>) -> Box<dyn Iterator<Item=Quote> + '_>;
}
| true
|
e3ab9fcfc4eeab86b0a79828814f952ffc38978b
|
Rust
|
hgzimmerman/HLWNPA
|
/src/parser/mod.rs
|
UTF-8
| 8,773
| 2.765625
| 3
|
[] |
no_license
|
use ast::{Ast};
#[allow(unused_imports)]
use nom::*;
mod operators;
mod expressions;
use self::expressions::sexpr;
mod identifier;
mod literal;
mod utilities;
mod assignment;
use self::assignment::*;
mod type_signature;
mod function;
use self::function::*;
mod body;
mod control_flow;
use self::control_flow::control_flow;
mod structure;
use self::structure::{struct_definition, create_struct_instance};
mod include;
use self::include::include;
///Anything that generates an AST node.
named!(any_ast<Ast>,
alt_complete!(
sexpr | // works as a stand in for tokens groups captured no_keyword_token_group
include |
declaration |
control_flow |
struct_definition |
create_struct_instance |
function
) // Order is very important here
);
named!(pub program<Ast>,
do_parse!(
e: many1!(ws!(any_ast)) >>
(Ast::ExpressionList( e ))
)
);
#[cfg(test)]
mod test {
use super::*;
use testing::test_constants::SIMPLE_PROGRAM_INPUT_1;
use nom::IResult;
use test::Bencher;
use ast::{Datatype, TypeInfo};
use preprocessor::preprocess;
use std::boxed::Box;
use s_expression::SExpression;
/// assign the value 7 to x
/// create a function that takes a number
/// call the function with x
#[test]
fn parse_simple_program_and_validate_ast_test() {
let (_, value) = match program(SIMPLE_PROGRAM_INPUT_1.as_bytes()) {
IResult::Done(rest, v) => (rest, v),
IResult::Error(e) => panic!("{}", e),
_ => panic!(),
};
let expected_assignment: Ast = Ast::SExpr(SExpression::VariableDeclaration {
identifier: Box::new(Ast::ValueIdentifier("x".to_string())),
ast: Box::new(Ast::SExpr(SExpression::Add(
Box::new(Ast::Literal(Datatype::Number(3))),
Box::new(Ast::Literal(Datatype::Number(4))),
))),
});
let expected_fn: Ast = Ast::SExpr(SExpression::DeclareFunction {
identifier: Box::new(Ast::ValueIdentifier("test_function".to_string())),
function_datatype: Box::new(Ast::Literal(Datatype::Function {
parameters: Box::new(Ast::ExpressionList (
vec![Ast::SExpr(SExpression::TypeAssignment {
identifier: Box::new(Ast::ValueIdentifier("a".to_string())),
type_info: Box::new(Ast::Type(TypeInfo::Number))
})],
)),
body: Box::new(Ast::ExpressionList(vec![
Ast::SExpr(
SExpression::Add(
Box::new(Ast::ValueIdentifier ( "a".to_string() )),
Box::new(Ast::Literal ( Datatype::Number(8))),
)
)
])),
return_type: TypeInfo::Number,
})),
});
let expected_fn_call: Ast = Ast::SExpr(SExpression::ExecuteFn {
identifier: Box::new(Ast::ValueIdentifier("test_function".to_string())),
parameters: Box::new(Ast::ExpressionList(
vec![Ast::ValueIdentifier("x".to_string())],
)),
});
let expected_program_ast: Ast = Ast::ExpressionList(vec![
expected_assignment,
expected_fn,
expected_fn_call
]);
assert_eq!(expected_program_ast, value)
}
#[bench]
fn parse_simple_program_bench(b: &mut Bencher) {
fn parse_simple_program() {
let (_, _) = match program(SIMPLE_PROGRAM_INPUT_1.as_bytes()) {
IResult::Done(rest, v) => (rest, v),
IResult::Error(e) => panic!("{}", e),
_ => panic!(),
};
}
b.iter(|| parse_simple_program());
}
#[bench]
fn preprocess_and_parse_simple_program_bench(b: &mut Bencher) {
fn parse_simple_program() {
let preprocessed = preprocess(SIMPLE_PROGRAM_INPUT_1);
let (_, _) = match program(preprocessed.as_bytes()) {
IResult::Done(rest, v) => (rest, v),
IResult::Error(e) => panic!("{}", e),
_ => panic!(),
};
}
b.iter(|| parse_simple_program());
}
#[test]
fn parse_program_with_only_identifier_test() {
let input_string = "x";
let (_, value) = match program(input_string.as_bytes()) {
IResult::Done(rest, v) => (rest, v),
IResult::Error(e) => panic!("Error in parsing: {}", e),
IResult::Incomplete(i) => panic!("Incomplete parse: {:?}", i),
};
assert_eq!(Ast::ExpressionList ( vec![Ast::ValueIdentifier("x".to_string())] ), value)
}
#[test]
fn parse_program_with_if_test() {
let input_string = "if true { true } else { true }";
let (_, value) = match program(input_string.as_bytes()) {
IResult::Done(rest, v) => (rest, v),
IResult::Error(e) => panic!("Error in parsing: {}", e),
IResult::Incomplete(i) => panic!("Incomplete parse: {:?}", i),
};
assert_eq!(Ast::ExpressionList (
vec![Ast::Conditional {
condition: Box::new(Ast::Literal(Datatype::Bool(true))),
true_expr: Box::new(Ast::ExpressionList(vec![Ast::Literal(Datatype::Bool(true))])),
false_expr: Some(Box::new(Ast::ExpressionList(vec![Ast::Literal(Datatype::Bool(true))])))
}]
), value)
}
#[test]
fn parse_program_with_array_assignment() {
let input_string = r##"
let myArray := [8, 3]
"##;
let (_, _) = match program(input_string.as_bytes()) {
IResult::Done(rest, v) => (rest, v),
IResult::Error(e) => panic!("Error in parsing: {}", e),
IResult::Incomplete(i) => panic!("Incomplete parse: {:?}", i),
};
}
#[test]
fn parse_program_with_array_access() {
let input_string = r##"
let value_in_array := existing_array[8]
"##;
let (_, _) = match program(input_string.as_bytes()) {
IResult::Done(rest, v) => (rest, v),
IResult::Error(e) => panic!("Error in parsing: {}", e),
IResult::Incomplete(i) => panic!("Incomplete parse: {:?}", i),
};
}
#[test]
fn parse_program_with_struct_definition() {
let input_string = r##"struct MyStruct {
a : Number
}
"##;
let (_, _) = match program(input_string.as_bytes()) {
IResult::Done(rest, v) => (rest, v),
IResult::Error(e) => panic!("Error in parsing: {}", e),
IResult::Incomplete(i) => panic!("Incomplete parse: {:?}", i),
};
}
#[test]
fn parse_program_with_struct_creation() {
let input_string = r##"new MyStruct {
a : 8
}
"##;
let (_, _) = match program(input_string.as_bytes()) {
IResult::Done(rest, v) => (rest, v),
IResult::Error(e) => panic!("Error in parsing: {}", e),
IResult::Incomplete(i) => panic!("Incomplete parse: {:?}", i),
};
}
#[test]
fn parse_program_with_struct_instance_creation_and_assignment() {
let input_string = r##"let instance := new MyStruct {
a : 8
}
"##;
let (_, _) = match program(input_string.as_bytes()) {
IResult::Done(rest, v) => (rest, v),
IResult::Error(e) => panic!("Error in parsing: {}", e),
IResult::Incomplete(i) => panic!("Incomplete parse: {:?}", i),
};
}
#[test]
fn parse_program_with_struct_access_and_assignment() {
let input_string = r##"
let outside_value := myStructInstance.field
"##;
let (_, _) = match program(input_string.as_bytes()) {
IResult::Done(rest, v) => (rest, v),
IResult::Error(e) => panic!("Error in parsing: {}", e),
IResult::Incomplete(i) => panic!("Incomplete parse: {:?}", i),
};
}
#[test]
fn verify_program_with_escapes_in_strings() {
let input_string = "
\"\nHello\nWorld\n\"
";
let (_, ast) = match program(input_string.as_bytes()) {
IResult::Done(rest, v) => (rest, v),
IResult::Error(e) => panic!("Error in parsing: {}", e),
IResult::Incomplete(i) => panic!("Incomplete parse: {:?}", i),
};
assert_eq!(Ast::ExpressionList (
vec![
Ast::Literal(Datatype::String("\nHello\nWorld\n".to_string()))
]
), ast)
}
}
| true
|
1d9a1077418d80d55e6b3e6969f3d164a355ded3
|
Rust
|
Kixiron/sruth
|
/src/repr/constant.rs
|
UTF-8
| 1,496
| 2.796875
| 3
|
[
"MIT",
"Apache-2.0"
] |
permissive
|
use crate::repr::{
utils::{DisplayCtx, IRDisplay},
Type,
};
use abomonation_derive::Abomonation;
use lasso::Resolver;
use pretty::{DocAllocator, DocBuilder};
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Abomonation)]
pub enum Constant {
Bool(bool),
Int(i64),
Uint(u64),
}
impl Constant {
pub const fn as_bool(&self) -> Option<bool> {
if let Self::Bool(bool) = *self {
Some(bool)
} else {
None
}
}
pub fn ty(&self) -> Type {
match self {
Self::Bool(_) => Type::Bool,
Self::Int(_) => Type::Int,
Self::Uint(_) => Type::Uint,
}
}
pub const fn is_zero(&self) -> bool {
match *self {
Self::Int(int) if int == 0 => true,
Self::Uint(uint) if uint == 0 => true,
Self::Bool(_) | Self::Int(_) | Self::Uint(_) => false,
}
}
pub const fn is_signed_int(&self) -> bool {
matches!(self, Self::Int(_))
}
}
impl IRDisplay for Constant {
fn display<'a, D, A, R>(&self, alloc: DisplayCtx<'a, D, A, R>) -> DocBuilder<'a, D, A>
where
D: DocAllocator<'a, A>,
D::Doc: Clone,
A: Clone + 'a,
R: Resolver,
{
match self {
Self::Bool(boolean) => alloc.text(format!("{}", boolean)),
Self::Int(int) => alloc.text(format!("{}", int)),
Self::Uint(uint) => alloc.text(format!("{}", uint)),
}
}
}
| true
|
28b074f83ad920d44c52f7cd60f9aecf3c1a7d93
|
Rust
|
sjoshid/exercism
|
/rust/ocr-numbers/src/lib.rs
|
UTF-8
| 2,166
| 3.40625
| 3
|
[] |
no_license
|
// The code below is a stub. Just enough to satisfy the compiler.
// In order to pass the tests you can add-to or change any of this code.
#[derive(Debug, PartialEq)]
pub enum Error {
InvalidRowCount(usize),
InvalidColumnCount(usize),
}
pub fn convert(input: &str) -> Result<String, Error> {
let mut lines = input.split("\n").collect::<Vec<&str>>();
let mut results = Vec::new();
for line in lines.chunks(4) {
let mut digits_on_same_line = String::new();
if line.len() % 4 != 0 {
return Err(Error::InvalidRowCount(line.len()));
} else if !(line[0].len() == line[1].len() && line[1].len() == line[2].len() && line[2].len() == line[3].len())
|| (line[0].len() % 3 != 0)
|| (line[1].len() % 3 != 0)
|| (line[2].len() % 3 != 0)
|| (line[3].len() % 3 != 0)
{
return Err(Error::InvalidColumnCount(line[0].len()));
} else {
for i in (0..line[0].len()).step_by(3) {
let current = *line.get(0).unwrap(); // row 1
let f = ¤t[i..(i+3)];
let current = *line.get(1).unwrap(); // row 2
let s = ¤t[i..(i+3)];
let current = *line.get(2).unwrap(); // row 3
let t = ¤t[i..(i+3)];
let current = *line.get(3).unwrap(); // row 4
let l = ¤t[i..(i+3)];
let string_to_check = f.to_owned() + s + t + l;
let parsed = check_for_digit(string_to_check.as_str());
digits_on_same_line += parsed;
}
results.push(digits_on_same_line);
}
}
return Ok(results.join(","));
}
fn check_for_digit(check_for_digit: &str) -> &str {
let digit = match check_for_digit {
" _ | ||_| " => "0",
" | | " => "1",
" _ _||_ " => "2",
" _ _| _| " => "3",
" |_| | " => "4",
" _ |_ _| " => "5",
" _ |_ |_| " => "6",
" _ | | " => "7",
" _ |_||_| " => "8",
" _ |_| _| " => "9",
_ => "?",
};
digit
}
| true
|
d70474ccc4d376a051d26598229d538de4a5ac4c
|
Rust
|
vain0x/languages
|
/picomet-lang/compiler/src/app/main.rs
|
UTF-8
| 2,919
| 3.09375
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] |
permissive
|
use crate::app;
use crate::lsp;
use std::env::ArgsOs;
use std::path::PathBuf;
enum Arg {
Help,
Version,
Run {
picomet_file_path: PathBuf,
},
GenRust {
picomet_file_path: PathBuf,
runtime_file_path: PathBuf,
out_file_path: PathBuf,
},
Lsp,
}
fn get_version() -> &'static str {
env!("CARGO_PKG_VERSION")
}
fn get_help() -> String {
format!(
r#"picomet {version}
USAGE:
picomet [OPTIONS] [SUBCOMMAND]
SUBCOMMAND:
run [PICOMET_FILE_PATH]
Run Picomet code
gen_rust [PICOMET_FILE] [RUNTIME_FILE] [OUT_FILE]
Bundle Picomet code and Runtime
to single Rust code
lsp
Start LSP server
OPTIONS:
-h, --help Print help
-V, --version Print Version"#,
version = get_version()
)
}
fn exit_with_version() -> ! {
eprintln!("{}", get_version());
std::process::exit(1)
}
fn exit_with_help() -> ! {
eprintln!("{}", get_help());
std::process::exit(1)
}
fn parse_args(args: ArgsOs) -> Result<Arg, String> {
let argc = args.len();
let mut args = args.into_iter();
let verb = match args.next() {
None => return Ok(Arg::Help),
Some(verb) => verb,
};
match verb.into_string().unwrap().as_str() {
"-h" | "--help" | "help" => Ok(Arg::Help),
"-V" | "--version" | "version" => Ok(Arg::Version),
"run" => {
if argc < 2 {
return Err("run: Missing some parameter.".to_string());
}
Ok(Arg::Run {
picomet_file_path: PathBuf::from(args.next().unwrap()),
})
}
"gen_rust" => {
if argc < 4 {
return Err("gen_rust: Missing some parameter.".to_string());
}
Ok(Arg::GenRust {
picomet_file_path: PathBuf::from(args.next().unwrap()),
runtime_file_path: PathBuf::from(args.next().unwrap()),
out_file_path: PathBuf::from(args.next().unwrap()),
})
}
"lsp" => Ok(Arg::Lsp),
verb => Err(format!("Unknown subcommand '{}'.", verb)),
}
}
fn switch_on_args(mut args: ArgsOs) {
// Skip self path.
args.next();
let arg = parse_args(args).unwrap_or_else(|err| {
eprintln!("{}", err);
exit_with_help();
});
match arg {
Arg::Version => exit_with_version(),
Arg::Help => exit_with_help(),
Arg::Run { picomet_file_path } => app::run::run(picomet_file_path),
Arg::GenRust {
picomet_file_path,
runtime_file_path,
out_file_path,
} => {
app::gen_rust::gen_rust_to_file(&picomet_file_path, &runtime_file_path, &out_file_path)
.unwrap()
}
Arg::Lsp => lsp::lsp_main::start_lsp_server(),
}
}
pub fn main() {
switch_on_args(std::env::args_os())
}
| true
|
143facfa8b95b1320c54dbcbd103b21f51efab3e
|
Rust
|
thfm/scholar
|
/src/utils.rs
|
UTF-8
| 626
| 3.109375
| 3
|
[
"MIT"
] |
permissive
|
use nalgebra::DMatrix;
use rand::distributions::{Distribution, Uniform};
/// Generates a matrix with the specified dimensions and random values between -1 and 1.
pub(crate) fn gen_random_matrix(rows: usize, cols: usize) -> DMatrix<f64> {
let elements = rows * cols;
let range = Uniform::new_inclusive(-1.0, 1.0);
DMatrix::from_iterator(
rows,
cols,
(0..elements).map(|_| range.sample(&mut rand::thread_rng())),
)
}
/// Converts a slice to a one-column matrix.
pub(crate) fn convert_slice_to_matrix(slice: &[f64]) -> DMatrix<f64> {
DMatrix::from_row_slice(slice.len(), 1, slice)
}
| true
|
4842da8c109e71728a12a8cc7f166bc0a1a2267e
|
Rust
|
ankurhimanshu14/novarche
|
/src/apis/rm_store/inventory.rs
|
UTF-8
| 2,047
| 2.953125
| 3
|
[
"Apache-2.0"
] |
permissive
|
pub mod inventory {
use mysql::*;
use mysql::prelude::*;
#[derive(Debug, Clone)]
pub struct Inventory {
pub heat_no: String,
pub grade: String,
pub size: usize,
pub section: String,
pub avail_qty: f64
}
impl Inventory {
pub fn inventory() -> Result<Vec<Inventory>> {
let url = "mysql://root:@localhost:3306/mws_database".to_string();
let pool = Pool::new(url).unwrap();
let mut conn = pool.get_conn().unwrap();
let table = "CREATE TEMPORARY TABLE inventory(
inv_id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
heat_no VARCHAR(20) NOT NULL UNIQUE,
grade VARCHAR(20) NOT NULL,
size INT NOT NULL,
section VARCHAR(10) NOT NULL,
avail_qty FLOAT(10, 3) NOT NULL
)ENGINE = InnoDB;";
conn.query_drop(table)?;
let insert = "INSERT INTO inventory(heat_no, grade, size, section, avail_qty)
SELECT DISTINCT
a.heat_no,
s.grade,
s.size,
s.section,
a.avail_qty
FROM approved_components a
INNER JOIN steels s
ON s.steel_code = (SELECT steel_code FROM gate_entry WHERE gate_entry_id = a.rm_id);";
conn.query_drop(insert)?;
let select = "SELECT heat_no, grade, size, section, avail_qty FROM inventory WHERE avail_qty <> 0 GROUP BY heat_no;";
let mut v: Vec<Inventory> = Vec::new();
conn.query_map(
select,
|(heat_no, grade, size, section, avail_qty)| {
let inv = Inventory {
heat_no, grade, size, section, avail_qty
};
v.push(inv)
}
)?;
Ok(v)
}
}
}
| true
|
31fcc6cfc785970b1e09e025050c67676075265d
|
Rust
|
communityvi/communityvi
|
/communityvi-server/src/message/outgoing.rs
|
UTF-8
| 4,442
| 2.953125
| 3
|
[] |
no_license
|
use crate::message::outgoing::broadcast_message::BroadcastMessage;
use crate::message::outgoing::error_message::ErrorMessage;
use crate::message::outgoing::success_message::SuccessMessage;
use crate::message::{MessageError, WebSocketMessage};
use js_int::UInt;
use serde::{Deserialize, Serialize};
pub mod broadcast_message;
pub mod error_message;
pub mod success_message;
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
#[serde(tag = "type")]
pub enum OutgoingMessage {
Success {
request_id: UInt,
message: SuccessMessage,
},
Error {
request_id: Option<UInt>,
message: ErrorMessage,
},
Broadcast {
message: BroadcastMessage,
},
}
impl From<&OutgoingMessage> for WebSocketMessage {
fn from(response: &OutgoingMessage) -> Self {
let json = serde_json::to_string(response).expect("Failed to serialize response to JSON.");
WebSocketMessage::text(json)
}
}
impl TryFrom<&WebSocketMessage> for OutgoingMessage {
type Error = MessageError;
fn try_from(websocket_message: &WebSocketMessage) -> Result<Self, MessageError> {
match websocket_message {
WebSocketMessage::Text(json) => {
serde_json::from_str(json).map_err(|error| MessageError::DeserializationFailed {
error: error.to_string(),
json: json.to_string(),
})
}
_ => Err(MessageError::WrongMessageType(websocket_message.clone())),
}
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::message::outgoing::broadcast_message::ClientJoinedBroadcast;
use crate::message::outgoing::error_message::ErrorMessageType;
use crate::room::client_id::ClientId;
use js_int::uint;
#[test]
fn success_message_should_serialize_and_deserialize() {
let success_message = OutgoingMessage::Success {
request_id: uint!(42),
message: SuccessMessage::Success,
};
let json = serde_json::to_string(&success_message).expect("Failed to serialize Success message to JSON");
assert_eq!(
r#"{"type":"success","request_id":42,"message":{"type":"success"}}"#,
json
);
let deserialized_success_message: OutgoingMessage =
serde_json::from_str(&json).expect("Failed to deserialize Success message from JSON");
assert_eq!(success_message, deserialized_success_message);
}
#[test]
fn error_message_with_request_id_should_serialize_and_deserialize() {
let error_message = OutgoingMessage::Error {
request_id: Some(uint!(42)),
message: ErrorMessage::builder()
.error(ErrorMessageType::InternalServerError)
.message("No medium".to_string())
.build(),
};
let json = serde_json::to_string(&error_message).expect("Failed to serialize error message to JSON");
assert_eq!(
r#"{"type":"error","request_id":42,"message":{"error":"internal_server_error","message":"No medium"}}"#,
json
);
let deserialized_error_message: OutgoingMessage =
serde_json::from_str(&json).expect("Failed to deserialize error message from JSON");
assert_eq!(error_message, deserialized_error_message);
}
#[test]
fn error_message_without_request_id_should_serialize_and_deserialize() {
let error_message = OutgoingMessage::Error {
request_id: None,
message: ErrorMessage::builder()
.error(ErrorMessageType::InvalidFormat)
.message("Missing request_id".to_string())
.build(),
};
let json = serde_json::to_string(&error_message).expect("Failed to serialize error message to JSON");
assert_eq!(
r#"{"type":"error","request_id":null,"message":{"error":"invalid_format","message":"Missing request_id"}}"#,
json
);
let deserialized_error_message: OutgoingMessage =
serde_json::from_str(&json).expect("Failed to deserialize error message from JSON");
assert_eq!(error_message, deserialized_error_message);
}
#[test]
fn broadcast_message_should_serialize_and_deserialize() {
let broadcast_message = OutgoingMessage::Broadcast {
message: BroadcastMessage::ClientJoined(ClientJoinedBroadcast {
id: ClientId::from(99),
name: "Luftballons".to_string(),
}),
};
let json = serde_json::to_string(&broadcast_message).expect("Failed to serialize broadcast message to JSON");
assert_eq!(
r#"{"type":"broadcast","message":{"type":"client_joined","id":99,"name":"Luftballons"}}"#,
json
);
let deserialized_broadcast_message: OutgoingMessage =
serde_json::from_str(&json).expect("Failed to deserialize broadcast message from JSON");
assert_eq!(broadcast_message, deserialized_broadcast_message);
}
}
| true
|
1727f601153f69a3ec87dc47f729e650b4818ade
|
Rust
|
emeric-martineau/redis-concentrator
|
/src/node/mod.rs
|
UTF-8
| 1,110
| 3
| 3
|
[
"Apache-2.0"
] |
permissive
|
//! This module contains routine to connect to redis node.
//!
use crate::lib::redis::stream::network::NetworkStream;
use crate::lib::redis::types::RedisError;
use std::net::TcpStream;
/// Create a a network stream in blocking mode.
pub fn create_redis_stream_connection_blocking(address: &str) -> Result<NetworkStream, RedisError> {
create_redis_stream_param(address, false)
}
/// Create a a network stream in non blocking mode.
pub fn create_redis_stream_connection(address: &str) -> Result<NetworkStream, RedisError> {
create_redis_stream_param(address, true)
}
/// Create redis stream.
fn create_redis_stream_param(address: &str, blocking: bool) -> Result<NetworkStream, RedisError> {
let tcp_stream = match TcpStream::connect(address) {
Ok(s) => s,
Err(e) => return Err(RedisError::from_io_error(e)),
};
if let Err(e) = tcp_stream.set_nonblocking(blocking) {
return Err(RedisError::from_io_error(e));
}
if let Err(e) = tcp_stream.set_nodelay(true) {
return Err(RedisError::from_io_error(e));
}
Ok(NetworkStream::new(tcp_stream))
}
| true
|
40d17f87b28b5d756a14e2b89dd5bccc045fea45
|
Rust
|
iqlusioninc/yubihsm.rs
|
/src/asymmetric/commands/generate_key.rs
|
UTF-8
| 872
| 2.734375
| 3
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
//! Generate a new asymmetric key within the `YubiHSM 2`
//!
//! <https://developers.yubico.com/YubiHSM2/Commands/Generate_Asymmetric_Key.html>
use crate::{
command::{self, Command},
object::{self, generate},
response::Response,
};
use serde::{Deserialize, Serialize};
/// Request parameters for `command::generate_asymmetric_key`
#[derive(Serialize, Deserialize, Debug)]
pub(crate) struct GenAsymmetricKeyCommand(pub(crate) generate::Params);
impl Command for GenAsymmetricKeyCommand {
type ResponseType = GenAsymmetricKeyResponse;
}
/// Response from `command::generate_asymmetric_key`
#[derive(Serialize, Deserialize, Debug)]
pub(crate) struct GenAsymmetricKeyResponse {
/// ID of the key
pub key_id: object::Id,
}
impl Response for GenAsymmetricKeyResponse {
const COMMAND_CODE: command::Code = command::Code::GenerateAsymmetricKey;
}
| true
|
6e041d75beae1c5406a863fd2545ec5b50ae78f3
|
Rust
|
shayneofficer/Advent-of-Code-2019
|
/03-crossed-wires/02.rs
|
UTF-8
| 2,899
| 2.90625
| 3
|
[] |
no_license
|
use std::fs;
use std::collections::HashMap;
use std::time::Instant;
fn main() {
let start = Instant::now();
let input = fs::read_to_string("./input.txt")
.expect("Something went wrong");
let wires: Vec<&str> = input.split('\n').collect();
let wire_one: Vec<&str> = wires[0].trim().split(',').collect();
let wire_two: Vec<&str> = wires[1].trim().split(',').collect();
let mut steps: HashMap<(i64, i64), u32> = HashMap::new();
let mut intersections: HashMap<(i64, i64), u32> = HashMap::new();
// (-994, 210), (-722, 274), (-290, -1036), (-277, -1036), (529, -582), (-3363, -4440)
// (-3363, -3937), (-3109, -3139), (-2618, -3077), (-2538, -3077), (-2523, -2959)
// (-2523, -2820), (-2511, -2011), (-2355, -2011), (-2208, -1811), (-2208, -1728)
// (-2208, -1582), (-2208, -1523), (-2167, -1012), (-2157, -1012), (-1690, -1012)
// (-783, -433), (-596, -1036), (752, 889), (531, 712), (855, 41), (991, 41)
// (1197, -15), (1197, -314), (1617, -314), (1435, -197), (991, 592), (855, 592)
let mut current_position: (i64, i64) = (0, 0);
let mut total_steps: u32 = 0;
for instruction in wire_one {
let (direction, distance) = instruction.split_at(1);
let dist: u32 = distance.parse::<u32>().unwrap();
for _i in 0..dist {
match direction {
"U" => current_position.1 += 1,
"D" => current_position.1 -= 1,
"L" => current_position.0 -= 1,
"R" => current_position.0 += 1,
_ => println!("Error")
}
total_steps += 1;
if !steps.contains_key(¤t_position) {
steps.insert(current_position, total_steps);
}
}
}
current_position = (0, 0);
total_steps = 0;
for instruction in wire_two {
let (direction, distance) = instruction.split_at(1);
let dist: u32 = distance.parse::<u32>().unwrap();
for _i in 0..dist {
match direction {
"U" => current_position.1 += 1,
"D" => current_position.1 -= 1,
"L" => current_position.0 -= 1,
"R" => current_position.0 += 1,
_ => println!("Error")
}
total_steps += 1;
if steps.contains_key(¤t_position) {
let both_wires_total_steps = total_steps +
steps.get(¤t_position).expect("Failed to get num steps");
intersections.insert(current_position, both_wires_total_steps);
}
}
}
let mut v = intersections.values().collect::<Vec<&u32>>();
v.sort();
println!("{}", v[0]); // 16524
println!("{}", start.elapsed().as_secs()); // 0 - wow way more performant than puzzle 1 solution
}
| true
|
8eb9acd2be8254d5330a8ae880b59824abcfc97f
|
Rust
|
StarryInternet/nl80211
|
/src/helpers.rs
|
UTF-8
| 1,297
| 3.28125
| 3
|
[
"MIT"
] |
permissive
|
use macaddr::MacAddr;
use neli::err::NlError;
use std::convert::TryInto;
/// Parse a vec of bytes as a String
pub fn parse_string(input: &[u8]) -> String {
String::from_utf8_lossy(input)
.trim_matches(char::from(0))
.to_string()
}
/// Parse a vec of bytes as a mac address
pub fn parse_macaddr(input: &[u8]) -> Result<MacAddr, NlError> {
if input.len() == 6 {
let array: [u8; 6] = input
.try_into()
.expect("Slice with incorrect number of bytes");
Ok(array.into())
} else if input.len() == 8 {
let array: [u8; 8] = input
.try_into()
.expect("Slice with incorrect number of bytes");
Ok(array.into())
} else {
Err(NlError::Msg(format!(
"Encountered a {}-byte MAC address",
input.len()
)))
}
}
#[cfg(test)]
mod test_type_conversion {
use super::*;
#[test]
fn test_parse_string() {
let input_string = "test".to_string();
let bytes_string = input_string.as_bytes().to_vec();
assert_eq!(parse_string(&bytes_string), input_string);
}
#[test]
fn test_parse_string_trim_zeros() {
let input = [0x48, 0x45, 0x4C, 0x4C, 0x4F, 0x00];
assert_eq!(parse_string(&input), "HELLO");
}
}
| true
|
31c7cb238034f031e84bde1132f8a1111675c534
|
Rust
|
yurivish/glium
|
/tests/support/mod.rs
|
UTF-8
| 3,680
| 2.71875
| 3
|
[
"Apache-2.0"
] |
permissive
|
/*!
Test supports module.
*/
#![allow(dead_code)]
use glutin;
use glium::{self, DisplayBuild};
use std::os;
/// Returns true if we are executed headless tests.
pub fn is_headless() -> bool {
os::getenv("HEADLESS_TESTS").is_some()
}
/// Builds a headless display for tests.
#[cfg(feature = "headless")]
pub fn build_display() -> glium::Display {
let display = if is_headless() {
glutin::HeadlessRendererBuilder::new(1024, 768).build_glium().unwrap()
} else {
glutin::WindowBuilder::new().with_visibility(false).build_glium().unwrap()
};
unsafe {
display.set_debug_callback_sync(|&mut: msg: String, _, _, severity: glium::debug::Severity| {
if severity == glium::debug::Severity::Medium ||
severity == glium::debug::Severity::High
{
panic!("{}", msg);
}
})
};
display
}
/// Builds a headless display for tests.
#[cfg(not(feature = "headless"))]
pub fn build_display() -> glium::Display {
assert!(!is_headless());
let display = glutin::WindowBuilder::new().with_visibility(false).build_glium().unwrap();
unsafe {
display.set_debug_callback_sync(|&mut: msg: String, _, _, severity: glium::debug::Severity| {
if severity == glium::debug::Severity::Medium ||
severity == glium::debug::Severity::High
{
panic!("{}", msg);
}
})
};
display
}
/// Builds a 2x2 unicolor texture.
pub fn build_unicolor_texture2d(display: &glium::Display, red: f32, green: f32, blue: f32)
-> glium::Texture2d
{
let color = ((red * 255.0) as u8, (green * 255.0) as u8, (blue * 255.0) as u8);
glium::texture::Texture2d::new(display, vec![
vec![color, color],
vec![color, color],
])
}
/// Builds a VB, IB and program that draw the red color `(1.0, 0.0, 0.0, 1.0)` on the whole screen.
pub fn build_fullscreen_red_pipeline(display: &glium::Display) -> (glium::vertex_buffer::VertexBufferAny,
glium::IndexBuffer, glium::Program)
{
#[vertex_format]
#[derive(Copy)]
struct Vertex {
position: [f32; 2],
}
(
glium::VertexBuffer::new(display, vec![
Vertex { position: [-1.0, 1.0] }, Vertex { position: [1.0, 1.0] },
Vertex { position: [-1.0, -1.0] }, Vertex { position: [1.0, -1.0] },
]).into_vertex_buffer_any(),
glium::IndexBuffer::new(display, glium::index_buffer::TriangleStrip(vec![0u8, 1, 2, 3])),
glium::Program::from_source(display,
"
#version 110
attribute vec2 position;
void main() {
gl_Position = vec4(position, 0.0, 1.0);
}
",
"
#version 110
void main() {
gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
}
",
None).unwrap()
)
}
/// Builds a VB and an IB corresponding to a rectangle.
///
/// The VB has the "position" attribute of type "vec2".
pub fn build_rectangle_vb_ib(display: &glium::Display)
-> (glium::vertex_buffer::VertexBufferAny, glium::IndexBuffer)
{
#[vertex_format]
#[derive(Copy)]
struct Vertex {
position: [f32; 2],
}
(
glium::VertexBuffer::new(display, vec![
Vertex { position: [-1.0, 1.0] }, Vertex { position: [1.0, 1.0] },
Vertex { position: [-1.0, -1.0] }, Vertex { position: [1.0, -1.0] },
]).into_vertex_buffer_any(),
glium::IndexBuffer::new(display, glium::index_buffer::TriangleStrip(vec![0u8, 1, 2, 3])),
)
}
| true
|
5712d719065f9d55a13cf387513c84dc2842c729
|
Rust
|
jrjparks/OpnFi-rs
|
/opnfi_gateway/src/net/nameservers.rs
|
UTF-8
| 933
| 2.59375
| 3
|
[
"Apache-2.0"
] |
permissive
|
use regex::{self, Regex};
use std::io::BufRead;
use std::str::FromStr;
use std::{fs, io, net::IpAddr, path};
pub(crate) fn get_nameservers() -> io::Result<Vec<IpAddr>> {
lazy_static! {
static ref NAMESERVER_REGEX: Regex = Regex::new(r"^nameserver\s([\d.:a-f]+)$").unwrap();
}
let resolv_path = path::Path::new("/etc/resolv.conf");
let mut nameservers = Vec::new();
if resolv_path.exists() {
let rdr = io::BufReader::new(fs::File::open(resolv_path)?);
for line in rdr.lines() {
if let Some(cap) = NAMESERVER_REGEX.captures(line?.as_str()) {
if let Some(mat) = cap.get(1) {
nameservers.push(IpAddr::from_str(mat.as_str()).unwrap())
}
}
}
Ok(nameservers)
} else {
Err(io::Error::new(
io::ErrorKind::NotFound,
"Could not find /etc/resolv.conf",
))
}
}
| true
|
53b87640a2dcc793b12305f1403c9f0253162c7f
|
Rust
|
redpfire/dfu-boot
|
/src/flags.rs
|
UTF-8
| 2,692
| 2.71875
| 3
|
[
"MIT"
] |
permissive
|
use crate::flash;
use crate::util;
use crate::dfu;
use stm32f1xx_hal::pac::FLASH;
#[allow(dead_code)]
const BL_FLAGS_HIGH: u32 = 0x0801fc00;
#[allow(dead_code)]
const BL_FLAGS_LOW: u32 = 0x0800fc00;
pub(crate) fn write_bl_flags(flags: &BlFlags) {
unsafe fn _write(flags: &BlFlags, addr: u32) {
util::_log_fmt(format_args!("Writing BL FLAGS to 0x{:x}\r\n", addr));
let words: &[u32] = BlFlags::as_u32_slice(flags);
// util::_log_fmt(format_args!("Slice: {:?}\r\n", words));
for (pos, w) in words.iter().enumerate() {
flash::write_word(addr+(pos as u32*4), *w).ok();
}
}
unsafe {
let flash = &*FLASH::ptr();
flash::erase_page(BL_FLAGS_HIGH);
let sr = flash.sr.read();
// 128kb not supported, fall back to 64kb
if sr.wrprterr().bit_is_set() || sr.pgerr().bit_is_set() || sr.eop().bit_is_clear() {
util::_log_str("128 kb not supported\r\n");
flash::erase_page(BL_FLAGS_LOW);
_write(flags, BL_FLAGS_LOW);
}
else {
_write(flags, BL_FLAGS_HIGH);
}
}
}
pub(crate) fn read_bl_flags() -> core::option::Option<&'static BlFlags> {
unsafe {
let mut flags = &*(BL_FLAGS_HIGH as *mut BlFlags);
if flags.magic != dfu::BL_MAGIC {
util::_log_str("Magic in BL_FLAGS_HIGH not found\r\n");
flags = &*(BL_FLAGS_LOW as *mut BlFlags);
if flags.magic != dfu::BL_MAGIC {
util::_log_str("Magic in BL_FLAGS_LOW not found\r\n");
return None;
}
else {
util::_log_fmt(format_args!("Flags from BL_FLAGS_LOW: {}\r\n", flags));
return Some(flags);
}
}
else {
util::_log_fmt(format_args!("Flags from BL_FLAGS_HIGH: {}\r\n", flags));
return Some(flags);
}
}
}
#[derive(Debug)]
pub struct BlFlags {
pub magic: u32,
pub flash_count: u32,
pub user_code_legit: bool,
pub user_code_present: bool,
pub user_code_length: u32,
}
impl BlFlags {
pub(crate) unsafe fn as_u32_slice<T: Sized>(p: &T) -> &[u32] {
::core::slice::from_raw_parts(
(p as *const T) as *const u32,
::core::mem::size_of::<T>(),
)
}
}
impl core::fmt::Display for BlFlags {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
write!(f, "BlFlags {{\r\n MAGIC: 0x{:x}\r\n Flash Count: {}\r\n UserCode Legit: {}\r\n UserCode Present: {}\r\n UserCode Length: {}\r\n}}", self.magic, self.flash_count, self.user_code_legit, self.user_code_present, self.user_code_length)
}
}
| true
|
7e0176467070b9284ddc3f43758f18a4baeb7866
|
Rust
|
K0bin/SourceRenderer
|
/quake3_formats/bsp/src/lump_data/vertex.rs
|
UTF-8
| 1,060
| 2.65625
| 3
|
[
"MIT"
] |
permissive
|
use std::io::{Read, Result as IOResult};
use crate::lump_data::{LumpData, LumpType};
use nalgebra::{Vector3, Vector2};
use crate::PrimitiveRead;
#[derive(Clone, Debug)]
pub struct Vertex {
pub position: Vector3<f32>,
pub tex_coord: [Vector2<f32>; 2],
pub normal: Vector3<f32>,
pub color: [u8; 4],
}
impl LumpData for Vertex {
fn lump_type() -> LumpType {
LumpType::Vertices
}
fn element_size(_version: i32) -> usize {
44
}
fn read(reader: &mut dyn Read, _version: i32) -> IOResult<Self> {
let position = Vector3::<f32>::new(reader.read_f32()?, reader.read_f32()?, reader.read_f32()?);
let tex_coord = [
Vector2::<f32>::new(reader.read_f32()?, reader.read_f32()?),
Vector2::<f32>::new(reader.read_f32()?, reader.read_f32()?),
];
let normal = Vector3::<f32>::new(reader.read_f32()?, reader.read_f32()?, reader.read_f32()?);
let color = [reader.read_u8()?, reader.read_u8()?, reader.read_u8()?, reader.read_u8()?];
Ok(Self {
position,
tex_coord,
normal,
color
})
}
}
| true
|
e3501725418dc3029819b390cef089b4571f7794
|
Rust
|
Frezc/leetcode-solutions
|
/src/n0115_distinct_subsequences.rs
|
UTF-8
| 3,255
| 3.703125
| 4
|
[] |
no_license
|
/**
* [115] Distinct Subsequences
*
* Given a string S and a string T, count the number of distinct subsequences of S which equals T.
*
* A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ACE" is a subsequence of "ABCDE" while "AEC" is not).
*
* Example 1:
*
*
* Input: S = "rabbbit", T = "rabbit"
* Output: 3
* Explanation:
*
* As shown below, there are 3 ways you can generate "rabbit" from S.
* (The caret symbol ^ means the chosen letters)
*
* rabbbit
* ^^^^ ^^
* rabbbit
* ^^ ^^^^
* rabbbit
* ^^^ ^^^
*
*
* Example 2:
*
*
* Input: S = "babgbag", T = "bag"
* Output: 5
* Explanation:
*
* As shown below, there are 5 ways you can generate "bag" from S.
* (The caret symbol ^ means the chosen letters)
*
* babgbag
* ^^ ^
* babgbag
* ^^ ^
* babgbag
* ^ ^^
* babgbag
* ^ ^^
* babgbag
* ^^^
*
*
*/
/// A simple DP question
/// Iterate solution:
/// Suppose i, j are end indices of substring of t and s, like s.substring(0, j+1) & t.substring(0, i+1)
/// Allocate dp with t.len * s.len, and fill 0 to it.
/// The key recursion is if s[j] == t[i], dp[i][j] = dp[i-1][j-1] + dp[i][j-1] else dp[i][j] = dp[i][j-1].
///
/// For example, suppose s = "babgbag", t = "bag", j = 3, i = 2.
/// Because s[j] == t[i], we can convert num_distinct("babg", "bag") to num_distinct("bab", "ba") + num_distinct("bab", "bag").
/// The first is matching current char and the second is not matching current char (just drop it).
///
/// Recursive solution:
/// Same
pub struct Solution {}
// submission codes start here
impl Solution {
pub fn num_distinct(s: String, t: String) -> i32 {
let l1 = t.len();
let l2 = s.len();
if l1 == 0 || l2 == 0 {
return 0;
}
let mut dp = vec![vec![0; l2]; l1];
for (i, c1) in t.chars().enumerate() {
for (j, c2) in s.chars().enumerate() {
if j < i || j > l2 - l1 + i {
continue;
}
if c1 == c2 {
dp[i][j] = if j > 0 {
dp[i][j - 1] + if i > 0 {
dp[i - 1][j - 1]
} else { 1 }
} else { 1 };
} else {
dp[i][j] = if j > 0 {
dp[i][j -1]
} else { 0 }
}
}
}
dp[l1 - 1][l2 - 1]
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
use crate::*;
#[test]
fn test_115() {
assert_eq!(Solution::num_distinct("rabbbit".to_string(), "rabbit".to_string()), 3);
assert_eq!(Solution::num_distinct("babgbag".to_string(), "bag".to_string()), 5);
assert_eq!(Solution::num_distinct("babgbag".to_string(), "bag".to_string()), 5);
assert_eq!(Solution::num_distinct("bababa".to_string(), "bag".to_string()), 0);
assert_eq!(Solution::num_distinct("".to_string(), "".to_string()), 0);
assert_eq!(Solution::num_distinct("a".to_string(), "".to_string()), 0);
}
}
| true
|
40a195ccab05428e980f7f981b6fe68098f25aff
|
Rust
|
TomSpencerLondon/ruruby
|
/src/loader.rs
|
UTF-8
| 1,278
| 2.859375
| 3
|
[
"MIT"
] |
permissive
|
use crate::*;
use std::fs::*;
use std::io::Read;
use std::path::PathBuf;
pub enum LoadError {
NotFound(String),
CouldntOpen(String),
}
pub fn load_file(path: &PathBuf) -> Result<String, LoadError> {
let mut file_body = String::new();
match OpenOptions::new().read(true).open(path) {
Ok(mut file) => match file.read_to_string(&mut file_body) {
Ok(_) => {}
Err(ioerr) => {
let msg = format!("{}", ioerr);
return Err(LoadError::CouldntOpen(msg));
}
},
Err(ioerr) => {
let msg = format!("{}", ioerr);
return Err(LoadError::CouldntOpen(msg));
}
};
Ok(file_body)
}
/// Load file and execute.
pub fn load_exec(vm: &mut VM, path: &PathBuf, allow_repeat: bool) -> Result<bool, RubyError> {
let absolute_path = vm.canonicalize_path(path)?;
let res = vm.globals.add_source_file(&absolute_path);
if !allow_repeat && res.is_none() {
return Ok(false);
}
let program = vm.load_file(&absolute_path)?;
#[cfg(feature = "verbose")]
eprintln!("reading:{}", absolute_path.to_string_lossy());
//vm.class_push(BuiltinClass::object());
vm.run(absolute_path, program)?;
//vm.class_pop();
Ok(true)
}
| true
|
e219443e33a1b9897fdfdf77eb803651b43ae4dc
|
Rust
|
chibby0ne/exercism
|
/rust/palindrome-products/src/lib.rs
|
UTF-8
| 1,601
| 3.734375
| 4
|
[
"MIT"
] |
permissive
|
use std::iter;
/// `Palindrome` is a newtype which only exists when the contained value is a palindrome number in base ten.
///
/// A struct with a single field which is used to constrain behavior like this is called a "newtype", and its use is
/// often referred to as the "newtype pattern". This is a fairly common pattern in Rust.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Ord, PartialOrd)]
pub struct Palindrome(u64);
impl Palindrome {
fn is_palindrome(value: u64) -> bool {
let val_str = value.to_string();
val_str
.chars()
.zip(val_str.chars().rev())
.all(|(front, back)| front == back)
}
/// Create a `Palindrome` only if `value` is in fact a palindrome when represented in base ten. Otherwise, `None`.
pub fn new(value: u64) -> Option<Palindrome> {
if Palindrome::is_palindrome(value) {
Some(Palindrome(value))
} else {
None
}
}
/// Get the value of this palindrome.
pub fn into_inner(self) -> u64 {
self.0
}
}
pub fn palindrome_products(min: u64, max: u64) -> Option<(Palindrome, Palindrome)> {
let mut palindromes: Vec<Palindrome> = (min..=max)
.flat_map(|v| {
iter::repeat(v)
.zip(min..=max)
.map(|(a, b)| a * b)
.collect::<Vec<u64>>()
})
.filter_map(Palindrome::new)
.collect();
palindromes.sort_unstable();
match (palindromes.first(), palindromes.last()) {
(Some(&min), Some(&max)) => Some((min, max)),
_ => None,
}
}
| true
|
0e1eceee72a046738332ee433fa5901c1eeb3fe8
|
Rust
|
adilhasan/catalogue
|
/src/scan.rs
|
UTF-8
| 2,913
| 2.921875
| 3
|
[
"MIT"
] |
permissive
|
// Library of functions for scanning the database
//
use std::{path::PathBuf, fs};
use std::path::Path;
use data_encoding::HEXUPPER;
use ring::digest::{Context, Digest, SHA256};
use std::fs::File;
use std::error::Error;
use std::io::{BufReader, Read};
use std::time::{UNIX_EPOCH};
use walkdir::{WalkDir};
use log::{debug, error};
use crate::catalogue_database;
use crate::models;
// Starting from the top_dir walk through the directory finding files of interest, extract properties
// and output a list of files
fn find_files(top_dir: PathBuf, recursive: bool) -> Result<Vec<models::DataFile>, Box <dyn Error>> {
let mut files: Vec<models::DataFile> = Vec::new();
let formats = vec!["docx", "pdf", "epub"];
let mut walk = WalkDir::new(&top_dir).max_depth(1);
if recursive {
walk = WalkDir::new(&top_dir);
}
// loop over the folder and get the
for node in walk {
let path = match node {
Ok(n) => n.into_path(),
Err(err) => {
let e_path = err.path().unwrap_or(Path::new("")).to_path_buf();
error!("Cannot access path {:?}", e_path);
e_path
},
};
let mut a_file : models::DataFile = models::DataFile::new();
a_file.extension = match &path.extension() {
Some(p_ext) => p_ext.to_str().unwrap().to_string(),
None => String::from(""),
};
if !(formats.iter().any(|&f| f == a_file.extension)) {
continue;
}
let metadata = fs::metadata(&path)?;
a_file.created = match metadata.created() {
Ok(t) => match t.duration_since(UNIX_EPOCH) {
Ok(ts) => ts.as_secs(),
Err(_) => 0,
},
Err(_) => 0,
};
a_file.size = metadata.len();
a_file.path = path;
let input = File::open(&a_file.path)?;
let reader = BufReader::new(input);
let digest = sha256_digest(reader)?;
a_file.hash = HEXUPPER.encode(digest.as_ref());
debug!("{:?}",&a_file);
files.push(a_file)
}
Ok(files)
}
// Code taken from the Rust Cookbook
// Compute the sha-256 hash for the file
fn sha256_digest<R: Read>(mut reader: R) -> Result<Digest, Box <dyn Error>> {
let mut context = Context::new(&SHA256);
let mut buffer = [0; 1024];
loop {
let count = reader.read(&mut buffer)?;
if count == 0 {
break;
}
context.update(&buffer[..count]);
}
Ok(context.finish())
}
// Scan the directory, get the list of files and put into the database
pub fn scan(directory: PathBuf, recursive: bool, config: models::Config) -> Result<(), Box <dyn Error>> {
let files = find_files(directory, recursive)?;
catalogue_database::create_table(&config)?;
catalogue_database::insert_files(&config, files);
Ok(())
}
| true
|
a96db1ca2c0e8f4db1b68696504daed31b6d5dfa
|
Rust
|
woohp/foo
|
/src/err.rs
|
UTF-8
| 1,614
| 3.28125
| 3
|
[] |
no_license
|
use std::str::Utf8Error;
use std::num::ParseIntError;
use std::fmt;
use std::error;
#[derive(Debug)]
pub enum BencodeError {
Utf8(Utf8Error),
IntError(ParseIntError),
DictionaryKeyNotString,
UnexpectedCharacter(usize),
UnexpectedEndOfInput,
}
impl fmt::Display for BencodeError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
BencodeError::Utf8(ref err) => write!(f, "Utf8 error: {}", err),
BencodeError::IntError(ref err) => write!(f, "Int error: {}", err),
BencodeError::DictionaryKeyNotString => write!(f, "Dictionary key was not a string"),
BencodeError::UnexpectedCharacter(ref position) => write!(f, "Unexpected character: position {}", position),
BencodeError::UnexpectedEndOfInput => write!(f, "Unexpected end of input"),
}
}
}
impl error::Error for BencodeError {
fn description(&self) -> &str {
match *self {
BencodeError::Utf8(ref err) => err.description(),
BencodeError::IntError(ref err) => err.description(),
BencodeError::DictionaryKeyNotString => "Dictionary key was not a string",
BencodeError::UnexpectedCharacter(_) => "Unexpected character",
BencodeError::UnexpectedEndOfInput => "Unexpected end of input",
}
}
}
impl From<Utf8Error> for BencodeError {
fn from(err: Utf8Error) -> BencodeError {
BencodeError::Utf8(err)
}
}
impl From<ParseIntError> for BencodeError {
fn from(err: ParseIntError) -> BencodeError {
BencodeError::IntError(err)
}
}
| true
|
dbb0a640a2b9f30361460988950d3cbda3c4a4c2
|
Rust
|
bruno319/noise-detector
|
/src/main.rs
|
UTF-8
| 2,064
| 2.8125
| 3
|
[] |
no_license
|
use std::sync::mpsc::*;
use portaudio;
use crate::input::{get_input_settings, Sensibility, NoiseState};
use crate::output::Alarm;
use std::io::stdin;
use std::thread;
use std::time::Duration;
mod output;
mod input;
fn main() {
let sensibility = choose_sensibility_level();
let mut noise_state = NoiseState::new(sensibility);
let pa = portaudio::PortAudio::new().expect("Unable to init PortAudio");
let mut alarm = Alarm::new(&pa);
let input_settings = get_input_settings(&pa);
let (sender, receiver) = channel();
let read_input_callback = move |portaudio::InputStreamCallbackArgs { buffer, .. }| {
match sender.send(buffer) {
Ok(_) => portaudio::Continue,
Err(_) => portaudio::Complete
}
};
let mut stream = pa.open_non_blocking_stream(input_settings, read_input_callback).expect("Unable to create stream");
stream.start().expect("Unable to start stream");
while stream.is_active().unwrap() {
thread::sleep(Duration::from_millis(100));
if noise_state.is_noisy() && !alarm.is_playing() {
alarm.play(&pa).expect("Unable to play alarm sound");
}
while let Ok(buffer) = receiver.try_recv() {
noise_state.add(buffer.to_vec());
}
}
}
fn choose_sensibility_level() -> Sensibility {
print_menu();
let option = &mut String::new();
stdin().read_line(option)
.map_or_else(|_err| {
println!("Unable to read console. Setting to medium sensibility");
Sensibility::Medium
}, |_ok| set_sensibility_option(option))
}
fn print_menu() {
println!("Choose sensibility level: \n \
1 - High \n \
2 - Medium \n \
3 - Low");
}
fn set_sensibility_option(option: &mut String) -> Sensibility {
match option.trim() {
"1" => Sensibility::High,
"2" => Sensibility::Medium,
"3" => Sensibility::Low,
_ => {
println!("Invalid option. Setting to medium sensibility");
Sensibility::Medium
}
}
}
| true
|
9c82f0052b2eb2198604909ac8d2a6f0134f9259
|
Rust
|
google/tock-on-titan
|
/third_party/futures-util/src/future/future/flatten.rs
|
UTF-8
| 1,392
| 2.59375
| 3
|
[
"Apache-2.0",
"LicenseRef-scancode-generic-cla",
"MIT"
] |
permissive
|
use super::chain::Chain;
use core::fmt;
use core::pin::Pin;
use futures_core::future::{FusedFuture, Future};
use futures_core::task::{Context, Poll};
use pin_utils::unsafe_pinned;
/// Future for the [`flatten`](super::FutureExt::flatten) method.
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct Flatten<Fut>
where Fut: Future,
{
state: Chain<Fut, Fut::Output, ()>,
}
impl<Fut> Flatten<Fut>
where Fut: Future,
Fut::Output: Future,
{
unsafe_pinned!(state: Chain<Fut, Fut::Output, ()>);
pub(super) fn new(future: Fut) -> Flatten<Fut> {
Flatten {
state: Chain::new(future, ()),
}
}
}
impl<Fut> fmt::Debug for Flatten<Fut>
where Fut: Future + fmt::Debug,
Fut::Output: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Flatten")
.field("state", &self.state)
.finish()
}
}
impl<Fut> FusedFuture for Flatten<Fut>
where Fut: Future,
Fut::Output: Future,
{
fn is_terminated(&self) -> bool { self.state.is_terminated() }
}
impl<Fut> Future for Flatten<Fut>
where Fut: Future,
Fut::Output: Future,
{
type Output = <Fut::Output as Future>::Output;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
self.state().poll(cx, |a, ()| a)
}
}
| true
|
517618217379f000822637a9002f174a5eca9475
|
Rust
|
shanavas786/coding-fu
|
/rust/fib/src/main.rs
|
UTF-8
| 3,192
| 2.8125
| 3
|
[
"LicenseRef-scancode-public-domain"
] |
permissive
|
#![feature(test)]
extern crate test;
use std::collections::HashMap;
use test::Bencher;
static mut A: [u32; 32] = [0; 32];
static BENCH_SIZE: u32 = 32;
unsafe fn fib_static_mut(n: u32) -> u32 {
if n < 2 {
return 1;
}
println!("{}", n);
if A[n as usize] == 0 {
A[n as usize] = fib_static_mut(n - 1) + fib_static_mut(n - 2);
}
A[n as usize]
}
fn fib_hashmap(n: u32) -> u32 {
let mut cache = HashMap::new();
cache.insert(0u32, 1u32);
cache.insert(1u32, 1u32);
fn fib_mem(n: u32, cache: &mut HashMap<u32, u32>) -> u32 {
let val = cache.get(&n);
match val {
Some(&v) => v,
None => {
let a = fib_mem(n - 1, cache);
let b = fib_mem(n - 2, cache);
cache.insert(n, a + b);
a + b
}
}
}
fib_mem(n, &mut cache)
}
struct Fib {
cache: HashMap<u32, u32>,
}
impl Fib {
fn new() -> Self {
let mut cache = HashMap::new();
cache.insert(0u32, 1u32);
cache.insert(1u32, 1u32);
Fib { cache: cache }
}
fn get(&mut self, n: u32) -> u32 {
let val = self.cache.get(&n);
match val {
Some(&v) => v,
None => {
let a = self.get(n - 1);
let b = self.get(n - 2);
self.cache.insert(n, a + b);
a + b
}
}
}
}
// by Devdutt Shenoi(de-sh)
struct FibV {
cache: Vec<u32>
}
impl FibV {
fn new() -> Self {
FibV{ cache: vec![1,1] }
}
fn gen(&mut self, n: u32) {
let len = self.cache.len() - 1;
for i in len..(n as usize) {
self.cache.push(self.cache[i] + self.cache[i-1]);
}
}
fn get(&mut self, n: u32) -> u32 {
match self.cache.get(n as usize) {
Some(a) => *a,
None => {
self.gen(n);
*self.cache.get(n as usize).unwrap()
}
}
}
}
#[bench]
fn bench_fib_static_mut(b: &mut Bencher) {
b.iter(|| {
(0..BENCH_SIZE)
.map(|x| unsafe { fib_static_mut(x) })
.collect::<Vec<u32>>()
})
}
#[bench]
fn bench_fib_hashmap(b: &mut Bencher) {
b.iter(|| (0..BENCH_SIZE).map(fib_hashmap).collect::<Vec<u32>>())
}
#[bench]
fn bench_fib_struct(b: &mut Bencher) {
let mut fib = Fib::new();
b.iter(|| (0..BENCH_SIZE).map(|x| fib.get(x)).collect::<Vec<u32>>())
}
#[bench]
fn bench_fib_vec(b: &mut Bencher) {
let mut fib = FibV::new();
b.iter(|| (0..BENCH_SIZE).map(|x| fib.get(x)).collect::<Vec<u32>>())
}
// Compiling fib v0.1.0 (/home/shanavas/learn/coding-fu/rust/fib)
// Finished bench [optimized] target(s) in 0.82s
// Running target/release/deps/fib-d1b99b5a2fc5179f
//
// running 4 tests
// test bench_fib_hashmap ... bench: 57,959 ns/iter (+/- 2,442)
// test bench_fib_static_mut ... bench: 4,143 ns/iter (+/- 46)
// test bench_fib_struct ... bench: 709 ns/iter (+/- 32)
// test bench_fib_vec ... bench: 122 ns/iter (+/- 0)
//
// test result: ok. 0 passed; 0 failed; 0 ignored; 4 measured; 0 filtered out
| true
|
442a5855b38c0ea1b2f1868d398a9646fd81546d
|
Rust
|
cohyou/apg
|
/src/apg/value.rs
|
UTF-8
| 722
| 3.34375
| 3
|
[
"MIT"
] |
permissive
|
use std::rc::Rc;
use std::fmt;
use super::*;
#[derive(Clone, PartialEq, Eq, Hash)]
pub enum Value {
Unit,
Inl(Rc<Value>, Rc<Type>),
Inr(Rc<Type>, Rc<Value>),
Pair(Rc<Value>, Rc<Value>),
Prim(Rc<Value>),
Id(Rc<Element>),
}
impl fmt::Debug for Value {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Value::Unit => write!(f, "()"),
Value::Inl(v, t) => write!(f, "{:?} + {:?}", v, t),
Value::Inr(t, v) => write!(f, "{:?} + {:?}", t, v),
Value::Pair(v1, v2) => write!(f, "{:?} * {:?}", v1, v2),
Value::Prim(v) => write!(f, "P{:?}", v),
Value::Id(e) => write!(f, "{:?}", e),
}
}
}
| true
|
b674d66fc40228e069b4e80f697bb5e85c532d8f
|
Rust
|
MinniFlo/advent_of_code_2019
|
/3_a/src/main.rs
|
UTF-8
| 6,003
| 3.203125
| 3
|
[] |
no_license
|
use std::fs::File;
use std::io::{BufReader, BufRead};
use std::collections::HashSet;
use std::i32::MAX;
#[derive(Debug)]
enum Dir { Up, Right }
#[derive(Debug)]
struct Line {
start: i32,
end: i32,
constant: i32,
dir: Dir,
end_coord: (i32, i32),
}
impl Line {
fn new(begin: (i32, i32), dir_char: char, len: i32) -> Line {
match dir_char {
'U' => {
let start = begin.1;
let end = start + len;
let constant = begin.0;
let dir = Dir::Up;
let end_coord: (i32, i32) = (constant, end);
Line { start, end, constant, dir, end_coord }
}
'R' => {
let start = begin.0;
let end = start + len;
let constant = begin.1;
let dir = Dir::Right;
let end_coord: (i32, i32) = (end, constant);
Line { start, end, constant, dir, end_coord }
}
'D' => {
let end = begin.1;
let start = end - len;
let constant = begin.0;
let dir = Dir::Up;
let end_coord: (i32, i32) = (constant, start);
Line { start, end, constant, dir, end_coord }
}
'L' => {
let end = begin.0;
let start = end - len;
let constant = begin.1;
let dir = Dir::Right;
let end_coord: (i32, i32) = (start, constant);
Line { start, end, constant, dir, end_coord }
}
_ => panic!("convert function does not work")
}
}
fn intersections_with(&self, other: &Line) -> Option<(i32, i32)> {
if self.compare_dir(&other.dir) {
None
}else if (self.start..=self.end).contains(&other.constant) &&
(other.start..=other.end).contains(&self.constant) {
if self.compare_dir(&Dir::Right) {
Some((other.constant, self.constant))
} else {
Some((self.constant, other.constant))
}
} else {
None
}
}
fn compare_dir(&self, dir: &Dir) -> bool {
match (&self.dir, dir) {
(Dir::Right, Dir::Right) => true,
(Dir::Up, Dir::Up) => true,
_ => false
}
}
fn contains_tup(&self, tup: (i32, i32)) -> bool {
match self.dir {
Dir::Up => tup.0 == self.constant && (self.start..=self.end).contains(&tup.1),
Dir::Right => tup.1 == self.constant && (self.start..=self.end).contains(&tup.0)
}
}
fn distants_in_line(&self, tup: (i32, i32)) -> i32 {
match self.dir {
Dir::Up => {
if self.end == self.end_coord.1 {
tup.1 - self.start
} else {
self.end - tup.1
}
}
Dir::Right => {
if self.end == self.end_coord.0 {
tup.0 - self.start
} else {
self.end - tup.0
}
}
}
}
}
fn convert_to_vec(s_o: &mut String) -> Vec<&str> {
s_o.split(',')
.map(|s| s.trim())
.collect()
}
fn convert_to_line(vec: Vec<&str>) -> Vec<Line> {
let mut lines: Vec<Line> = Vec::new();
let mut origin: (i32, i32) = (0, 0);
for i in vec.iter() {
let dir_char: char = i[0..1].parse().unwrap();
let len: i32 = i[1..].parse().unwrap();
let line: Line = Line::new(origin, dir_char, len);
origin = line.end_coord;
lines.push(line);
}
lines
}
fn _find_short_manhatten(vec1: Vec<&str>, vec2: Vec<&str>) -> i32 {
let line1 = convert_to_line(vec1);
let line2 = convert_to_line(vec2);
let mut intersections: HashSet<(i32, i32)> = HashSet::new();
for i in line1.iter() {
for j in line2.iter() {
if let Some(tup) = i.intersections_with(j) {
if tup != (0, 0) {
intersections.insert(tup);
}
}
}
}
let mut nearest = MAX;
for (x, y) in intersections.iter() {
let value = x.abs() + y.abs();
if value < nearest {
nearest = value
}
}
nearest
}
fn length_to_tup(line: &Vec<Line>, intersection: &(i32, i32)) -> i32 {
let mut sum = 0;
for i in line.iter() {
if i.contains_tup(*intersection) {
sum += i.distants_in_line(*intersection);
return sum
}
sum += (i.start - i.end).abs();
}
panic!("intersection is not an intersection");
}
fn find_short_delay(vec1: Vec<&str>, vec2: Vec<&str>) -> i32 {
let line1 = convert_to_line(vec1);
let line2 = convert_to_line(vec2);
let mut intersections: HashSet<(i32, i32)> = HashSet::new();
for i in line1.iter() {
for j in line2.iter() {
if let Some(tup) = i.intersections_with(j) {
if tup != (0, 0) {
intersections.insert(tup);
}
}
}
}
let mut length_sum = MAX;
for tup in intersections.iter() {
let line1_sum = length_to_tup(&line1, tup);
let line2_sum = length_to_tup(&line2, tup);
if line1_sum + line2_sum < length_sum {
length_sum = line1_sum + line2_sum;
}
}
length_sum
}
fn main() -> std::io::Result<()> {
let file = File::open("./input.txt")?;
let mut str_1 = String::new();
let mut str_2 = String::new();
let mut reader = BufReader::new(file);
reader.read_line(&mut str_1).unwrap();
reader.read_line(&mut str_2).unwrap();
// let mut str_1 = String::from("R8,U5,L5,D3");
// let mut str_2 = String::from("U7,R6,D4,L4");
let vec1 = convert_to_vec(&mut str_1);
let vec2 = convert_to_vec(&mut str_2);
print!("{}", find_short_delay(vec1, vec2));
Ok(())
}
| true
|
bee0a95e1d61092ee238e79eee5aace372864d91
|
Rust
|
Meyermagic/met
|
/src/stage.rs
|
UTF-8
| 2,287
| 2.640625
| 3
|
[] |
no_license
|
use common::MetCommand;
use std::io::fs;
use std::io;
use std::os;
use metaphor::repository::find_repo_root;
pub struct Command;
impl Command {
pub fn new() -> Box<MetCommand> { box Command as Box<MetCommand> }
}
impl MetCommand for Command {
fn name(&self) -> &'static str { "stage" }
fn run(&self, args: &[String]) {
let cd = os::make_absolute(&Path::new("."));
let repo_root = match find_repo_root(&cd) {
Some(path) => path,
None => fail!("no repo found in this or any parent directory."),
};
debug!("repo root: {}", repo_root.display());
let met_root = repo_root.join(".met");
let head_dir = met_root.join("head");
let stage_dir = met_root.join("stage");
let stage_source = match args.len() {
0 => repo_root.clone(),
1 => cd.join(args.get(0).unwrap().as_slice()),
_ => fail!("usage: met stage [path]"),
};
debug!("non-rel stage source: {}", stage_source.display());
let stage_source = match stage_source.path_relative_from(&repo_root) {
Some(path) => path,
None => fail!("file or directory to stage must be inside repository root"),
};
debug!("rel stage source: {}", stage_source.display());
let cd_suc = os::change_dir(&repo_root);
debug!("cd: {}", cd_suc);
let dirpart = Path::new(stage_source.dirname());
debug!("dir part: {}", dirpart.display());
if dirpart != Path::new(".") {
debug!("path to stage not at repo root");
fs::mkdir_recursive(&stage_dir.join(dirpart), io::UserDir);
}
if stage_source.is_file() {
debug!("staging a file");
let target = stage_dir.join(&stage_source);
fs::copy(&stage_source, &target);
} else if stage_source.is_dir() {
debug!("staging a directory");
let met_rel = Path::new("./.met");
for path in fs::walk_dir(&stage_source).unwrap() {
debug!("walking over {}", path.display());
if met_rel.is_ancestor_of(&path) {
debug!("skipping .met");
continue;
}
//FIXME: Handle symlinks properly
match path.lstat().unwrap().kind {
io::TypeFile => {
debug!("staging file {}", path.display());
fs::copy(&path, &stage_dir.join(&path));
},
io::TypeDirectory => {
debug!("staging dir {}", path.display());
fs::mkdir(&stage_dir.join(&path), io::UserDir);
},
_ => {},
}
}
}
}
}
| true
|
7008be9497dfdc70b79512d8bd940707a33d2ca2
|
Rust
|
matrix-org/rust-synapse-compress-state
|
/synapse_auto_compressor/src/state_saving.rs
|
UTF-8
| 11,934
| 2.84375
| 3
|
[
"Apache-2.0"
] |
permissive
|
// This module contains functions to communicate with the database
use anyhow::{bail, Result};
use log::trace;
use synapse_compress_state::Level;
use openssl::ssl::{SslConnector, SslMethod, SslVerifyMode};
use postgres::{fallible_iterator::FallibleIterator, types::ToSql, Client};
use postgres_openssl::MakeTlsConnector;
/// Connects to the database and returns a postgres client
///
/// # Arguments
///
/// * `db_url` - The URL of the postgres database that synapse is using.
/// e.g. "postgresql://user:password@domain.com/synapse"
pub fn connect_to_database(db_url: &str) -> Result<Client> {
let mut builder = SslConnector::builder(SslMethod::tls())?;
builder.set_verify(SslVerifyMode::NONE);
let connector = MakeTlsConnector::new(builder.build());
let client = Client::connect(db_url, connector)?;
Ok(client)
}
/// Creates the state_compressor_state and state_compressor progress tables
///
/// If these tables already exist then this function does nothing
///
/// # Arguments
///
/// * `client` - A postgres client used to send the requests to the database
pub fn create_tables_if_needed(client: &mut Client) -> Result<()> {
let create_state_table = r#"
CREATE TABLE IF NOT EXISTS state_compressor_state (
room_id TEXT NOT NULL,
level_num INT NOT NULL,
max_size INT NOT NULL,
current_length INT NOT NULL,
current_head BIGINT,
UNIQUE (room_id, level_num)
)"#;
client.execute(create_state_table, &[])?;
let create_state_table_indexes = r#"
CREATE INDEX IF NOT EXISTS state_compressor_state_index ON state_compressor_state (room_id)"#;
client.execute(create_state_table_indexes, &[])?;
let create_progress_table = r#"
CREATE TABLE IF NOT EXISTS state_compressor_progress (
room_id TEXT PRIMARY KEY,
last_compressed BIGINT NOT NULL
)"#;
client.execute(create_progress_table, &[])?;
let create_compressor_global_progress_table = r#"
CREATE TABLE IF NOT EXISTS state_compressor_total_progress(
lock CHAR(1) NOT NULL DEFAULT 'X' UNIQUE,
lowest_uncompressed_group BIGINT NOT NULL,
CHECK (Lock='X')
);
INSERT INTO state_compressor_total_progress
(lowest_uncompressed_group)
VALUES (0)
ON CONFLICT (lock) DO NOTHING;
"#;
client.batch_execute(create_compressor_global_progress_table)?;
Ok(())
}
/// Retrieve the level info so we can restart the compressor
///
/// # Arguments
///
/// * `client` - A postgres client used to send the requests to the database
/// * `room_id` - The room who's saved compressor state we want to load
pub fn read_room_compressor_state(
client: &mut Client,
room_id: &str,
) -> Result<Option<(i64, Vec<Level>)>> {
// Query to retrieve all levels from state_compressor_state
// Ordered by ascending level_number
let sql = r#"
SELECT level_num, max_size, current_length, current_head, last_compressed
FROM state_compressor_state
LEFT JOIN state_compressor_progress USING (room_id)
WHERE room_id = $1
ORDER BY level_num ASC
"#;
// send the query to the database
let mut levels = client.query_raw(sql, &[room_id])?;
// Needed to ensure that the rows are for unique consecutive levels
// starting from 1 (i.e of form [1,2,3] not [0,1,2] or [1,1,2,2,3])
let mut prev_seen = 0;
// The vector to store the level info from the database in
let mut level_info: Vec<Level> = Vec::new();
// Where the last compressor run stopped
let mut last_compressed = None;
// Used to only read last_compressed value once
let mut first_row = true;
// Loop through all the rows retrieved by that query
while let Some(l) = levels.next()? {
// Read out the fields into variables
//
// Some of these are `usize` as they may be used to index vectors, but stored as Postgres
// type `INT` which is the same as`i32`.
//
// Since usize is unlikely to be ess than 32 bits wide, this conversion should be safe
let level_num: usize = l.get::<_, i32>("level_num") as usize;
let max_size: usize = l.get::<_, i32>("max_size") as usize;
let current_length: usize = l.get::<_, i32>("current_length") as usize;
let current_head: Option<i64> = l.get("current_head");
// Only read the last compressed column once since is the same for each row
if first_row {
last_compressed = l.get("last_compressed"); // might be NULL if corrupted
if last_compressed.is_none() {
bail!(
"No entry in state_compressor_progress for room {} but entries in state_compressor_state were found",
room_id
)
}
first_row = false;
}
// Check that there aren't multiple entries for the same level number
// in the database. (Should be impossible due to unique key constraint)
if prev_seen == level_num {
bail!(
"The level {} occurs twice in state_compressor_state for room {}",
level_num,
room_id,
);
}
// Check that there is no missing level in the database
// e.g. if the previous row retrieved was for level 1 and this
// row is for level 3 then since the SQL query orders the results
// in ascenting level numbers, there was no level 2 found!
if prev_seen != level_num - 1 {
bail!("Levels between {} and {} are missing", prev_seen, level_num,);
}
// if the level is not empty, then it must have a head!
if current_head.is_none() && current_length != 0 {
bail!(
"Level {} has no head but current length is {} in room {}",
level_num,
current_length,
room_id,
);
}
// If the level has more groups in than the maximum then something is wrong!
if current_length > max_size {
bail!(
"Level {} has length {} but max size {} in room {}",
level_num,
current_length,
max_size,
room_id,
);
}
// Add this level to the level_info vector
level_info.push(Level::restore(max_size, current_length, current_head));
// Mark the previous level_number seen as the current one
prev_seen = level_num;
}
// If we didn't retrieve anything from the database then there is no saved state
// in the database!
if level_info.is_empty() {
return Ok(None);
}
// Return the compressor state we retrieved
// last_compressed cannot be None at this point, so safe to unwrap
Ok(Some((last_compressed.unwrap(), level_info)))
}
/// Save the level info so it can be loaded by the next run of the compressor
///
/// # Arguments
///
/// * `client` - A postgres client used to send the requests to the database
/// * `room_id` - The room who's saved compressor state we want to save
/// * `level_info` - The state that can be used to restore the compressor later
/// * `last_compressed` - The last state_group that was compressed. This is needed
/// so that the compressor knows where to start from next
pub fn write_room_compressor_state(
client: &mut Client,
room_id: &str,
level_info: &[Level],
last_compressed: i64,
) -> Result<()> {
// Wrap all the changes to the state for this room in a transaction
// This prevents accidentally having malformed compressor start info
let mut write_transaction = client.transaction()?;
// Go through every level that the compressor is using
for (level_num, level) in level_info.iter().enumerate() {
// the 1st level is level 1 not level 0, but enumerate starts at 0
// so need to add 1 to get correct number
let level_num = level_num + 1;
// bring the level info out of the Level struct
let (max_size, current_len, current_head) = (
level.get_max_length(),
level.get_current_length(),
level.get_head(),
);
// Update the database with this compressor state information
//
// Some of these are `usize` as they may be used to index vectors, but stored as Postgres
// type `INT` which is the same as`i32`.
//
// Since these values should always be small, this conversion should be safe.
let (level_num, max_size, current_len) =
(level_num as i32, max_size as i32, current_len as i32);
let params: Vec<&(dyn ToSql + Sync)> =
vec![&room_id, &level_num, &max_size, ¤t_len, ¤t_head];
write_transaction.execute(
r#"
INSERT INTO state_compressor_state
(room_id, level_num, max_size, current_length, current_head)
VALUES ($1, $2, $3, $4, $5)
ON CONFLICT (room_id, level_num)
DO UPDATE SET
max_size = excluded.max_size,
current_length = excluded.current_length,
current_head= excluded.current_head;
"#,
¶ms,
)?;
}
// Update the database with this progress information
let params: Vec<&(dyn ToSql + Sync)> = vec![&room_id, &last_compressed];
write_transaction.execute(
r#"
INSERT INTO state_compressor_progress (room_id, last_compressed)
VALUES ($1, $2)
ON CONFLICT (room_id)
DO UPDATE SET last_compressed = excluded.last_compressed;
"#,
¶ms,
)?;
// Commit the transaction (otherwise changes never happen)
write_transaction.commit()?;
Ok(())
}
/// Returns the room with with the lowest uncompressed state group id
///
/// A group is detected as uncompressed if it is greater than the `last_compressed`
/// entry in `state_compressor_progress` for that room.
///
/// The `lowest_uncompressed_group` value stored in `state_compressor_total_progress`
/// stores where this method last finished, to prevent repeating work
///
/// # Arguments
///
/// * `client` - A postgres client used to send the requests to the database
pub fn get_next_room_to_compress(client: &mut Client) -> Result<Option<String>> {
// Walk the state_groups table until find next uncompressed group
let get_next_room = r#"
SELECT room_id, id
FROM state_groups
LEFT JOIN state_compressor_progress USING (room_id)
WHERE
id >= (SELECT lowest_uncompressed_group FROM state_compressor_total_progress)
AND (
id > last_compressed
OR last_compressed IS NULL
)
ORDER BY id ASC
LIMIT 1
"#;
let row_opt = client.query_opt(get_next_room, &[])?;
let next_room_row = if let Some(row) = row_opt {
row
} else {
return Ok(None);
};
let next_room: String = next_room_row.get("room_id");
let lowest_uncompressed_group: i64 = next_room_row.get("id");
// This method has determined where the lowest uncompressesed group is, save that
// information so we don't have to redo this work in the future.
let update_total_progress = r#"
UPDATE state_compressor_total_progress SET lowest_uncompressed_group = $1;
"#;
client.execute(update_total_progress, &[&lowest_uncompressed_group])?;
trace!(
"next_room: {}, lowest_uncompressed: {}",
next_room,
lowest_uncompressed_group
);
Ok(Some(next_room))
}
| true
|
1b77a3098f25f26a538503eea8882a86c50c2143
|
Rust
|
Byron/gitoxide
|
/gix-commitgraph/tests/access/mod.rs
|
UTF-8
| 4,094
| 2.546875
| 3
|
[
"MIT",
"Apache-2.0"
] |
permissive
|
use crate::{check_common, graph_and_expected, graph_and_expected_named};
#[test]
fn single_parent() {
let (cg, refs) = graph_and_expected("single_parent.sh", &["parent", "child"]);
check_common(&cg, &refs);
assert_eq!(cg.commit_at(refs["parent"].pos()).generation(), 1);
assert_eq!(cg.commit_at(refs["child"].pos()).generation(), 2);
}
#[test]
fn single_commit_huge_dates_generation_v2_also_do_not_allow_huge_dates() {
let (cg, refs) = graph_and_expected_named("single_commit_huge_dates.sh", "v2", &["HEAD"]);
let info = &refs["HEAD"];
let actual = cg.commit_by_id(info.id).expect("present");
assert_eq!(
actual.committer_timestamp(),
1,
"overflow happened, can't represent huge dates"
);
assert_eq!(
info.time.seconds, 68719476737,
"this is the value we would want to see, but it's not possible in V2 either, as that is just about generations"
);
assert_eq!(actual.generation(), 1, "generations are fine though");
}
#[test]
fn single_commit_huge_dates_overflow_v1() {
let (cg, refs) = graph_and_expected_named("single_commit_huge_dates.sh", "v1", &["HEAD"]);
let info = &refs["HEAD"];
let actual = cg.commit_by_id(info.id).expect("present");
assert_eq!(actual.committer_timestamp(), 1, "overflow happened");
assert_eq!(
info.time.seconds, 68719476737,
"this is the value we would want to see, but it's not possible in V1"
);
assert_eq!(actual.generation(), 1, "generations are fine though");
}
#[test]
fn single_commit_future_64bit_dates_work() {
let (cg, refs) = graph_and_expected_named("single_commit_huge_dates.sh", "max-date", &["HEAD"]);
let info = &refs["HEAD"];
let actual = cg.commit_by_id(info.id).expect("present");
assert_eq!(
actual.committer_timestamp(),
info.time.seconds.try_into().expect("timestamps in bound"),
"this is close the the highest representable value in the graph, like year 2500, so we are good for longer than I should care about"
);
assert_eq!(actual.generation(), 1);
}
#[test]
fn generation_numbers_overflow_is_handled_in_chained_graph() {
let names = ["extra", "old-2", "future-2", "old-1", "future-1"];
let (cg, mut refs) = graph_and_expected("generation_number_overflow.sh", &names);
for (r, expected) in names
.iter()
.map(|n| refs.remove(n.to_owned()).expect("present"))
.zip((1..=5).rev())
{
assert_eq!(
cg.commit_by_id(r.id).expect("present").generation(),
expected,
"actually, this test seems to have valid generation numbers from the get-go. How to repro the actual issue?"
);
}
}
#[test]
fn octupus_merges() {
let (cg, refs) = graph_and_expected(
"octopus_merges.sh",
&[
"root",
"parent1",
"parent2",
"parent3",
"parent4",
"three_parents",
"four_parents",
],
);
check_common(&cg, &refs);
assert_eq!(cg.commit_at(refs["root"].pos()).generation(), 1);
assert_eq!(cg.commit_at(refs["parent1"].pos()).generation(), 2);
assert_eq!(cg.commit_at(refs["parent2"].pos()).generation(), 2);
assert_eq!(cg.commit_at(refs["parent3"].pos()).generation(), 2);
assert_eq!(cg.commit_at(refs["parent4"].pos()).generation(), 2);
assert_eq!(cg.commit_at(refs["three_parents"].pos()).generation(), 3);
assert_eq!(cg.commit_at(refs["four_parents"].pos()).generation(), 3);
}
#[test]
fn single_commit() {
let (cg, refs) = graph_and_expected("single_commit.sh", &["commit"]);
check_common(&cg, &refs);
assert_eq!(cg.commit_at(refs["commit"].pos()).generation(), 1);
}
#[test]
fn two_parents() {
let (cg, refs) = graph_and_expected("two_parents.sh", &["parent1", "parent2", "child"]);
check_common(&cg, &refs);
assert_eq!(cg.commit_at(refs["parent1"].pos()).generation(), 1);
assert_eq!(cg.commit_at(refs["parent2"].pos()).generation(), 1);
assert_eq!(cg.commit_at(refs["child"].pos()).generation(), 2);
}
| true
|
cda3189282d0c104ceaa797c5859b454cd152abb
|
Rust
|
realbigsean/lighthouse
|
/consensus/tree_hash_derive/src/lib.rs
|
UTF-8
| 11,408
| 2.8125
| 3
|
[
"Apache-2.0"
] |
permissive
|
#![recursion_limit = "256"]
use darling::FromDeriveInput;
use proc_macro::TokenStream;
use quote::quote;
use std::convert::TryInto;
use syn::{parse_macro_input, Attribute, DataEnum, DataStruct, DeriveInput, Meta};
/// The highest possible union selector value (higher values are reserved for backwards compatible
/// extensions).
const MAX_UNION_SELECTOR: u8 = 127;
#[derive(Debug, FromDeriveInput)]
#[darling(attributes(tree_hash))]
struct StructOpts {
#[darling(default)]
enum_behaviour: Option<String>,
}
const ENUM_TRANSPARENT: &str = "transparent";
const ENUM_UNION: &str = "union";
const ENUM_VARIANTS: &[&str] = &[ENUM_TRANSPARENT, ENUM_UNION];
const NO_ENUM_BEHAVIOUR_ERROR: &str = "enums require an \"enum_behaviour\" attribute, \
e.g., #[tree_hash(enum_behaviour = \"transparent\")]";
enum EnumBehaviour {
Transparent,
Union,
}
impl EnumBehaviour {
pub fn new(s: Option<String>) -> Option<Self> {
s.map(|s| match s.as_ref() {
ENUM_TRANSPARENT => EnumBehaviour::Transparent,
ENUM_UNION => EnumBehaviour::Union,
other => panic!(
"{} is an invalid enum_behaviour, use either {:?}",
other, ENUM_VARIANTS
),
})
}
}
/// Return a Vec of `syn::Ident` for each named field in the struct, whilst filtering out fields
/// that should not be hashed.
///
/// # Panics
/// Any unnamed struct field (like in a tuple struct) will raise a panic at compile time.
fn get_hashable_fields(struct_data: &syn::DataStruct) -> Vec<&syn::Ident> {
get_hashable_fields_and_their_caches(struct_data)
.into_iter()
.map(|(ident, _, _)| ident)
.collect()
}
/// Return a Vec of the hashable fields of a struct, and each field's type and optional cache field.
fn get_hashable_fields_and_their_caches(
struct_data: &syn::DataStruct,
) -> Vec<(&syn::Ident, syn::Type, Option<syn::Ident>)> {
struct_data
.fields
.iter()
.filter_map(|f| {
if should_skip_hashing(f) {
None
} else {
let ident = f
.ident
.as_ref()
.expect("tree_hash_derive only supports named struct fields");
let opt_cache_field = get_cache_field_for(f);
Some((ident, f.ty.clone(), opt_cache_field))
}
})
.collect()
}
/// Parse the cached_tree_hash attribute for a field.
///
/// Extract the cache field name from `#[cached_tree_hash(cache_field_name)]`
///
/// Return `Some(cache_field_name)` if the field has a cached tree hash attribute,
/// or `None` otherwise.
fn get_cache_field_for(field: &syn::Field) -> Option<syn::Ident> {
use syn::{MetaList, NestedMeta};
let parsed_attrs = cached_tree_hash_attr_metas(&field.attrs);
if let [Meta::List(MetaList { nested, .. })] = &parsed_attrs[..] {
nested.iter().find_map(|x| match x {
NestedMeta::Meta(Meta::Path(path)) => path.get_ident().cloned(),
_ => None,
})
} else {
None
}
}
/// Process the `cached_tree_hash` attributes from a list of attributes into structured `Meta`s.
fn cached_tree_hash_attr_metas(attrs: &[Attribute]) -> Vec<Meta> {
attrs
.iter()
.filter(|attr| attr.path.is_ident("cached_tree_hash"))
.flat_map(|attr| attr.parse_meta())
.collect()
}
/// Returns true if some field has an attribute declaring it should not be hashed.
///
/// The field attribute is: `#[tree_hash(skip_hashing)]`
fn should_skip_hashing(field: &syn::Field) -> bool {
field.attrs.iter().any(|attr| {
attr.path.is_ident("tree_hash")
&& attr.tokens.to_string().replace(" ", "") == "(skip_hashing)"
})
}
/// Implements `tree_hash::TreeHash` for some `struct`.
///
/// Fields are hashed in the order they are defined.
#[proc_macro_derive(TreeHash, attributes(tree_hash))]
pub fn tree_hash_derive(input: TokenStream) -> TokenStream {
let item = parse_macro_input!(input as DeriveInput);
let opts = StructOpts::from_derive_input(&item).unwrap();
let enum_opt = EnumBehaviour::new(opts.enum_behaviour);
match &item.data {
syn::Data::Struct(s) => {
if enum_opt.is_some() {
panic!("enum_behaviour is invalid for structs");
}
tree_hash_derive_struct(&item, s)
}
syn::Data::Enum(s) => match enum_opt.expect(NO_ENUM_BEHAVIOUR_ERROR) {
EnumBehaviour::Transparent => tree_hash_derive_enum_transparent(&item, s),
EnumBehaviour::Union => tree_hash_derive_enum_union(&item, s),
},
_ => panic!("tree_hash_derive only supports structs and enums."),
}
}
fn tree_hash_derive_struct(item: &DeriveInput, struct_data: &DataStruct) -> TokenStream {
let name = &item.ident;
let (impl_generics, ty_generics, where_clause) = &item.generics.split_for_impl();
let idents = get_hashable_fields(struct_data);
let num_leaves = idents.len();
let output = quote! {
impl #impl_generics tree_hash::TreeHash for #name #ty_generics #where_clause {
fn tree_hash_type() -> tree_hash::TreeHashType {
tree_hash::TreeHashType::Container
}
fn tree_hash_packed_encoding(&self) -> Vec<u8> {
unreachable!("Struct should never be packed.")
}
fn tree_hash_packing_factor() -> usize {
unreachable!("Struct should never be packed.")
}
fn tree_hash_root(&self) -> tree_hash::Hash256 {
let mut hasher = tree_hash::MerkleHasher::with_leaves(#num_leaves);
#(
hasher.write(self.#idents.tree_hash_root().as_bytes())
.expect("tree hash derive should not apply too many leaves");
)*
hasher.finish().expect("tree hash derive should not have a remaining buffer")
}
}
};
output.into()
}
/// Derive `TreeHash` for an enum in the "transparent" method.
///
/// The "transparent" method is distinct from the "union" method specified in the SSZ specification.
/// When using "transparent", the enum will be ignored and the contained field will be hashed as if
/// the enum does not exist.
///
///## Limitations
///
/// Only supports:
/// - Enums with a single field per variant, where
/// - All fields are "container" types.
///
/// ## Panics
///
/// Will panic at compile-time if the single field requirement isn't met, but will panic *at run
/// time* if the container type requirement isn't met.
fn tree_hash_derive_enum_transparent(
derive_input: &DeriveInput,
enum_data: &DataEnum,
) -> TokenStream {
let name = &derive_input.ident;
let (impl_generics, ty_generics, where_clause) = &derive_input.generics.split_for_impl();
let (patterns, type_exprs): (Vec<_>, Vec<_>) = enum_data
.variants
.iter()
.map(|variant| {
let variant_name = &variant.ident;
if variant.fields.len() != 1 {
panic!("TreeHash can only be derived for enums with 1 field per variant");
}
let pattern = quote! {
#name::#variant_name(ref inner)
};
let ty = &(&variant.fields).into_iter().next().unwrap().ty;
let type_expr = quote! {
<#ty as tree_hash::TreeHash>::tree_hash_type()
};
(pattern, type_expr)
})
.unzip();
let output = quote! {
impl #impl_generics tree_hash::TreeHash for #name #ty_generics #where_clause {
fn tree_hash_type() -> tree_hash::TreeHashType {
#(
assert_eq!(
#type_exprs,
tree_hash::TreeHashType::Container,
"all variants must be of container type"
);
)*
tree_hash::TreeHashType::Container
}
fn tree_hash_packed_encoding(&self) -> Vec<u8> {
unreachable!("Enum should never be packed")
}
fn tree_hash_packing_factor() -> usize {
unreachable!("Enum should never be packed")
}
fn tree_hash_root(&self) -> tree_hash::Hash256 {
match self {
#(
#patterns => inner.tree_hash_root(),
)*
}
}
}
};
output.into()
}
/// Derive `TreeHash` for an `enum` following the "union" SSZ spec.
///
/// The union selector will be determined based upon the order in which the enum variants are
/// defined. E.g., the top-most variant in the enum will have a selector of `0`, the variant
/// beneath it will have a selector of `1` and so on.
///
/// # Limitations
///
/// Only supports enums where each variant has a single field.
fn tree_hash_derive_enum_union(derive_input: &DeriveInput, enum_data: &DataEnum) -> TokenStream {
let name = &derive_input.ident;
let (impl_generics, ty_generics, where_clause) = &derive_input.generics.split_for_impl();
let patterns: Vec<_> = enum_data
.variants
.iter()
.map(|variant| {
let variant_name = &variant.ident;
if variant.fields.len() != 1 {
panic!("TreeHash can only be derived for enums with 1 field per variant");
}
quote! {
#name::#variant_name(ref inner)
}
})
.collect();
let union_selectors = compute_union_selectors(patterns.len());
let output = quote! {
impl #impl_generics tree_hash::TreeHash for #name #ty_generics #where_clause {
fn tree_hash_type() -> tree_hash::TreeHashType {
tree_hash::TreeHashType::Container
}
fn tree_hash_packed_encoding(&self) -> Vec<u8> {
unreachable!("Enum should never be packed")
}
fn tree_hash_packing_factor() -> usize {
unreachable!("Enum should never be packed")
}
fn tree_hash_root(&self) -> tree_hash::Hash256 {
match self {
#(
#patterns => {
let root = inner.tree_hash_root();
let selector = #union_selectors;
tree_hash::mix_in_selector(&root, selector)
.expect("derive macro should prevent out-of-bounds selectors")
},
)*
}
}
}
};
output.into()
}
fn compute_union_selectors(num_variants: usize) -> Vec<u8> {
let union_selectors = (0..num_variants)
.map(|i| {
i.try_into()
.expect("union selector exceeds u8::max_value, union has too many variants")
})
.collect::<Vec<u8>>();
let highest_selector = union_selectors
.last()
.copied()
.expect("0-variant union is not permitted");
assert!(
highest_selector <= MAX_UNION_SELECTOR,
"union selector {} exceeds limit of {}, enum has too many variants",
highest_selector,
MAX_UNION_SELECTOR
);
union_selectors
}
| true
|
6ea1227eb6f19c3c5ba49f43baf74b8ca8989e90
|
Rust
|
johan-sun/hackerrank-rust
|
/Algorithms/Warmup/Diagonal-Difference.rs
|
UTF-8
| 875
| 2.84375
| 3
|
[] |
no_license
|
use std::prelude::v1::*;
use std::io::prelude::*;
fn main() {
let stdin = std::io::stdin();
let stdin = stdin.lock();
let mut lines = stdin.lines();
while let Some(Ok(n)) = lines.by_ref().next() {
let n : usize = n.parse().expect("not a number");
let mut i = 0;
let mut sum1 = 0i32;
let mut sum2 = 0i32;
for line in lines.by_ref().take(n) {
let line :String = line.expect("IO error");
let nums1 = line.split_whitespace().map(|x| x.trim().parse::<i32>().expect("not a number"));
let nums2 = line.split_whitespace().map(|x| x.trim().parse::<i32>().expect("not a number"));
sum1 += nums1.skip(i).next().expect("too less");
sum2 += nums2.rev().skip(i).next().expect("too less");
i += 1;
}
println!("{}", (sum1 - sum2).abs());
}
}
| true
|
86c7778ab3d27feb9121754632d2ae2f8606ac46
|
Rust
|
entrpntr/mon-tas-gen
|
/src/multi/plan/namingscreen.rs
|
UTF-8
| 7,089
| 2.609375
| 3
|
[] |
no_license
|
use serde_derive::{Serialize, Deserialize};
use std::cmp::Ordering;
use crate::metric::*;
use crate::multi::*;
use crate::rom::*;
use gambatte::inputs::*;
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct NamingScreenPlanState {
letter_progress: u8,
delta: (i8, i8),
pressed_input_state: PressedInputState,
}
impl PartialOrd for NamingScreenPlanState {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
if self.letter_progress != other.letter_progress {
self.letter_progress.partial_cmp(&other.letter_progress)
} else {
(other.delta.0.abs() + other.delta.1.abs()).partial_cmp(&(self.delta.0.abs() + self.delta.1.abs()))
}
}
}
impl PartialEq for NamingScreenPlanState {
fn eq(&self, other: &Self) -> bool {
self.partial_cmp(other) == Some(Ordering::Equal)
}
}
// Plan to progress DisplayNamingScreen inputs, entering single-letter names
pub struct NamingScreenPlan<M> {
// instance state
pressed_input_state: PressedInputState,
delta: (i8, i8),
letter_progress: u8,
// config state
initial_delta: (i8, i8),
fill_letter_count: u8,
metric: M,
}
impl NamingScreenPlan<NullMetric> {
pub fn with_letter(letter: u8) -> Self { Self::with_metric(letter, NullMetric) }
}
impl<M> NamingScreenPlan<M> {
pub fn with_metric(letter: u8, metric: M) -> Self {
assert!(letter >= b'A' && letter <= b'Z');
let letter_offset = (letter - b'A') as i8;
let dx = (letter_offset + 4) % 9 - 4;
let dy = letter_offset / 9;
Self {
// Set instance state to dummy values, will be initialize()'d later.
pressed_input_state: PressedInputState::unknown(),
delta: (dx, dy),
letter_progress: 0,
// Default config state.
initial_delta: (dx, dy),
fill_letter_count: 1,
metric,
}
}
pub fn with_fill_letters(self, fill_letter_count: u8) -> Self { Self { fill_letter_count, ..self }} // Add and remove fill letters, useful for Yellow rival to save frames on Pikachu encounter.
}
impl<R: Rom + JoypadLowSensitivityAddresses, M: Metric<R>> Plan<R> for NamingScreenPlan<M> {
type Value = M::ValueType;
fn save(&self) -> PlanState {
PlanState::NamingScreenState(NamingScreenPlanState { letter_progress: self.letter_progress, delta: self.delta, pressed_input_state: self.pressed_input_state })
}
fn restore(&mut self, state: &PlanState) {
if let PlanState::NamingScreenState(NamingScreenPlanState { letter_progress, delta, pressed_input_state }) = state {
self.letter_progress = *letter_progress;
self.delta = *delta;
self.pressed_input_state = *pressed_input_state;
} else { panic!("Loading incompatible plan state {:?}", state); }
}
fn initialize(&mut self, gb: &mut Gb<R>, state: &GbState) {
self.letter_progress = 0;
self.delta = self.initial_delta;
self.pressed_input_state = PressedInputState::from_gb_state(gb, state);
}
fn is_safe(&self) -> bool { true }
fn get_blockable_inputs(&self) -> Input {
if self.letter_progress == 2 * self.fill_letter_count - 1 { START }
else if self.letter_progress >= self.fill_letter_count { B }
else if self.letter_progress >= 1 { A }
else if self.delta.0 == 0 && self.delta.1 == 0 { A }
else {
let mut blocked_inputs = Input::empty();
if self.delta.0 > 0 { blocked_inputs |= R; }
if self.delta.0 < 0 { blocked_inputs |= L; }
if self.delta.1 > 0 { blocked_inputs |= D; }
if self.delta.1 < 0 { blocked_inputs |= U; }
blocked_inputs
}
}
fn canonicalize_input(&self, input: Input) -> Option<Input> {
let input = self.pressed_input_state.get_pressed_input(input);
if input.contains(D) {
if self.letter_progress >= 1 { Some(Input::empty()) } else if self.delta.1 > 0 { Some(D) }else { None }
} else if input.contains(U) {
if self.letter_progress >= 1 { Some(Input::empty()) } else if self.delta.1 < 0 { Some(U) } else { None }
} else if input.contains(L) {
if self.letter_progress >= 1 { Some(Input::empty()) } else if self.delta.0 < 0 { Some(L) } else { None }
} else if input.contains(R) {
if self.letter_progress >= 1 { Some(Input::empty()) } else if self.delta.0 > 0 { Some(R) } else { None }
} else if input.contains(START) {
if self.letter_progress == 2 * self.fill_letter_count - 1 { Some(START) } else { None }
} else if input.contains(SELECT) {
if self.letter_progress >= 1 { Some(Input::empty()) } else { None }
} else if input.contains(B) {
if self.letter_progress < 2 * self.fill_letter_count - 1 && self.letter_progress >= self.fill_letter_count { Some(B) } else if self.letter_progress >= 1 { None } else { Some(Input::empty()) }
} else if input.contains(A) {
if self.letter_progress >= self.fill_letter_count { None } else if self.letter_progress == 0 && self.delta != (0, 0) { None } else { Some(A) }
} else { Some(Input::empty()) }
}
fn execute_input(&mut self, gb: &mut Gb<R>, s: &GbState, input: Input) -> Option<(GbState, Option<M::ValueType>)> {
let pressed = self.pressed_input_state.get_pressed_input(input);
let mut is_done = false;
let mut delay = false;
if pressed.contains(D) {
if self.letter_progress >= 1 { delay = true; } else if self.delta.1 > 0 { self.delta = (self.delta.0, self.delta.1 - 1) } else { return None; }
} else if pressed.contains(U) {
if self.letter_progress >= 1 { delay = true; } else if self.delta.1 < 0 { self.delta = (self.delta.0, self.delta.1 + 1) } else { return None; }
} else if pressed.contains(L) {
if self.letter_progress >= 1 { delay = true; } else if self.delta.0 < 0 { self.delta = (self.delta.0 + 1, self.delta.1) } else { return None; }
} else if pressed.contains(R) {
if self.letter_progress >= 1 { delay = true; } else if self.delta.0 > 0 { self.delta = (self.delta.0 - 1, self.delta.1) } else { return None; }
} else if pressed.contains(START) {
if self.letter_progress == 2 * self.fill_letter_count - 1 { is_done = true; } else { return None; }
} else if pressed.contains(SELECT) {
if self.letter_progress >= 1 { delay = true; } else { return None; }
} else if pressed.contains(B) {
if self.letter_progress < 2 * self.fill_letter_count - 1 && self.letter_progress >= self.fill_letter_count { self.letter_progress += 1; } else if self.letter_progress >= 1 { return None; } else { delay = true; }
} else if pressed.contains(A) {
if self.letter_progress >= self.fill_letter_count { return None; } else if self.letter_progress == 0 && self.delta != (0, 0) { return None; } else { self.letter_progress += 1; }
} else { delay = true; }
gb.restore(s);
gb.input(input);
if is_done {
if let Some(metric_value) = self.metric.evaluate(gb) {
gb.step();
return Some((gb.save(), Some(metric_value)));
} else { return None; }
}
if delay {
gb.delay_step();
} else {
gb.step();
}
let new_state = gb.save();
self.pressed_input_state = PressedInputState::from_gb(gb);
Some((new_state, None))
}
}
| true
|
838c8aff444d5663e062292198043bf039594026
|
Rust
|
DataDog/glommio
|
/glommio/src/io/read_result.rs
|
UTF-8
| 5,494
| 2.890625
| 3
|
[
"MIT",
"Apache-2.0"
] |
permissive
|
// unless explicitly stated otherwise all files in this repository are licensed
// under the mit/apache-2.0 license, at your convenience
//
// this product includes software developed at datadog (https://www.datadoghq.com/). copyright 2020 datadog, inc.
use crate::io::ScheduledSource;
use std::{num::NonZeroUsize, ptr::NonNull};
#[derive(Default, Clone, Debug)]
/// ReadResult encapsulates a buffer, returned by read operations like
/// [`get_buffer_aligned`](super::DmaStreamReader::get_buffer_aligned) and
/// [`read_at`](super::DmaFile::read_at)
pub struct ReadResult(Option<ReadResultInner>);
impl core::ops::Deref for ReadResult {
type Target = [u8];
/// Allows accessing the contents of this buffer as a byte slice
fn deref(&self) -> &[u8] {
self.0.as_deref().unwrap_or(&[])
}
}
#[derive(Clone, Debug)]
struct ReadResultInner {
buffer: ScheduledSource,
mem: NonNull<u8>,
// This (usage of `NonZeroUsize`) is probably needed to make sure that rustc
// doesn't need to reserve additional memory for the surrounding Option enum tag.
// see also `self::test::equal_struct_size`
//
// The additionally `ReadResultInner` structure is a good idea as it allows
// a cleaner implementation (offset and end/len don't have any meaning if buffer.is_none()).
len: NonZeroUsize,
}
impl core::ops::Deref for ReadResultInner {
type Target = [u8];
fn deref(&self) -> &[u8] {
unsafe { std::slice::from_raw_parts(self.mem.as_ptr(), self.len.get()) }
}
}
impl ReadResult {
pub(crate) fn empty_buffer() -> Self {
Self(None)
}
pub(crate) fn from_sliced_buffer(buffer: ScheduledSource, offset: usize, len: usize) -> Self {
Self(
NonZeroUsize::new(len)
.map(|len| unsafe {
NonNull::new(buffer.as_bytes().as_ptr() as *mut u8).map(|ptr| {
let mem = NonNull::new_unchecked(ptr.as_ptr().add(offset));
let ret = ReadResultInner { buffer, mem, len };
ReadResultInner::check_invariants(&ret);
ret
})
})
.unwrap_or(None),
)
}
/// Creates a slice of this ReadResult with the given offset and length.
///
/// Returns `None` if either offset or offset + len would not fit in the
/// original buffer.
pub fn slice(this: &Self, extra_offset: usize, len: usize) -> Option<Self> {
Some(Self(if let Some(len) = NonZeroUsize::new(len) {
Some(ReadResultInner::slice(this.0.as_ref()?, extra_offset, len)?)
} else {
// This branch is needed to make sure that calls to `slice` with `len = 0` are
// handled. If they aren't valid, then `len` should be changed to
// `NonZeroUsize`.
None
}))
}
/// Creates a slice of this ReadResult with the given offset and length.
/// Similar to [`ReadResult::slice`], but does not check if the offset and
/// length are correct.
///
/// # Safety
///
/// Any user of this function must guarantee that the offset and length are
/// correct (not out of bounds).
pub unsafe fn slice_unchecked(this: &Self, extra_offset: usize, len: usize) -> Self {
Self(NonZeroUsize::new(len).map(|len| {
ReadResultInner::slice_unchecked(this.0.as_ref().unwrap(), extra_offset, len)
}))
}
}
impl ReadResultInner {
fn check_invariants(this: &Self) {
unsafe {
debug_assert!(
this.mem.as_ptr().add(this.len.get() - 1) as *const u8
<= this.buffer.as_bytes().last().unwrap() as *const u8,
"a ReadResult contains an out-of-range 'end': offset ({:?} + {}) > {:?} buffer \
length ({})",
this.mem,
this.len,
this.buffer.as_bytes().last().unwrap() as *const u8,
this.buffer.as_bytes().len(),
);
}
}
fn slice(this: &Self, extra_offset: usize, len: NonZeroUsize) -> Option<Self> {
Self::check_invariants(this);
if extra_offset > this.len.get() || len.get() > (this.len.get() - extra_offset) {
None
} else {
unsafe {
Some(ReadResultInner {
buffer: this.buffer.clone(),
mem: NonNull::new_unchecked(this.mem.as_ptr().add(extra_offset)),
len,
})
}
}
}
unsafe fn slice_unchecked(this: &Self, extra_offset: usize, len: NonZeroUsize) -> Self {
Self::check_invariants(this);
debug_assert!(
extra_offset <= this.len.get(),
"offset {} is more than the length ({}) of the slice",
extra_offset,
this.len,
);
debug_assert!(
len.get() <= (this.len.get() - extra_offset),
"length {} would cross past the end ({}) of the slice",
len.get() + extra_offset,
this.len,
);
ReadResultInner {
buffer: this.buffer.clone(),
mem: NonNull::new_unchecked(this.mem.as_ptr().add(extra_offset)),
len,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn equal_struct_size() {
use core::mem::size_of;
assert_eq!(size_of::<ReadResult>(), size_of::<ReadResultInner>());
}
}
| true
|
01d50809e381740783a299240e54972c79fe84dd
|
Rust
|
fengkx/leetcode
|
/count-and-say/src/lib.rs
|
UTF-8
| 1,834
| 4.15625
| 4
|
[
"Unlicense"
] |
permissive
|
struct Solution;
impl Solution {
pub fn count_and_say(n: i32) -> String {
if n <= 1 {
return "1".to_string();
}
Self::count_and_say_string(Self::count_and_say(n - 1).as_ref())
}
fn count_and_say_string(n: &str) -> String {
if n.is_empty() {
return "1".to_string();
}
let mut result = String::new();
let len = n.len();
let mut i = 0;
while i < len {
let cur = n.chars().nth(i).unwrap();
let mut cnt = 0;
while i < len && n.chars().nth(i).unwrap() == cur {
i += 1;
cnt += 1;
}
result.push_str(&format!("{}{}", cnt, cur));
}
result
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_count_and_say() {
let test_cases = vec![(1, "1"), (2, "11"), (3, "21"), (4, "1211"), (5, "111221")];
for (n, expected) in test_cases {
assert_eq!(Solution::count_and_say(n), expected.to_string());
}
}
#[test]
fn test_count_and_say_string() {
assert_eq!(
Solution::count_and_say_string("11223"),
"212213".to_string()
);
assert_eq!(
Solution::count_and_say_string("3322251"),
"23321511".to_string()
);
}
#[test]
fn test_additional_cases() {
assert_eq!(Solution::count_and_say(2), "11".to_string());
assert_eq!(Solution::count_and_say_string("1"), "11".to_string());
assert_eq!(Solution::count_and_say_string("11"), "21".to_string());
assert_eq!(Solution::count_and_say(3), "21".to_string());
assert_eq!(Solution::count_and_say(4), "1211".to_string());
assert_eq!(Solution::count_and_say(5), "111221".to_string());
}
}
| true
|
7295ef3e0209876ba084159cd990ce2980d176e6
|
Rust
|
brockelmore/ethabi
|
/ethabi/src/param_type/deserialize.rs
|
UTF-8
| 1,999
| 2.75
| 3
|
[
"Apache-2.0"
] |
permissive
|
// Copyright 2015-2020 Parity Technologies
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use super::{ParamType, Reader};
use serde::{
de::{Error as SerdeError, Visitor},
Deserialize, Deserializer,
};
use std::fmt;
impl<'a> Deserialize<'a> for ParamType {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'a>,
{
deserializer.deserialize_identifier(ParamTypeVisitor)
}
}
struct ParamTypeVisitor;
impl<'a> Visitor<'a> for ParamTypeVisitor {
type Value = ParamType;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(formatter, "a correct name of abi-encodable parameter type")
}
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
where
E: SerdeError,
{
Reader::read(value).map_err(|e| SerdeError::custom(format!("{:?}", e).as_str()))
}
fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
where
E: SerdeError,
{
self.visit_str(value.as_str())
}
}
#[cfg(test)]
mod tests {
use crate::ParamType;
#[test]
fn param_type_deserialization() {
let s = r#"["address", "bytes", "bytes32", "bool", "string", "int", "uint", "address[]", "uint[3]", "bool[][5]", "tuple[]"]"#;
let deserialized: Vec<ParamType> = serde_json::from_str(s).unwrap();
assert_eq!(
deserialized,
vec![
ParamType::Address,
ParamType::Bytes,
ParamType::FixedBytes(32),
ParamType::Bool,
ParamType::String,
ParamType::Int(256),
ParamType::Uint(256),
ParamType::Array(Box::new(ParamType::Address)),
ParamType::FixedArray(Box::new(ParamType::Uint(256)), 3),
ParamType::FixedArray(Box::new(ParamType::Array(Box::new(ParamType::Bool))), 5),
ParamType::Array(Box::new(ParamType::Tuple(vec![]))),
]
);
}
}
| true
|
5e2d044148df71a977a063aa7d7bc7fe20641aa6
|
Rust
|
lucabecci/Rust-learning
|
/src/week1/primitives/tuples.rs
|
UTF-8
| 523
| 3.734375
| 4
|
[] |
no_license
|
fn reverse(pair: (i32, bool)) -> (bool, i32){
let (integer, boolean) = pair;
(boolean, integer)
}
#[derive(Debug)]
struct Arr(u8, u8, u8);
fn Tuples(){
let long_tuples = ((22, 44, 66, 88), (-22, -11, -1), 0);
println!("long tuple: {:?}", long_tuples);
//use a function reverse for reverse my next variable
let pair = (3, false);
println!("now pair is: {:?}", pair);
println!("the reversed pair is {:?}", reverse(pair));
let arr = Arr(1,2,3);
println!("My arr has: {:?}", arr)
}
| true
|
87a6dcdf590e370355ef27a1c379fdcbd0672e84
|
Rust
|
michelleN/bindle
|
/src/search/strict.rs
|
UTF-8
| 6,331
| 3.28125
| 3
|
[
"Apache-2.0"
] |
permissive
|
//! A strict query engine implementation. It always expects a strict match of query terms
use std::collections::BTreeMap;
use std::ops::RangeInclusive;
use std::sync::Arc;
use tokio::sync::RwLock;
use tracing::{debug, instrument, trace};
use crate::search::{Matches, Search, SearchOptions};
/// Implements strict query processing.
#[derive(Clone)]
pub struct StrictEngine {
// A BTreeMap will keep the records in a predictable order, which makes the
// search results predictable. This greatly simplifies the process of doing offsets
// and limits.
index: Arc<RwLock<BTreeMap<String, crate::Invoice>>>,
}
impl Default for StrictEngine {
fn default() -> Self {
StrictEngine {
index: Arc::new(RwLock::new(BTreeMap::new())),
}
}
}
#[async_trait::async_trait]
impl Search for StrictEngine {
#[instrument(level = "trace", skip(self))]
async fn query(
&self,
term: &str,
filter: &str,
options: SearchOptions,
) -> anyhow::Result<Matches> {
trace!("beginning search");
let mut found: Vec<crate::Invoice> = self
.index
.read()
.await
.iter()
.filter(|(_, i)| {
// Per the spec:
// - if `term` is present, then it must be contained within the name field of the bindle.
// - if a version filter is present, then the version of the bindle must abide by the filter.
debug!(term, filter, "comparing term and filter");
i.bindle.id.name().contains(term)
&& (filter.is_empty() || i.version_in_range(filter))
})
.map(|(_, v)| (*v).clone())
.collect();
debug!(total_matches = found.len(), "Found matches");
let mut matches = Matches::new(&options, term.to_owned());
matches.strict = true;
matches.yanked = false;
matches.total = found.len() as u64;
if matches.offset >= matches.total {
// We're past the end of the search results. Return an empty matches object.
matches.more = false;
return Ok(matches);
}
// Apply offset and limit
let mut last_index = matches.offset + matches.limit as u64 - 1;
if last_index >= matches.total {
last_index = matches.total - 1;
}
matches.more = matches.total > last_index + 1;
trace!(last_index, matches.more, "Getting next page of results");
let range = RangeInclusive::new(matches.offset as usize, last_index as usize);
matches.invoices = found.drain(range).collect();
trace!("Returning {} found invoices", matches.invoices.len());
Ok(matches)
}
async fn index(&self, invoice: &crate::Invoice) -> anyhow::Result<()> {
self.index
.write()
.await
.insert(invoice.name(), invoice.clone());
Ok(())
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::Invoice;
#[tokio::test]
async fn strict_engine_should_index() {
let inv = invoice_fixture("my/bindle".to_owned(), "1.2.3".to_owned());
let inv2 = invoice_fixture("my/bindle".to_owned(), "1.3.0".to_owned());
let searcher = StrictEngine::default();
searcher
.index(&inv)
.await
.expect("succesfully indexed my/bindle/1.2.3");
searcher
.index(&inv2)
.await
.expect("succesfully indexed my/bindle/1.3.0");
assert_eq!(2, searcher.index.read().await.len());
// Search for one result
let matches = searcher
.query("my/bindle", "1.2.3", SearchOptions::default())
.await
.expect("found some matches");
assert_eq!(1, matches.invoices.len());
// Search for two results
let matches = searcher
.query("my/bindle", "^1.2.3", SearchOptions::default())
.await
.expect("found some matches");
assert_eq!(2, matches.invoices.len());
// Search for non-existant bindle
let matches = searcher
.query("my/bindle2", "1.2.3", SearchOptions::default())
.await
.expect("found some matches");
assert!(matches.invoices.is_empty());
// Search for non-existant version
let matches = searcher
.query("my/bindle", "1.2.99", SearchOptions::default())
.await
.expect("found some matches");
assert!(matches.invoices.is_empty());
// TODO: Need to test yanked bindles
}
fn invoice_fixture(name: String, version: String) -> Invoice {
let labels = vec![
crate::Label {
sha256: "abcdef1234567890987654321".to_owned(),
media_type: "text/toml".to_owned(),
name: "foo.toml".to_owned(),
size: 101,
..Default::default()
},
crate::Label {
sha256: "bbcdef1234567890987654321".to_owned(),
media_type: "text/toml".to_owned(),
name: "foo2.toml".to_owned(),
size: 101,
..Default::default()
},
crate::Label {
sha256: "cbcdef1234567890987654321".to_owned(),
media_type: "text/toml".to_owned(),
name: "foo3.toml".to_owned(),
size: 101,
..Default::default()
},
];
Invoice {
bindle_version: crate::BINDLE_VERSION_1.to_owned(),
yanked: None,
yanked_signature: None,
annotations: None,
bindle: crate::BindleSpec {
id: format!("{}/{}", name, version).parse().unwrap(),
description: Some("bar".to_owned()),
authors: Some(vec!["m butcher".to_owned()]),
},
parcel: Some(
labels
.iter()
.map(|l| crate::Parcel {
label: l.clone(),
conditions: None,
})
.collect(),
),
group: None,
signature: None,
}
}
}
| true
|
6acff59c27ceb4da859f04a47359e1edb95f1100
|
Rust
|
costa-wang/rust-practice
|
/practice-collection/lifecycle/generic_ref_lifecycle/src/main.rs
|
UTF-8
| 482
| 3.59375
| 4
|
[] |
no_license
|
// 微信文章:Rust生命周期bound用于泛型的引用
trait Print {
fn output(&self);
}
struct Inner<'a>{
data: &'a i32,
}
impl<'a> Print for Inner<'a> {
fn output(&self) {
println!("Inner data: {}", self.data);
}
}
// 通过trait解耦
struct Outer<'b, T: 'b + Print> {
pub inner: &'b T,
}
fn main() {
let data = 10;
{
let a = Inner{ data: &data };
let outer = Outer{ inner: &a };
outer.inner.output();
}
}
| true
|
ad109160f25011033fa0df46b34f9ddd7784c9d4
|
Rust
|
dannywillems/web-ocaml-rust-tuto
|
/002-basic-typed-values/rust/src/lib.rs
|
UTF-8
| 2,040
| 2.640625
| 3
|
[] |
no_license
|
use rand::Rng;
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
extern "C" {
#[wasm_bindgen(js_namespace = console)]
fn log(s: &str);
}
#[wasm_bindgen]
pub fn get_bool_true() -> bool {
true
}
#[wasm_bindgen]
pub fn get_bool_false() -> bool {
false
}
#[wasm_bindgen]
pub fn get_uint32_zero() -> u32 {
0
}
#[wasm_bindgen]
pub fn get_uint16_random() -> u16 {
let mut rng = rand::thread_rng();
rng.gen::<u16>()
}
#[wasm_bindgen]
pub fn get_uint16_zero() -> u16 {
0
}
#[wasm_bindgen]
pub fn get_uint32_random() -> u32 {
let mut rng = rand::thread_rng();
rng.gen::<u32>()
}
#[wasm_bindgen]
pub fn get_int32_zero() -> i32 {
0
}
#[wasm_bindgen]
pub fn get_int32_random() -> i32 {
let mut rng = rand::thread_rng();
rng.gen::<i32>()
}
#[wasm_bindgen]
pub fn get_int64_zero() -> i64 {
0
}
#[wasm_bindgen]
pub fn get_int64_random() -> i64 {
let mut rng = rand::thread_rng();
rng.gen::<i64>()
}
#[wasm_bindgen]
pub fn get_uint64_random() -> u64 {
let mut rng = rand::thread_rng();
rng.gen::<u64>()
}
#[wasm_bindgen]
pub fn get_uint64_max() -> u64 {
std::u64::MAX
}
#[wasm_bindgen]
pub fn get_u8_random() -> u8 {
let mut rng = rand::thread_rng();
let x = rng.gen::<u8>();
x
}
#[wasm_bindgen]
pub fn get_usize_random() -> usize {
let mut rng = rand::thread_rng();
let x = rng.gen::<usize>();
x
}
#[wasm_bindgen]
pub fn get_usize_min() -> usize {
std::usize::MIN
}
#[wasm_bindgen]
pub fn get_usize_max() -> usize {
// !! usize is on 32 bits when compiled with wasm32-unknown-unknown
// wasm is only specified for 32 bits.
std::usize::MAX
}
#[wasm_bindgen]
pub fn get_option_int64_null() -> Option<i64> {
// !! usize is on 32 bits when compiled with wasm32-unknown-unknown
// wasm is only specified for 32 bits.
None
}
#[wasm_bindgen]
pub fn get_option_int64_some() -> Option<i64> {
// !! usize is on 32 bits when compiled with wasm32-unknown-unknown
// wasm is only specified for 32 bits.
Some(42)
}
| true
|
c640f5560041a240ecea15ecd4408c05d359b922
|
Rust
|
pierreyoda/rustboycolor
|
/src/gpu/tile.rs
|
UTF-8
| 3,914
| 3.484375
| 3
|
[
"MIT"
] |
permissive
|
/// A tile is an area of 8x8 pixels.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct Tile {
/// Each tile occupies 16 bytes, where 2 bytes represent a line:
/// byte 0-1 = first line (upper 8 pixels)
/// byte 2-3 = second lines
/// etc.
///
/// For each line, the first byte defines the bit 0 of the color numbers
/// and the second byte defines the bit 1. In both cases, bit 7 is the
/// leftmost pixel and bit 0 the rightmost.
///
/// Each pixel thus has a color number from 0 to 3 which is translated into
/// colors or shades of gray according to the current palettes.
raw_data: [u8; 16],
/// Cached internal state, better suited for rendering.
///
/// First index is Y coordinate, second index is X coordinate.
data: [[u8; 8]; 8],
}
impl Tile {
pub fn new(raw_data: [u8; 16]) -> Tile {
let mut new_tile = Tile {
raw_data,
data: [[0x00; 8]; 8],
};
new_tile.cache();
new_tile
}
pub fn raw_byte(&self, index: usize) -> u8 {
self.raw_data[index]
}
pub fn update_raw_byte(&mut self, index: usize, byte: u8) {
self.raw_data[index] = byte;
self.cache();
}
/// Update the tile's internal state to match its raw value.
fn cache(&mut self) {
for y in 0..8 {
let line_lo = self.raw_data[y * 2];
let line_hi = self.raw_data[y * 2 + 1];
for x in 0..8 {
let color = ((line_hi >> (7 - x)) & 0x01) << 1 | ((line_lo >> (7 - x)) & 0x01);
debug_assert!(color < 4);
self.data[y][x] = color;
}
}
}
pub fn data(&self) -> &[[u8; 8]; 8] {
&self.data
}
}
#[cfg(test)]
mod test {
use super::Tile;
#[test]
fn test_tile_cache() {
// Source for the Tile example: http://fms.komkon.org/GameBoy/Tech/Software.html
// .33333.. .33333.. -> 0b0111_1100 -> 0x7C
// 22...22. 0b0111_1100 -> 0x7C
// 11...11. 22...22. -> 0b0000_0000 -> 0x00
// 2222222. 0b1100_0110 -> 0xC6
// 33...33. 11...11. -> 0b1100_0110 -> 0xC6
// 22...22. 0b0000_0000 -> 0x00
// 11...11. 2222222. -> 0b0000_0000 -> 0x00
// ........ 0b1111_1110 -> 0xFE
// 33...33. -> 0b1100_0110 -> 0xC6
// 0b1100_0110 -> 0xC6
// 22...22. -> 0b0000_0000 -> 0x00
// 0b1100_0110 -> 0xC6
// 11...11. -> 0b1100_0110 -> 0xC6
// 0b0000_0000 -> 0x00
// ........ -> 0b0000_0000 -> 0x00
// 0b0000_0000 -> 0x00
//
let tile = Tile::new([
0x7C, 0x7C, 0x00, 0xC6, 0xC6, 0x00, 0x00, 0xFE, 0xC6, 0xC6, 0x00, 0xC6, 0xC6, 0x00,
0x00, 0x00,
]);
let data = tile.data();
let data_test = [
[0, 3, 3, 3, 3, 3, 0, 0],
[2, 2, 0, 0, 0, 2, 2, 0],
[1, 1, 0, 0, 0, 1, 1, 0],
[2, 2, 2, 2, 2, 2, 2, 0],
[3, 3, 0, 0, 0, 3, 3, 0],
[2, 2, 0, 0, 0, 2, 2, 0],
[1, 1, 0, 0, 0, 1, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
];
for (y, line) in data.iter().enumerate() {
for (x, color_value) in line.iter().enumerate() {
assert_eq!(*color_value, data_test[y][x]);
}
}
}
}
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.