file_name large_stringlengths 4 69 | prefix large_stringlengths 0 26.7k | suffix large_stringlengths 0 24.8k | middle large_stringlengths 0 2.12k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
f2s.rs | // Translated from C to Rust. The original C code can be found at
// https://github.com/ulfjack/ryu and carries the following license:
//
// Copyright 2018 Ulf Adams
//
// The contents of this file may be used under the terms of the Apache License,
// Version 2.0.
//
// (See accompanying file LICENSE-Apache or copy ... | ;
let exp = e10 + removed;
FloatingDecimal32 {
exponent: exp,
mantissa: output,
}
}
| {
// Specialized for the common case (~96.0%). Percentages below are relative to this.
// Loop iterations below (approximately):
// 0: 13.6%, 1: 70.7%, 2: 14.1%, 3: 1.39%, 4: 0.14%, 5+: 0.01%
while vp / 10 > vm / 10 {
last_removed_digit = (vr % 10) as u8;
vr /= 10... | conditional_block |
f2s.rs | // Translated from C to Rust. The original C code can be found at
// https://github.com/ulfjack/ryu and carries the following license:
//
// Copyright 2018 Ulf Adams
//
// The contents of this file may be used under the terms of the Apache License,
// Version 2.0.
//
// (See accompanying file LICENSE-Apache or copy ... | (m: u32, q: u32, j: i32) -> u32 {
debug_assert!(q < FLOAT_POW5_INV_SPLIT.len() as u32);
unsafe { mul_shift(m, *FLOAT_POW5_INV_SPLIT.get_unchecked(q as usize), j) }
}
#[cfg_attr(feature = "no-panic", inline)]
fn mul_pow5_div_pow2(m: u32, i: u32, j: i32) -> u32 {
debug_assert!(i < FLOAT_POW5_SPLIT.len() as u... | mul_pow5_inv_div_pow2 | identifier_name |
f2s.rs | // Translated from C to Rust. The original C code can be found at
// https://github.com/ulfjack/ryu and carries the following license:
//
// Copyright 2018 Ulf Adams
//
// The contents of this file may be used under the terms of the Apache License,
// Version 2.0.
//
// (See accompanying file LICENSE-Apache or copy ... |
// Returns true if value is divisible by 5^p.
#[cfg_attr(feature = "no-panic", inline)]
fn multiple_of_power_of_5(value: u32, p: u32) -> bool {
pow5_factor(value) >= p
}
// Returns true if value is divisible by 2^p.
#[cfg_attr(feature = "no-panic", inline)]
fn multiple_of_power_of_2(value: u32, p: u32) -> bool {
... | }
count
} | random_line_split |
mailbox.rs | use std::future::Future;
use anyhow::Result;
use wasmtime::{Caller, FuncType, Linker, Trap, ValType};
use crate::{
api::{error::IntoTrap, get_memory},
message::Message,
state::ProcessState,
};
use super::{link_async2_if_match, link_if_match};
// Register the mailbox APIs to the linker
pub(crate) fn regi... |
//% lunatic::message::prepare_receive(i32_data_size_ptr: i32, i32_res_size_ptr: i32) -> i32
//%
//% Returns:
//% * 0 if it's a regular message.
//% * 1 if it's a signal turned into a message.
//%
//% For regular messages both parameters are used.
//% * **i32_data_size_ptr** - Location to write the message buffer size... | {
let message = caller
.data_mut()
.message
.take()
.or_trap("lunatic::message::send")?;
let process = caller
.data()
.resources
.processes
.get(process_id)
.or_trap("lunatic::message::send")?;
let result = match process.send_message(me... | identifier_body |
mailbox.rs | use std::future::Future;
use anyhow::Result;
use wasmtime::{Caller, FuncType, Linker, Trap, ValType};
use crate::{
api::{error::IntoTrap, get_memory},
message::Message,
state::ProcessState,
};
use super::{link_async2_if_match, link_if_match};
// Register the mailbox APIs to the linker
pub(crate) fn regi... | //% The process of sending them around needs to be explicit.
//%
//% This API was designed around the idea that most guest languages will use some serialization
//% library and turning resources into indexes is a way of serializing. The same is true for
//% deserializing them on the receiving side, when an index needs ... | //% received message into the same structure.
//%
//% This can be a bit confusing, because resources are just IDs (u64 values) themself. But we
//% still need to serialize them into different u64 values. Resources are inherently bound to a
//% process and you can't access another resource just by guessing an ID from an... | random_line_split |
mailbox.rs | use std::future::Future;
use anyhow::Result;
use wasmtime::{Caller, FuncType, Linker, Trap, ValType};
use crate::{
api::{error::IntoTrap, get_memory},
message::Message,
state::ProcessState,
};
use super::{link_async2_if_match, link_if_match};
// Register the mailbox APIs to the linker
pub(crate) fn regi... | (
mut caller: Caller<ProcessState>,
data_size_ptr: u32,
res_size_ptr: u32,
) -> Box<dyn Future<Output = Result<u32, Trap>> + Send + '_> {
Box::new(async move {
let message = caller
.data_mut()
.mailbox
.recv()
.await
.expect("a process alway... | prepare_receive | identifier_name |
string.rs | // Copyright 2015 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 ... | () {
let string = "Venenatis_tellus_vel_tellus";
let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
assert_eq!(
break_string(20, false, &graphemes[..]),
SnippetState::EndOfInput("Venenatis_tellus_vel_tellus".to_string())
);
... | nothing_to_break | identifier_name |
string.rs | // Copyright 2015 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 ... | }
#[test]
fn big_whitespace() {
let string = "Neque in sem. Pellentesque tellus augue.";
let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
assert_eq!(
break_string(20, false, &graphemes[..]),
SnippetState::Lin... | {
let string = "Neque in sem. \n Pellentesque tellus augue.";
let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
assert_eq!(
break_string(15, false, &graphemes[..]),
SnippetState::Overflow("Neque in sem. \n".to_string(),... | identifier_body |
string.rs | // Copyright 2015 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 ... | /// Like max_chars_with_indent but the indentation is not substracted.
/// This allows to fit more graphemes from the string on a line when
/// SnippetState::Overflow.
fn max_chars_without_indent(&self) -> Option<usize> {
Some(self.config.max_width().checked_sub(self.line_end.len())?)
}
}
p... | .checked_sub(self.opener.len() + self.line_end.len() + 1)?
+ 1,
)
}
| random_line_split |
server.rs | protocol: Protocol::Udp,
}),
_ => Ok(Bind {
addr: s.to_owned(),
protocol: Protocol::Udp,
}),
}
}
}
impl Default for Config {
fn default() -> Self {
Config {
bind: Bind {
addr: "0.0.0.0:12... | (max_size_bytes: usize, receive: F) -> Self {
Decode {
read_head: 0,
discarding: false,
max_size_bytes,
receive,
}
}
}
impl<F> Decoder for Decode<F>
where
F: FnMut(Bytes) -> Result<Option<Message>, Error... | new | identifier_name |
server.rs | protocol: Protocol::Udp,
}),
_ => Ok(Bind {
addr: s.to_owned(),
protocol: Protocol::Udp,
}),
}
}
}
impl Default for Config {
fn default() -> Self {
Config {
bind: Bind {
addr: "0.0.0.0:12... |
}
struct Decode<F>(F);
impl<F> Decoder for Decode<F>
where
F: FnMut(Bytes) -> Result<Option<Message>, Error> + Unpin,
{
type Item = Received;
type Error = Error;
fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
// A... | {
emit("Setting up for UDP");
UdpFramed::new(self.0, Decode(receive)).map(|r| r.map(|(msg, _)| msg))
} | identifier_body |
server.rs | protocol: Protocol::Udp,
}),
_ => Ok(Bind {
addr: s.to_owned(),
protocol: Protocol::Udp,
}),
}
}
}
impl Default for Config {
fn default() -> Self {
Config {
bind: Bind {
addr: "0.0.0.0:1... | match process(msg) {
Ok(()) => {
increment!(server.process_ok);
}
Err(err) => {
increment!(server.process_err);
emit... | Some(Ok(Received::Complete(msg))) => {
increment!(server.receive_ok);
// Process the received message | random_line_split |
remote.rs | use super::*;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::io::{ReadHalf, WriteHalf};
use tokio::net::TcpStream;
use tracing::debug;
use tracing::{error, Instrument};
async fn direct_to_control(mut incoming: TcpStream) {
let mut control_socket =
match TcpStream::connect(format!("localhost:{}", ... | error!("failed to read from tcp socket: {:?}", e);
return;
}
};
if n == 0 {
debug!("stream ended");
let _ = tunnel_stream
.client
.tx
.send(ControlPacket::End(tunnel_stream.id.clone()))
... | {
// send initial control stream init to client
control_server::send_client_stream_init(tunnel_stream.clone()).await;
// now read from stream and forward to clients
let mut buf = [0; 1024];
loop {
// client is no longer connected
if Connections::get(&tunnel_stream.client.id).is_non... | identifier_body |
remote.rs | use super::*;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::io::{ReadHalf, WriteHalf};
use tokio::net::TcpStream;
use tracing::debug;
use tracing::{error, Instrument};
async fn direct_to_control(mut incoming: TcpStream) {
let mut control_socket =
match TcpStream::connect(format!("localhost:{}", ... | // look for a host header
if let Some(Ok(host)) = req
.headers
.iter()
.filter(|h| h.name.to_lowercase() == "host".to_string())
.map(|h| std::str::from_utf8(h.value))
.next()
{
tracing::info!(host=%host, path=%req.path.unwrap_or_default(), "peek request");
... | String::default()
};
| random_line_split |
remote.rs | use super::*;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::io::{ReadHalf, WriteHalf};
use tokio::net::TcpStream;
use tracing::debug;
use tracing::{error, Instrument};
async fn direct_to_control(mut incoming: TcpStream) {
let mut control_socket =
match TcpStream::connect(format!("localhost:{}", ... | (mut tunnel_stream: ActiveStream, mut tcp_stream: ReadHalf<TcpStream>) {
// send initial control stream init to client
control_server::send_client_stream_init(tunnel_stream.clone()).await;
// now read from stream and forward to clients
let mut buf = [0; 1024];
loop {
// client is no longer... | process_tcp_stream | identifier_name |
trig.rs | /*
This file is part of trig-rs, a library for doing typesafe trigonometry
with a variety of angle formats (radians, degrees, grad, turns, and so on).
*/
//! # `trig-rs`: Typesafe Trigonometric Primitives
//!
//! Leverage Rust's super-powered enums to create a typesafe system for
//! trigonometry in degrees, r... |
/// Calculate the cosine.
#[stable] #[inline] pub fn cos<S: BaseFloat, T: Trigonometry<S>>(t: T) -> S { t.cos() }
/// Calculate the tangent.
#[stable] #[inline] pub fn tan<S: BaseFloat, T: Trigonometry<S>>(t: T) -> S { t.tan() }
/// Calculate the arcsine (in radians).
#[inline] pub fn asin<S: BaseFloat>(s: S) -> An... | { t.sin() } | identifier_body |
trig.rs | /*
This file is part of trig-rs, a library for doing typesafe trigonometry
with a variety of angle formats (radians, degrees, grad, turns, and so on).
*/
//! # `trig-rs`: Typesafe Trigonometric Primitives
//!
//! Leverage Rust's super-powered enums to create a typesafe system for
//! trigonometry in degrees, r... | (s: S) -> Angle<S> { Rad(s % Float::two_pi()) }
/// Returns an angle in degrees.
pub fn degrees(s: S) -> Angle<S> { Deg(s % FromPrimitive::from_f64(360.0).unwrap()) }
/// Returns an angle in gradians.
pub fn gradians(s: S) -> Angle<S> { Grad(s % FromPrimitive::from_f64(400.0).unwrap()) }
/// ... | radians | identifier_name |
trig.rs | /*
This file is part of trig-rs, a library for doing typesafe trigonometry
with a variety of angle formats (radians, degrees, grad, turns, and so on).
*/
//! # `trig-rs`: Typesafe Trigonometric Primitives
//!
//! Leverage Rust's super-powered enums to create a typesafe system for
//! trigonometry in degrees, r... | //! copy of the documentation should be available at
//! [Rust-CI](http://www.rust-ci.org/atheriel/trig-rs/doc/trig/).
//!
//! ## Examples
//!
//! ```rust
//! use trig::{Angle, Rad, sin, cos};
//!
//! // Angle can be constructed in both common formats:
//! let angle1: Angle<f64> = Angle::degrees(180.0);
//! let angle2:... | //!
//! The code is hosted on [GitHub](https://github.com/atheriel/trig-rs), and a | random_line_split |
lib.rs | //! # Bracket Parse
//!
//! A Utility for parsing Bracketed lists and sets of strings.
//!
//! It is a relatively lazy way of parsing items from a bracketed string,
//!
//! "hello(peter,dave)" is easy for it to handle, as are nested brackets.
//!
//! The above will result in something like
//!
//! >Branch[Leaf("hello... | #[test]
fn test_head_tail(){
let b1 = Bracket::from_str("hello (andy dave)").unwrap();
match b1.head().match_str(){
"hello"=>{},//Where the actual code might go
_=>panic!("Head is not hello leaf"),
}
}
#[test]
fn many_tails(){
... | random_line_split | |
lib.rs | //! # Bracket Parse
//!
//! A Utility for parsing Bracketed lists and sets of strings.
//!
//! It is a relatively lazy way of parsing items from a bracketed string,
//!
//! "hello(peter,dave)" is easy for it to handle, as are nested brackets.
//!
//! The above will result in something like
//!
//! >Branch[Leaf("hello... |
pub fn br()->Bracket{
Bracket::Branch(Vec::new())
}
impl FromStr for Bracket{
type Err = String;
fn from_str(s:&str)->Result<Bracket,String>{
let mut res = Bracket::Empty;
let mut it = s.chars();
let mut curr = String::new();
while let Some(c) = it.next() {
... | {
Bracket::Leaf(s.to_string())
} | identifier_body |
lib.rs | //! # Bracket Parse
//!
//! A Utility for parsing Bracketed lists and sets of strings.
//!
//! It is a relatively lazy way of parsing items from a bracketed string,
//!
//! "hello(peter,dave)" is easy for it to handle, as are nested brackets.
//!
//! The above will result in something like
//!
//! >Branch[Leaf("hello... | () {
let b1 = Bracket::from_str("matt dave (andy steve)").unwrap();
let c1 = br().sib_lf("matt").sib_lf("dave").sib(
br().sib_lf("andy").sib_lf("steve")
);
let b2 = Bracket::from_str("matt dave( andy ste... | spaces | identifier_name |
mod.rs | //! Storage for span data shared by multiple [`Layer`]s.
//!
//! ## Using the Span Registry
//!
//! This module provides the [`Registry`] type, a [`Subscriber`] implementation
//! which tracks per-span data and exposes it to [`Layer`]s. When a `Registry`
//! is used as the base `Subscriber` of a `Layer` stack, the
//! ... | /// Returns a static reference to the span's metadata.
pub fn metadata(&self) -> &'static Metadata<'static> {
self.data.metadata()
}
/// Returns the span's name,
pub fn name(&self) -> &'static str {
self.data.metadata().name()
}
/// Returns a list of [fields] defined by the... | self.data.id()
}
| identifier_body |
mod.rs | //! Storage for span data shared by multiple [`Layer`]s.
//!
//! ## Using the Span Registry
//!
//! This module provides the [`Registry`] type, a [`Subscriber`] implementation
//! which tracks per-span data and exposes it to [`Layer`]s. When a `Registry`
//! is used as the base `Subscriber` of a `Layer` stack, the
//! ... | self) -> Extensions<'_> {
self.data.extensions()
}
/// Returns a mutable reference to this span's `Extensions`.
///
/// The extensions may be used by `Layer`s to store additional data
/// describing the span.
pub fn extensions_mut(&self) -> ExtensionsMut<'_> {
self.data.extensio... | tensions(& | identifier_name |
mod.rs | //! Storage for span data shared by multiple [`Layer`]s.
//!
//! ## Using the Span Registry
//!
//! This module provides the [`Registry`] type, a [`Subscriber`] implementation
//! which tracks per-span data and exposes it to [`Layer`]s. When a `Registry`
//! is used as the base `Subscriber` of a `Layer` stack, the
//! ... | pub use sharded::Registry;
/// Provides access to stored span data.
///
/// Subscribers which store span data and associate it with span IDs should
/// implement this trait; if they do, any [`Layer`]s wrapping them can look up
/// metadata via the [`Context`] type's [`span()`] method.
///
/// [`Layer`]:../layer/trait.... | #[cfg_attr(docsrs, doc(cfg(feature = "registry")))] | random_line_split |
docker_compose.rs | //! Provides utility functions for [ServerPlugin] and [ServerHandle] implementations that use Docker Compose.
//!
//! These functions all assume that the server has a dedicated directory, which contains a custom shell
//! script that wraps `docker-compose` with any setup, environment variables, etc. needed to run thing... | (&self) -> Result<String> {
let server_plugin = server_plugin_downcast(self);
match run_docker_compose(server_plugin, &["logs", "--no-color"]).with_context(|| {
format!(
"Running '{} up --detach' failed.",
server_plugin
.server_script()
... | emit_logs | identifier_name |
docker_compose.rs | //! Provides utility functions for [ServerPlugin] and [ServerHandle] implementations that use Docker Compose.
//!
//! These functions all assume that the server has a dedicated directory, which contains a custom shell
//! script that wraps `docker-compose` with any setup, environment variables, etc. needed to run thing... |
// Wait (up to a timeout) for the server to be ready.
match wait_for_ready(app_state, &server_handle).await {
Err(err) => {
server_handle.emit_logs_info()?;
Err(err)
}
Ok(_) => {
let server_handle: Box<dyn ServerHandle> = Box::new(server_handle);
... | let server_handle = DockerComposeServerHandle {
server_plugin: server_plugin.clone(),
http_client,
}; | random_line_split |
docker_compose.rs | //! Provides utility functions for [ServerPlugin] and [ServerHandle] implementations that use Docker Compose.
//!
//! These functions all assume that the server has a dedicated directory, which contains a custom shell
//! script that wraps `docker-compose` with any setup, environment variables, etc. needed to run thing... |
}
/// Runs the specified Docker Compose subcommand with the specified argument, for the specified FHIR Server
/// implementation.
///
/// Parameters:
/// * `server_plugin`: the [DockerComposeServerPlugin] that represents the FHIR Server implementation to run
/// the command for/against
/// * `args`: the Docker Comp... | {
launch_server(app_state, self).await
} | identifier_body |
lookup.rs | use crate::utils::{f64_compare, TValue, TValueType};
use super::*;
/// Functionality relating to looking up properties of the `Bezier` or points along the `Bezier`.
impl Bezier {
/// Convert a euclidean distance ratio along the `Bezier` curve to a parametric `t`-value.
pub fn euclidean_to_parametric(&self, ratio: f... | } else {
high = mid;
}
}
mid
}
/// Convert a [TValue] to a parametric `t`-value.
pub(crate) fn t_value_to_parametric(&self, t: TValue) -> f64 {
match t {
TValue::Parametric(t) => {
assert!((0.0..=1.).contains(&t));
t
}
TValue::Euclidean(t) => {
assert!((0.0..=1.).contains(&t))... | {
if ratio < error {
return 0.;
}
if 1. - ratio < error {
return 1.;
}
let mut low = 0.;
let mut mid = 0.;
let mut high = 1.;
let total_length = self.length(None);
while low < high {
mid = (low + high) / 2.;
let test_ratio = self.trim(TValue::Parametric(0.), TValue::Parametric(mid)).leng... | identifier_body |
lookup.rs | use crate::utils::{f64_compare, TValue, TValueType};
use super::*;
/// Functionality relating to looking up properties of the `Bezier` or points along the `Bezier`.
impl Bezier {
/// Convert a euclidean distance ratio along the `Bezier` curve to a parametric `t`-value.
pub fn | (&self, ratio: f64, error: f64) -> f64 {
if ratio < error {
return 0.;
}
if 1. - ratio < error {
return 1.;
}
let mut low = 0.;
let mut mid = 0.;
let mut high = 1.;
let total_length = self.length(None);
while low < high {
mid = (low + high) / 2.;
let test_ratio = self.trim(TValue::Parame... | euclidean_to_parametric | identifier_name |
lookup.rs | use crate::utils::{f64_compare, TValue, TValueType};
use super::*;
/// Functionality relating to looking up properties of the `Bezier` or points along the `Bezier`.
impl Bezier {
/// Convert a euclidean distance ratio along the `Bezier` curve to a parametric `t`-value.
pub fn euclidean_to_parametric(&self, ratio: f... |
}
mid
}
/// Convert a [TValue] to a parametric `t`-value.
pub(crate) fn t_value_to_parametric(&self, t: TValue) -> f64 {
match t {
TValue::Parametric(t) => {
assert!((0.0..=1.).contains(&t));
t
}
TValue::Euclidean(t) => {
assert!((0.0..=1.).contains(&t));
self.euclidean_to_parametri... | {
high = mid;
} | conditional_block |
lookup.rs | use crate::utils::{f64_compare, TValue, TValueType};
use super::*;
/// Functionality relating to looking up properties of the `Bezier` or points along the `Bezier`.
impl Bezier {
/// Convert a euclidean distance ratio along the `Bezier` curve to a parametric `t`-value.
pub fn euclidean_to_parametric(&self, ratio: f... | } else {
convergence_count = 0;
}
}
final_t
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_evaluate() {
let p1 = DVec2::new(3., 5.);
let p2 = DVec2::new(14., 3.);
let p3 = DVec2::new(19., 14.);
let p4 = DVec2::new(30., 21.);
let bezier1 = Bezier::from_quadratic_dvec2(p1, p2, p... | convergence_count += 1; | random_line_split |
agreement.rs | // Copyright 2015-2017 Brian Smith.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAI... |
/// The private key.
pub fn private_key(&self) -> &PrivateKey<U> { &self.private_key }
/// The public key.
pub fn public_key(&self) -> &PublicKey { &self.public_key }
/// Split the key pair apart.
pub fn split(self) -> (PrivateKey<U>, PublicKey) { (self.private_key, self.public_key) }
}
///... | {
// NSA Guide Step 1.
let private_key = ec::PrivateKey::generate(&alg.curve, rng)?;
let mut public_key = PublicKey {
bytes: [0; PUBLIC_KEY_MAX_LEN],
alg,
};
private_key.compute_public_key(&alg.curve, &mut public_key.bytes)?;
Ok(Self {
... | identifier_body |
agreement.rs | // Copyright 2015-2017 Brian Smith.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAI... | {
bytes: [u8; ec::ELEM_MAX_BYTES],
len: usize,
}
mod sealed {
pub trait Sealed {}
}
impl InputKeyMaterial {
/// Calls `kdf` with the raw key material and then returns what `kdf`
/// returns, consuming `Self` so that the key material can only be used
/// once.
pub fn derive<F, R>(self, kdf... | InputKeyMaterial | identifier_name |
agreement.rs | // Copyright 2015-2017 Brian Smith.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAI... | };
self.private_key
.compute_public_key(&self.alg.curve, &mut public_key.bytes)?;
Ok(public_key)
}
/// Performs a key agreement with an private key and the given public key.
///
/// Since `self` is consumed, it will not be usable after calling `agree`.
///
///... | alg: self.alg, | random_line_split |
agreement.rs | // Copyright 2015-2017 Brian Smith.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAI... |
// NSA Guide Prerequisite 2, regarding which KDFs are allowed, is delegated
// to the caller.
// NSA Guide Prerequisite 3, "Prior to or during the key-agreement process,
// each party shall obtain the identifier associated with the other party
// during the key-agreement scheme," is delegated to ... | {
return Err(error::Unspecified);
} | conditional_block |
read.rs | : PhantomData<U>,
}
impl Reader<File, UnifyVertices> {
/// Tries to open the file specified by the given path and creates a new
/// `Reader` from that file.
pub fn open(path: impl AsRef<Path>) -> Result<Self, Error> {
// We don't need a `BufReader` here, because we will use our internal
// ... | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("Reader")
.field("buf", &self.buf)
.field("solid_name", &self.solid_name)
.field("is_binary", &self.triangle_count.is_some())
.field("triangle_count", &self.triangle_count)
.finish()
... | }
impl<R: io::Read, U: UnifyingMarker> fmt::Debug for Reader<R, U> { | random_line_split |
read.rs | PhantomData<U>,
}
impl Reader<File, UnifyVertices> {
/// Tries to open the file specified by the given path and creates a new
/// `Reader` from that file.
pub fn open(path: impl AsRef<Path>) -> Result<Self, Error> {
// We don't need a `BufReader` here, because we will use our internal
// p... | <F>(self, triangle_count: u32, mut add_triangle: F) -> Result<(), Error>
where
F: FnMut(RawTriangle) -> Result<(), Error>,
{
const BYTES_PER_TRI: usize = 4 * 3 * 4 + 2;
let mut buf = self.buf;
// We attempt to read as many triangles as specified. If the
// specified nu... | read_raw_binary | identifier_name |
read.rs | PhantomData<U>,
}
impl Reader<File, UnifyVertices> {
/// Tries to open the file specified by the given path and creates a new
/// `Reader` from that file.
pub fn open(path: impl AsRef<Path>) -> Result<Self, Error> {
// We don't need a `BufReader` here, because we will use our internal
// p... |
// Read the all triangles into the raw result
self.read_raw(|tri| {
out.triangles.push(tri);
Ok(())
})?;
Ok(out)
}
/// Reads the whole file, passing each triangle to the `add_triangle`
/// callback.
///
/// This is a low level building bloc... | {
out.triangles.reserve(tri_count as usize);
} | conditional_block |
rsync.rs | use std::{
fs::File,
io::{BufReader, Read},
path::{Path, PathBuf},
};
use anyhow::{anyhow, Context, Result};
use filetime::{set_file_mtime, FileTime};
use log::{info, warn};
use rpki::{
repository::{sigobj::SignedObject, Cert, Crl, Manifest, Roa},
rrdp::ProcessSnapshot,
};
use serde::{Deserialize,... | (
rrdp_state: &RrdpState,
changed: bool,
config: &Config,
) -> Result<()> {
// Check that there is a current snapshot, if not, there is no work
if rrdp_state.snapshot_path().is_none() {
return Ok(());
}
// We can assume now that there is a snapshot and unwrap things for it
let s... | update_from_rrdp_state | identifier_name |
rsync.rs | use std::{
fs::File,
io::{BufReader, Read},
path::{Path, PathBuf},
};
use anyhow::{anyhow, Context, Result};
use filetime::{set_file_mtime, FileTime};
use log::{info, warn};
use rpki::{
repository::{sigobj::SignedObject, Cert, Crl, Manifest, Roa},
rrdp::ProcessSnapshot,
};
use serde::{Deserialize,... | "Renaming the rsync directory for previous revision to: {}",
current_preserve_path.display()
);
std::fs::rename(¤t_path, ¤t_preserve_path).with_context(|| {
format!(
"Could not rename current rsync dir from '{}' to '... | random_line_split | |
rsync.rs | use std::{
fs::File,
io::{BufReader, Read},
path::{Path, PathBuf},
};
use anyhow::{anyhow, Context, Result};
use filetime::{set_file_mtime, FileTime};
use log::{info, warn};
use rpki::{
repository::{sigobj::SignedObject, Cert, Crl, Manifest, Roa},
rrdp::ProcessSnapshot,
};
use serde::{Deserialize,... |
.map_err(|_| anyhow!("Cannot parse object at: {} to derive mtime", path_str))?;
let mtime = FileTime::from_unix_time(time.timestamp(), 0);
set_file_mtime(&path, mtime).map_err(|e| {
anyhow!(
"Cannot modify mtime for object at: {}, error: {}",
path_str,
e
... | {
// Try to parse this as a generic RPKI signed object
SignedObject::decode(data, false).map(|signed| signed.cert().validity().not_before())
} | conditional_block |
tcp.rs | //! # TCP handling
//!
//! This file contains the TCP handling for `clobber`. The loop here is that we connect, write,
//! and then read. If the client is in repeat mode then it will repeatedly write/read while the
//! connection is open.
//!
//! ## Performance Notes
//!
//! ### Perform allocations at startup
//!
//! T... |
}
| {
let addr = echo_server().unwrap();
let input = "test\n\r\n".as_bytes();
let want = input.len();
let result = async_std::task::block_on(async move {
let mut stream = connect(&addr).await?;
let mut read_buffer = [0u8; 1024];
let _ = write(&mut stream,... | identifier_body |
tcp.rs | //! # TCP handling
//!
//! This file contains the TCP handling for `clobber`. The loop here is that we connect, write,
//! and then read. If the client is in repeat mode then it will repeatedly write/read while the
//! connection is open.
//!
//! ## Performance Notes
//!
//! ### Perform allocations at startup
//!
//! T... | () {
let result = async_std::task::block_on(async {
let addr = echo_server().unwrap();
let result = connect(&addr).await;
result
});
assert!(result.is_ok());
}
#[test]
fn test_write() {
let addr = echo_server().unwrap();
let inpu... | test_connect | identifier_name |
tcp.rs | //! # TCP handling
//!
//! This file contains the TCP handling for `clobber`. The loop here is that we connect, write,
//! and then read. If the client is in repeat mode then it will repeatedly write/read while the
//! connection is open.
//!
//! ## Performance Notes
//!
//! ### Perform allocations at startup
//!
//! T... | }
#[cfg(test)]
mod tests {
use super::*;
use crate::server::echo_server;
#[test]
fn test_connect() {
let result = async_std::task::block_on(async {
let addr = echo_server().unwrap();
let result = connect(&addr).await;
result
});
assert!(res... | // todo: Do something with the read_buffer?
// todo: More verbose logging; dump to stdout, do post-run analysis on demand | random_line_split |
epoll_file.rs | ::epoll_waiter::EpollWaiter;
use super::host_file_epoller::HostFileEpoller;
use super::{EpollCtl, EpollEvent, EpollFlags};
use crate::events::{Observer, Waiter, WaiterQueue};
use crate::fs::{
AtomicIoEvents, File, FileTableEvent, FileTableNotifier, HostFd, IoEvents, IoNotifier,
};
use crate::prelude::*;
// TODO: P... |
fn update_host_events(&self, ready: &IoEvents, mask: &IoEvents, trigger_notifier: bool) {
self.host_events.update(ready, mask, Ordering::Release);
if trigger_notifier {
self.notifier.broadcast(ready);
}
}
fn as_any(&self) -> &dyn Any {
self
}
}
impl Drop ... | {
Some(self.host_file_epoller.host_fd())
} | identifier_body |
epoll_file.rs | ::epoll_waiter::EpollWaiter;
use super::host_file_epoller::HostFileEpoller;
use super::{EpollCtl, EpollEvent, EpollFlags};
use crate::events::{Observer, Waiter, WaiterQueue};
use crate::fs::{
AtomicIoEvents, File, FileTableEvent, FileTableNotifier, HostFd, IoEvents, IoNotifier,
};
use crate::prelude::*;
// TODO: P... | (&self) -> Result<&EpollFile> {
self.as_any()
.downcast_ref::<EpollFile>()
.ok_or_else(|| errno!(EBADF, "not an epoll file"))
}
}
#[derive(Debug)]
struct EpollEntry {
fd: FileDesc,
file: FileRef,
inner: SgxMutex<EpollEntryInner>,
// Whether the entry is in the ready li... | as_epoll_file | identifier_name |
epoll_file.rs | ::epoll_waiter::EpollWaiter;
use super::host_file_epoller::HostFileEpoller;
use super::{EpollCtl, EpollEvent, EpollFlags};
use crate::events::{Observer, Waiter, WaiterQueue};
use crate::fs::{
AtomicIoEvents, File, FileTableEvent, FileTableNotifier, HostFd, IoEvents, IoNotifier,
};
use crate::prelude::*;
// TODO: P... |
EpollCtl::Del(fd) => {
self.del_interest(*fd)?;
}
EpollCtl::Mod(fd, event, flags) => {
self.mod_interest(*fd, *event, *flags)?;
}
}
Ok(())
}
pub fn wait(
&self,
revents: &mut [MaybeUninit<EpollEvent... | {
self.add_interest(*fd, *event, *flags)?;
} | conditional_block |
epoll_file.rs | super::epoll_waiter::EpollWaiter;
use super::host_file_epoller::HostFileEpoller;
use super::{EpollCtl, EpollEvent, EpollFlags};
use crate::events::{Observer, Waiter, WaiterQueue};
use crate::fs::{
AtomicIoEvents, File, FileTableEvent, FileTableNotifier, HostFd, IoEvents, IoNotifier,
};
use crate::prelude::*;
// T... | // process, then this EpollFile still has connection with the parent process's
// file table, which is problematic.
/// A file that provides epoll API.
///
/// Conceptually, we maintain two lists: one consists of all interesting files,
/// which can be managed by the epoll ctl commands; the other are for ready files,
... | // with the current process's file table by regitering itself as an observer
// to the file table. But if an EpollFile is cloned or inherited by a child | random_line_split |
lib.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
//! This crate contains Winterfell STARK prover and verifier.
//!
//! A STARK is a novel proof-of-computation scheme to create efficiently... | //! #
//! # fn evaluate_transition<E: FieldElement + From<Self::BaseElement>>(
//! # &self,
//! # frame: &EvaluationFrame<E>,
//! # _periodic_values: &[E],
//! # result: &mut [E],
//! # ) {
//! # let current_state = &frame.current()[0];
//! # let next_state = curr... | //! # }
//! # } | random_line_split |
fetch.rs | use futures::{
future,
sync::{mpsc, oneshot},
};
use crate::msg;
use flatbuffers::FlatBufferBuilder;
use crate::js::*;
use crate::runtime::{Runtime, EVENT_LOOP};
use crate::utils::*;
use libfly::*;
use crate::errors::{FlyError, FlyResult};
use crate::get_next_stream_id;
use hyper::body::Payload;
use hyper:... | let host = if let Some(port) = http_uri.port_part() {
format!("{}:{}", host_str, port.as_str())
} else {
let port = if let Some(scheme) = http_uri.scheme_part() {
if scheme == &Scheme::HTTPS {
"443"
} else {
"80"
}
} els... | {
let cmd_id = base.cmd_id();
let msg = base.msg_as_http_request().unwrap();
let url = msg.url().unwrap();
if url.starts_with("file://") {
return file_request(rt, cmd_id, url);
}
let ptr = rt.ptr;
let req_id = msg.id();
let http_uri: hyper::Uri = match url.parse() {
O... | identifier_body |
fetch.rs | use futures::{
future,
sync::{mpsc, oneshot},
};
use crate::msg;
use flatbuffers::FlatBufferBuilder;
use crate::js::*;
use crate::runtime::{Runtime, EVENT_LOOP};
use crate::utils::*;
use libfly::*;
use crate::errors::{FlyError, FlyResult};
use crate::get_next_stream_id;
use hyper::body::Payload;
use hyper:... | status: res.status.as_u16(),
has_body: res.body.is_some(),
..Default::default()
},
);
if let Some(stream) = res.body {
send_body_stream(ptr, req_id, stream);
}
Ok(serialize_response... | headers: Some(res_headers), | random_line_split |
fetch.rs | use futures::{
future,
sync::{mpsc, oneshot},
};
use crate::msg;
use flatbuffers::FlatBufferBuilder;
use crate::js::*;
use crate::runtime::{Runtime, EVENT_LOOP};
use crate::utils::*;
use libfly::*;
use crate::errors::{FlyError, FlyResult};
use crate::get_next_stream_id;
use hyper::body::Payload;
use hyper:... | (rt: &mut Runtime, base: &msg::Base, raw: fly_buf) -> Box<Op> {
debug!("handling http response");
let msg = base.msg_as_http_response().unwrap();
let req_id = msg.id();
let status = match StatusCode::from_u16(msg.status()) {
Ok(s) => s,
Err(e) => return odd_future(format!("{}", e).into(... | op_http_response | identifier_name |
migrations.rs | // This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.a... | traits::{GetStorageVersion, PalletInfoAccess},
};
#[cfg(feature = "try-runtime")]
use sp_io::hashing::twox_128;
pub struct MigrateToV11<T, P, N>(sp_std::marker::PhantomData<(T, P, N)>);
impl<T: Config, P: GetStorageVersion + PalletInfoAccess, N: Get<&'static str>> OnRuntimeUpgrade
for MigrateToV11<T, P, N>
{... | use super::*;
use frame_support::{
storage::migration::move_pallet, | random_line_split |
migrations.rs | // This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.a... | <T>(sp_std::marker::PhantomData<T>);
impl<T: Config> OnRuntimeUpgrade for MigrateToV12<T> {
#[cfg(feature = "try-runtime")]
fn pre_upgrade() -> Result<Vec<u8>, TryRuntimeError> {
frame_support::ensure!(
StorageVersion::<T>::get() == ObsoleteReleases::V11_0_0,
"Expected v11 before upgrading to v12"
);... | MigrateToV12 | identifier_name |
migrations.rs | // This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.a... | }
else {
log!(
warn,
"InjectValidatorsIntoVoterList being executed on the wrong storage \
version, expected ObsoleteReleases::V8_0_0"
);
T::DbWeight::get().reads(1)
}
}
#[cfg(feature = "try-runtime")]
fn pre_upgrade() -> Result<Vec<u8>, TryRuntimeError> {
frame_support::ensure... | {
let prev_count = T::VoterList::count();
let weight_of_cached = Pallet::<T>::weight_of_fn();
for (v, _) in Validators::<T>::iter() {
let weight = weight_of_cached(&v);
let _ = T::VoterList::on_insert(v.clone(), weight).map_err(|err| {
log!(warn, "failed to insert {:?} into VoterList: {:?}",... | conditional_block |
migrations.rs | // This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.a... |
fn on_runtime_upgrade() -> Weight {
let current = Pallet::<T>::current_storage_version();
let onchain = StorageVersion::<T>::get();
if current == 13 && onchain == ObsoleteReleases::V12_0_0 {
StorageVersion::<T>::kill();
current.put::<Pallet<T>>();
log!(info, "v13 applied successfully");
T... | {
frame_support::ensure!(
StorageVersion::<T>::get() == ObsoleteReleases::V12_0_0,
"Required v12 before upgrading to v13"
);
Ok(Default::default())
} | identifier_body |
day20.rs | #![allow(dead_code)]
use std::collections::HashMap;
mod lib;
// Width (and height) of each tile.
const SIZE: usize = 10;
// One row/side of each tile.
type Line = u16;
#[derive(PartialEq, Eq, Debug, Clone, Hash, Default)]
struct Tile {
id: usize,
rows: Vec<Line>,
flipped: bool,
rotated: u32,
}
fn ... |
fn west_edge(self: &Self) -> Line {
self.rotate_cw().rows[0]
}
fn east_edge(self: &Self) -> Line {
self.rotate_cw().rotate_cw().rotate_cw().rows[0]
}
fn south_edge(self: &Self) -> Line {
self.rotate_cw().rotate_cw().rows[0]
}
fn get_edges(self: &Self) -> [Line; 4]... | self.rows[0]
} | random_line_split |
day20.rs | #![allow(dead_code)]
use std::collections::HashMap;
mod lib;
// Width (and height) of each tile.
const SIZE: usize = 10;
// One row/side of each tile.
type Line = u16;
#[derive(PartialEq, Eq, Debug, Clone, Hash, Default)]
struct Tile {
id: usize,
rows: Vec<Line>,
flipped: bool,
rotated: u32,
}
fn ... | (self: &Self) -> MergedTiles {
MergedTiles {
rows: self.rows.iter().cloned().rev().collect(),
}
}
}
fn main() {
let contents = std::fs::read_to_string("input/20.txt").expect("read failed");
let mut bag = TileBag::parse(&contents);
// Part 1: find corners, multiply their ids... | mirror_vertical | identifier_name |
day20.rs | #![allow(dead_code)]
use std::collections::HashMap;
mod lib;
// Width (and height) of each tile.
const SIZE: usize = 10;
// One row/side of each tile.
type Line = u16;
#[derive(PartialEq, Eq, Debug, Clone, Hash, Default)]
struct Tile {
id: usize,
rows: Vec<Line>,
flipped: bool,
rotated: u32,
}
fn ... |
#[test]
fn test_invert() {
assert_eq!(invert(1), 512);
assert_eq!(invert(512), 1);
assert_eq!(invert(2), 256);
}
}
impl std::fmt::Display for Tile {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut first = true;
for line in self.rows... | {
assert_eq!(line_to_string(1), ".........#");
assert_eq!(line_to_string(391), ".##....###");
} | identifier_body |
write.rs | unreachable = sess.target.target.options.trap_unreachable;
let emit_stack_size_section = sess.opts.debugging_opts.emit_stack_sizes;
let asm_comments = sess.asm_comments();
Arc::new(move || {
let tm = unsafe {
llvm::LLVMRustCreateTargetMachine(
triple.as_ptr(), cpu.as_pt... | diag_handler.err(&msg);
}
}
} else if config.embed_bitcode_marker {
embed_bitcode(cgcx, llcx, llmod, None);
}
time_ext(config.time_passes, &format!("codegen passes [{}]", module_name.unwrap()),
|| -> Result<(), FatalError> ... | let msg = format!("failed to write bytecode to {}: {}", dst.display(), e); | random_line_split |
write.rs | = sess.target.target.options.trap_unreachable;
let emit_stack_size_section = sess.opts.debugging_opts.emit_stack_sizes;
let asm_comments = sess.asm_comments();
Arc::new(move || {
let tm = unsafe {
llvm::LLVMRustCreateTargetMachine(
triple.as_ptr(), cpu.as_ptr(), featur... | (cgcx: &CodegenContext<LlvmCodegenBackend>,
msg: &str,
cookie: c_uint) {
cgcx.diag_emitter.inline_asm_error(cookie as u32, msg.to_owned());
}
unsafe extern "C" fn inline_asm_handler(diag: &SMDiagnostic,
... | report_inline_asm | identifier_name |
write.rs | llvm::LLVMRustAddPass(mpm, find_pass("name-anon-globals").unwrap());
have_name_anon_globals_pass = true;
}
} else {
// If we don't use the standard pipeline, directly populate the MPM
// with the extra passes.
for pass in ... | {
"\x01__imp__"
} | conditional_block | |
write.rs |
pub fn to_llvm_opt_settings(cfg: config::OptLevel) -> (llvm::CodeGenOptLevel, llvm::CodeGenOptSize)
{
use self::config::OptLevel::*;
match cfg {
No => (llvm::CodeGenOptLevel::None, llvm::CodeGenOptSizeNone),
Less => (llvm::CodeGenOptLevel::Less, llvm::CodeGenOptSizeNone),
Default => (l... | {
target_machine_factory(&tcx.sess, tcx.backend_optimization_level(LOCAL_CRATE), find_features)()
.unwrap_or_else(|err| {
llvm_err(tcx.sess.diagnostic(), &err).raise()
})
} | identifier_body | |
lib.rs | //! *“I'm late! I'm late! For a very important date!”*
//! *by “The White Rabbit”* 『Alice's Adventures in Wonderland』
//!
//! `white_rabbit` schedules your tasks and can repeat them!
//!
//! One funny use case are chat bot commands: Imagine a *remind me*-command,
//! the command gets executed and you simply create a on... | lse {
let mut scheduler_state = state_lock.lock();
if let SchedulerState::PauseTime(_) = *scheduler_state {
let peeked = locked_heap.peek().expect("Expected heap to be filled.");
if task.context.time < peeked.context.time {
let left = task.co... | *scheduler_state = SchedulerState::new_pause_time(left);
notifier.notify_one();
}
} e | conditional_block |
lib.rs | //! *“I'm late! I'm late! For a very important date!”*
//! *by “The White Rabbit”* 『Alice's Adventures in Wonderland』
//!
//! `white_rabbit` schedules your tasks and can repeat them!
//!
//! One funny use case are chat bot commands: Imagine a *remind me*-command,
//! the command gets executed and you simply create a on... | scheduler exists on two levels: The handle, granting you the
/// ability of adding new tasks, and the executor, dating and executing these
/// tasks when specified time is met.
///
/// **Info**: This scheduler may not be precise due to anomalies such as
/// preemption or platform differences.
pub struct Scheduler {
... | hedulerState::PauseTime(
duration
.to_std()
.unwrap_or_else(|_| StdDuration::from_millis(0)),
)
}
}
/// This | identifier_body |
lib.rs | //! *“I'm late! I'm late! For a very important date!”*
//! *by “The White Rabbit”* 『Alice's Adventures in Wonderland』
//!
//! `white_rabbit` schedules your tasks and can repeat them!
//!
//! One funny use case are chat bot commands: Imagine a *remind me*-command,
//! the command gets executed and you simply create a on... | DateTime<Utc>,
}
/// Every task will return this `enum`.
pub enum DateResult {
/// The task is considered finished and can be fully removed.
Done,
/// The task will be scheduled for a new date on passed `DateTime<Utc>`.
Repeat(DateTime<Utc>),
}
/// Every job gets a planned `Date` with the scheduler.
... | time: | identifier_name |
lib.rs | //! *“I'm late! I'm late! For a very important date!”*
//! *by “The White Rabbit”* 『Alice's Adventures in Wonderland』
//!
//! `white_rabbit` schedules your tasks and can repeat them!
//!
//! One funny use case are chat bot commands: Imagine a *remind me*-command,
//! the command gets executed and you simply create a on... |
}
#[must_use]
enum Break {
Yes,
No,
}
#[inline]
fn process_states(state_lock: &Mutex<SchedulerState>, notifier: &Condvar) -> Break {
let mut scheduler_state = state_lock.lock();
while let SchedulerState::PauseEmpty = *scheduler_state {
notifier.wait(&mut scheduler_state);
}
while le... | *state = SchedulerState::new_pause_time(left);
_push_and_notfiy(date, &mut heap_lock, ¬ifier);
} | random_line_split |
lib.rs | //! # Lattice Client
//!
//! This library provides a client that communicates with a waSCC lattice using
//! the lattice protocol over the NATS message broker. All waSCC hosts compiled
//! in lattice mode have the ability to automatically form self-healing, self-managing
//! infrastructure-agnostic clusters called [lat... |
/// Retrieves the list of all capabilities within the lattice (discovery limited by the client timeout period)
pub fn get_capabilities(
&self,
) -> std::result::Result<HashMap<String, Vec<HostedCapability>>, Box<dyn std::error::Error>>
{
let mut host_caps = HashMap::new();
let ... | {
let mut host_actors = HashMap::new();
let sub = self
.nc
.request_multi(self.gen_subject(INVENTORY_ACTORS).as_ref(), &[])?;
for msg in sub.timeout_iter(self.timeout) {
let ir: InventoryResponse = serde_json::from_slice(&msg.data)?;
if let Invent... | identifier_body |
lib.rs | //! # Lattice Client
//!
//! This library provides a client that communicates with a waSCC lattice using
//! the lattice protocol over the NATS message broker. All waSCC hosts compiled
//! in lattice mode have the ability to automatically form self-healing, self-managing
//! infrastructure-agnostic clusters called [lat... | (&self, subject: &str) -> String {
match self.namespace.as_ref() {
Some(s) => format!("{}.wasmbus.{}", s, subject),
None => format!("wasmbus.{}", subject),
}
}
}
fn get_connection(host: &str, credsfile: Option<PathBuf>) -> nats::Connection {
let mut opts = if let Some(cr... | gen_subject | identifier_name |
lib.rs | //! # Lattice Client
//!
//! This library provides a client that communicates with a waSCC lattice using
//! the lattice protocol over the NATS message broker. All waSCC hosts compiled
//! in lattice mode have the ability to automatically form self-healing, self-managing
//! infrastructure-agnostic clusters called [lat... | pub const INVENTORY_CAPABILITIES: &str = "inventory.capabilities";
pub const EVENTS: &str = "events";
const AUCTION_TIMEOUT_SECONDS: u64 = 5;
/// A response to a lattice probe for inventory. Note that these responses are returned
/// through regular (non-queue) subscriptions via a scatter-gather like pattern, so the
/... |
pub const INVENTORY_ACTORS: &str = "inventory.actors";
pub const INVENTORY_HOSTS: &str = "inventory.hosts";
pub const INVENTORY_BINDINGS: &str = "inventory.bindings"; | random_line_split |
mod.rs | pub mod cut_detector;
pub mod ring;
pub mod view;
use crate::{
common::{ConfigId, Endpoint, NodeId, Scheduler, SchedulerEvents},
consensus::FastPaxos,
error::Result,
event::{Event, NodeStatusChange},
monitor::Monitor,
transport::{
proto::{
self, Alert, BatchedAlertMessage, E... | ,
metadata: Metadata::default(),
})
.collect()
}
// Filter for removing invalid edge update messages. These include messages
// that were for a configuration that the current node is not a part of, and messages
// that violate teh semantics of being a part of a co... | {
EdgeStatus::Up
} | conditional_block |
mod.rs | pub mod cut_detector;
pub mod ring;
pub mod view;
use crate::{
common::{ConfigId, Endpoint, NodeId, Scheduler, SchedulerEvents},
consensus::FastPaxos,
error::Result,
event::{Event, NodeStatusChange},
monitor::Monitor,
transport::{
proto::{
self, Alert, BatchedAlertMessage, E... | cluster_metadata: HashMap::new(),
}
};
self.messages
.push_back((from, proto::ResponseKind::Join(response).into()));
}
}
// Invoked by observers of a node for failure detection
fn handle_probe_message(&self) -> Response {
... | sender: self.host_addr.clone(),
status: JoinStatus::ConfigChanged,
config_id: self.view.get_current_config_id(),
endpoints: vec![],
identifiers: vec![], | random_line_split |
mod.rs | pub mod cut_detector;
pub mod ring;
pub mod view;
use crate::{
common::{ConfigId, Endpoint, NodeId, Scheduler, SchedulerEvents},
consensus::FastPaxos,
error::Result,
event::{Event, NodeStatusChange},
monitor::Monitor,
transport::{
proto::{
self, Alert, BatchedAlertMessage, E... | (&mut self) {
for signal in self.monitor_cancellers.drain(..) {
let _ = signal.send(());
}
}
fn respond_to_joiners(&mut self, proposal: Vec<Endpoint>) {
let configuration = self.view.get_config();
let join_res = JoinResponse {
sender: self.host_addr.clon... | cancel_failure_detectors | identifier_name |
mod.rs | pub mod cut_detector;
pub mod ring;
pub mod view;
use crate::{
common::{ConfigId, Endpoint, NodeId, Scheduler, SchedulerEvents},
consensus::FastPaxos,
error::Result,
event::{Event, NodeStatusChange},
monitor::Monitor,
transport::{
proto::{
self, Alert, BatchedAlertMessage, E... |
pub fn view(&self) -> Vec<&Endpoint> {
self.view
.get_ring(0)
.expect("There is always a ring!")
.iter()
.collect()
}
pub fn step(&mut self, from: Endpoint, msg: proto::RequestKind) {
use proto::RequestKind::*;
match msg {
P... | {
let nodes = self.view.get_ring(0);
nodes
.iter()
.map(|_| NodeStatusChange {
endpoint: self.host_addr.clone(),
status: EdgeStatus::Up,
metadata: Metadata::default(),
})
.collect()
} | identifier_body |
font.rs | use prelude::*;
use core::{self, Layer, Context, Color, Point2, Rect};
use core::builder::*;
use rusttype;
use backends::backend;
use font_loader::system_fonts;
static FONT_COUNTER: AtomicUsize = ATOMIC_USIZE_INIT;
/// A font used for writing on a [`Layer`](struct.Layer.html).
///
/// Use [`Font::builder()`](#method.... | (context: &Context, font_data: Vec<u8>, size: f32) -> Font {
Font {
data : font_data,
font_id : FONT_COUNTER.fetch_add(1, Ordering::Relaxed),
size : size,
context : context.clone(),
}
}
/// Write text to given layer using given font
fn w... | create | identifier_name |
font.rs | use prelude::*;
use core::{self, Layer, Context, Color, Point2, Rect};
use core::builder::*;
use rusttype;
use backends::backend;
use font_loader::system_fonts;
static FONT_COUNTER: AtomicUsize = ATOMIC_USIZE_INIT;
/// A font used for writing on a [`Layer`](struct.Layer.html).
///
/// Use [`Font::builder()`](#method.... |
/// Creates a new unique font
fn create(context: &Context, font_data: Vec<u8>, size: f32) -> Font {
Font {
data : font_data,
font_id : FONT_COUNTER.fetch_add(1, Ordering::Relaxed),
size : size,
context : context.clone(),
}
}
/// Wr... | {
if let Some((font_data, _)) = system_fonts::get(&Self::build_property(&info)) {
Ok(Self::create(context, font_data, info.size))
} else {
Err(core::Error::FontError("Failed to get system font".to_string()))
}
} | identifier_body |
font.rs | use prelude::*;
use core::{self, Layer, Context, Color, Point2, Rect};
use core::builder::*;
use rusttype;
use backends::backend;
use font_loader::system_fonts;
static FONT_COUNTER: AtomicUsize = ATOMIC_USIZE_INIT;
/// A font used for writing on a [`Layer`](struct.Layer.html).
///
/// Use [`Font::builder()`](#method.... | .finish()
}
}
impl Font {
/// Returns a [font builder](support/struct.FontBuilder.html) for font construction.
///
/// # Examples
///
/// ```rust
/// # use radiant_rs::*;
/// # let display = Display::builder().hidden().build().unwrap();
/// # let renderer = Renderer::new... | .field("size", &self.size) | random_line_split |
font.rs | use prelude::*;
use core::{self, Layer, Context, Color, Point2, Rect};
use core::builder::*;
use rusttype;
use backends::backend;
use font_loader::system_fonts;
static FONT_COUNTER: AtomicUsize = ATOMIC_USIZE_INIT;
/// A font used for writing on a [`Layer`](struct.Layer.html).
///
/// Use [`Font::builder()`](#method.... |
if info.monospace {
property = property.monospace();
}
property.build()
}
}
/// A wrapper around rusttype's font cache.
pub struct FontCache {
cache : Mutex<rusttype::gpu_cache::Cache<'static>>,
queue : Mutex<Vec<(Rect<u32>, Vec<u8>)>>,
dirty : AtomicBool,
}
... | {
property = property.bold();
} | conditional_block |
type_checker.rs | use scopeguard::{guard, ScopeGuard};
use super::model::Model;
use super::cwf::*;
use super::lang::ast::*;
pub struct TypeChecker<T: Model> {
model: T,
ctxs : Vec<CtxInfo>,
}
struct CtxInfo {
syntax: Ctx,
// morphism from previous (if any) context to current
weakening: Option<Morph>,
defs: Vec<... | (&mut self, expr: &Expr) -> Result<(Tm, Ty), String> {
let (tm, _) = self.check_tm(expr)?;
let eq_ty = self.model.eq_ty(&tm, &tm);
let refl_tm = self.model.refl(&tm);
Ok((refl_tm, eq_ty))
}
fn true_tm(&mut self) -> (Tm, Ty) {
let cur_ctx_syn = &self.ctxs.last().unwrap().... | refl | identifier_name |
type_checker.rs | use scopeguard::{guard, ScopeGuard};
use super::model::Model;
use super::cwf::*;
use super::lang::ast::*;
pub struct TypeChecker<T: Model> {
model: T,
ctxs : Vec<CtxInfo>,
}
struct CtxInfo {
syntax: Ctx,
// morphism from previous (if any) context to current
weakening: Option<Morph>,
defs: Vec<... | if let Some(name) = name {
s.ctxs.last_mut().unwrap().defs.push((name.clone(), val, ty));
};
check_body(&mut s, body)
}
pub fn check_ty(&mut self, expr: &Expr) -> Result<Ty, String> {
let cur_ctx_syn = &self.ctxs.last().unwrap().syntax;
match expr {
... | random_line_split | |
type_checker.rs | use scopeguard::{guard, ScopeGuard};
use super::model::Model;
use super::cwf::*;
use super::lang::ast::*;
pub struct TypeChecker<T: Model> {
model: T,
ctxs : Vec<CtxInfo>,
}
struct CtxInfo {
syntax: Ctx,
// morphism from previous (if any) context to current
weakening: Option<Morph>,
defs: Vec<... |
fn true_tm(&mut self) -> (Tm, Ty) {
let cur_ctx_syn = &self.ctxs.last().unwrap().syntax;
let bool_ty = self.model.bool_ty(cur_ctx_syn);
let tm = self.model.true_tm(cur_ctx_syn);
(tm, bool_ty)
}
fn false_tm(&mut self) -> (Tm, Ty) {
let cur_ctx_syn = &self.ctxs.last(... | {
let (tm, _) = self.check_tm(expr)?;
let eq_ty = self.model.eq_ty(&tm, &tm);
let refl_tm = self.model.refl(&tm);
Ok((refl_tm, eq_ty))
} | identifier_body |
secp256k1_recover.rs | //! Public key recovery from [secp256k1] ECDSA signatures.
//!
//! [secp256k1]: https://en.bitcoin.it/wiki/Secp256k1
//!
//! _This module provides low-level cryptographic building blocks that must be
//! used carefully to ensure proper security. Read this documentation and
//! accompanying links thoroughly._
//!
//! Th... | /// client.send_and_confirm_transaction(&tx)?;
///
/// Ok(())
/// }
/// ```
pub fn secp256k1_recover(
hash: &[u8],
recovery_id: u8,
signature: &[u8],
) -> Result<Secp256k1Pubkey, Secp256k1RecoverError> {
#[cfg(target_os = "solana")]
{
let mut pubkey_buffer = [0u8; SECP256K1_PUBLIC_KE... | /// | random_line_split |
secp256k1_recover.rs | //! Public key recovery from [secp256k1] ECDSA signatures.
//!
//! [secp256k1]: https://en.bitcoin.it/wiki/Secp256k1
//!
//! _This module provides low-level cryptographic building blocks that must be
//! used carefully to ensure proper security. Read this documentation and
//! accompanying links thoroughly._
//!
//! Th... | (
hash: &[u8],
recovery_id: u8,
signature: &[u8],
) -> Result<Secp256k1Pubkey, Secp256k1RecoverError> {
#[cfg(target_os = "solana")]
{
let mut pubkey_buffer = [0u8; SECP256K1_PUBLIC_KEY_LENGTH];
let result = unsafe {
crate::syscalls::sol_secp256k1_recover(
... | secp256k1_recover | identifier_name |
secp256k1_recover.rs | //! Public key recovery from [secp256k1] ECDSA signatures.
//!
//! [secp256k1]: https://en.bitcoin.it/wiki/Secp256k1
//!
//! _This module provides low-level cryptographic building blocks that must be
//! used carefully to ensure proper security. Read this documentation and
//! accompanying links thoroughly._
//!
//! Th... |
pub fn to_bytes(self) -> [u8; 64] {
self.0
}
}
/// Recover the public key from a [secp256k1] ECDSA signature and
/// cryptographically-hashed message.
///
/// [secp256k1]: https://en.bitcoin.it/wiki/Secp256k1
///
/// This function is specifically intended for efficiently implementing
/// Ethereum's [... | {
Self(
<[u8; SECP256K1_PUBLIC_KEY_LENGTH]>::try_from(<&[u8]>::clone(&pubkey_vec))
.expect("Slice must be the same length as a Pubkey"),
)
} | identifier_body |
buffer.rs | //! Buffer implementation like Bytes / BytesMut.
//!
//! It is simpler and contains less unsafe code.
use std::default::Default;
use std::fmt;
use std::io::{self, Read, Write};
use std::marker::Unpin;
use std::mem;
use std::ops::{Deref, DerefMut};
use std::pin::Pin;
use std::slice;
use std::task::{Context, Poll};
use t... |
/// Add a string to the buffer.
#[inline]
pub fn put_str(&mut self, s: impl AsRef<str>) {
self.extend_from_slice(s.as_ref().as_bytes());
}
/// Return a reference to this Buffer as an UTF-8 string.
#[inline]
pub fn as_utf8_str(&self) -> Result<&str, std::str::Utf8Error> {
s... | {
self.extend_from_slice(s.as_bytes());
} | identifier_body |
buffer.rs | //! Buffer implementation like Bytes / BytesMut.
//!
//! It is simpler and contains less unsafe code.
use std::default::Default;
use std::fmt;
use std::io::{self, Read, Write};
use std::marker::Unpin;
use std::mem;
use std::ops::{Deref, DerefMut};
use std::pin::Pin;
use std::slice;
use std::task::{Context, Poll};
use t... |
#[test]
fn test_buffer() {
let mut b = Buffer::new();
b.reserve(4096);
b.start_offset = 23;
b.data.resize(b.start_offset, 0);
for _ in 0..50000 {
b.put_str("xyzzyxyzzy");
}
assert!(b.len() == 500000);
assert!(&b[1000..1010] == &b"xyzzy... | #[cfg(test)]
mod tests {
use super::*; | random_line_split |
buffer.rs | //! Buffer implementation like Bytes / BytesMut.
//!
//! It is simpler and contains less unsafe code.
use std::default::Default;
use std::fmt;
use std::io::{self, Read, Write};
use std::marker::Unpin;
use std::mem;
use std::ops::{Deref, DerefMut};
use std::pin::Pin;
use std::slice;
use std::task::{Context, Poll};
use t... | (&mut self, size: usize) {
if size == 0 {
self.clear();
return;
}
if size > self.len() {
panic!("Buffer::truncate(size): size > self.len()");
}
if self.rd_pos > size {
self.rd_pos = size;
}
self.data.truncate(size + ... | truncate | identifier_name |
buffer.rs | //! Buffer implementation like Bytes / BytesMut.
//!
//! It is simpler and contains less unsafe code.
use std::default::Default;
use std::fmt;
use std::io::{self, Read, Write};
use std::marker::Unpin;
use std::mem;
use std::ops::{Deref, DerefMut};
use std::pin::Pin;
use std::slice;
use std::task::{Context, Poll};
use t... |
}
#[inline]
fn chunk(&self) -> &[u8] {
self.bytes()
}
#[inline]
fn remaining(&self) -> usize {
self.len() - self.rd_pos
}
}
impl Deref for Buffer {
type Target = [u8];
#[inline]
fn deref(&self) -> &[u8] {
self.bytes()
}
}
impl DerefMut for Buffer... | {
// "It is recommended for implementations of advance to
// panic if cnt > self.remaining()"
panic!("read position advanced beyond end of buffer");
} | conditional_block |
udp.rs | // Copyright 2021 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use {
crate::{fastboot::InterfaceFactory, target::Target},
anyhow::{anyhow, bail, Context as _, Result},
async_io::Async,
async_net::UdpSoc... | format!("Could not parse response packet"),
))?;
match response.packet_type() {
Ok(PacketType::Fastboot) => (),
_ => {
return Err(std::io::Error::new(
... | {
// TODO(fxb/78975): unfortunately the Task requires the 'static lifetime so we have to
// copy the bytes and move them into the async block.
let packets = self.create_fastboot_packets(buf).map_err(|e| {
std::io::Error::new(
ErrorKind::Other,
... | conditional_block |
udp.rs | // Copyright 2021 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use {
crate::{fastboot::InterfaceFactory, target::Target},
anyhow::{anyhow, bail, Context as _, Result},
async_io::Async,
async_net::UdpSoc... | format!("Could not create fastboot packets: {}", e),
)
})?;
let socket = self.socket.clone();
self.write_task.replace(Box::pin(async move {
for packet in &packets {
let (out_buf, sz) = send_to_device(&packet, &so... | // TODO(fxb/78975): unfortunately the Task requires the 'static lifetime so we have to
// copy the bytes and move them into the async block.
let packets = self.create_fastboot_packets(buf).map_err(|e| {
std::io::Error::new(
ErrorKind::Other, | random_line_split |
udp.rs | // Copyright 2021 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use {
crate::{fastboot::InterfaceFactory, target::Target},
anyhow::{anyhow, bail, Context as _, Result},
async_io::Async,
async_net::UdpSoc... | (sequence: u16) -> [u8; 8] {
let mut packet = [0u8; 8];
packet[0] = 0x02;
packet[1] = 0x00;
BigEndian::write_u16(&mut packet[2..4], sequence);
BigEndian::write_u16(&mut packet[4..6], 1);
BigEndian::write_u16(&mut packet[6..8], MAX_SIZE);
packet
}
fn make_empty_fastboot_packet(sequence: u16)... | make_init_packet | identifier_name |
udp.rs | // Copyright 2021 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use {
crate::{fastboot::InterfaceFactory, target::Target},
anyhow::{anyhow, bail, Context as _, Result},
async_io::Async,
async_net::UdpSoc... |
async fn make_sender_socket(addr: SocketAddr) -> Result<UdpSocket> {
let socket: std::net::UdpSocket = match addr {
SocketAddr::V4(ref _saddr) => socket2::Socket::new(
socket2::Domain::IPV4,
socket2::Type::DGRAM,
Some(socket2::Protocol::UDP),
)
.context("... | {
let mut buf = [0u8; 1500]; // Responses should never get this big.
timeout(REPLY_TIMEOUT, Box::pin(socket.recv(&mut buf[..])))
.await
.map_err(|_| anyhow!("Timed out waiting for reply"))?
.map_err(|e| anyhow!("Recv error: {}", e))
.map(|size| (buf, size))
} | identifier_body |
peer_connection.rs | and the
// following disclaimer in the documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
// products derived from this software without specific prior written permission.
//
// THIS ... |
#[cfg(feature = "rpc")]
#[tracing::instrument("peer_connection::connect_rpc", level="trace", skip(self), fields(peer_node_id = self.peer_node_id.to_string().as_str()))]
pub async fn connect_rpc<T>(&mut self) -> Result<T, RpcError>
where T: From<RpcClient> + NamedProtocolService {
self.connect_... | {
let substream = self.open_substream(protocol_id).await?;
Ok(framing::canonical(substream.stream, max_frame_size))
} | identifier_body |
peer_connection.rs | the
// following disclaimer in the documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
// products derived from this software without specific prior written permission.
//
// THIS SOFT... | ,
Disconnect(silent, reply_tx) => {
debug!(
target: LOG_TARGET,
"[{}] Disconnect{}requested for {} connection to peer '{}'",
self,
if silent { " (silent) " } else { " " },
self.direction,
... | {
let tracing_id = tracing::Span::current().id();
let span = span!(Level::TRACE, "handle_request");
span.follows_from(tracing_id);
let result = self.open_negotiated_protocol_stream(protocol_id).instrument(span).await;
log_if_error_fmt!(
... | conditional_block |
peer_connection.rs | and the
// following disclaimer in the documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
// products derived from this software without specific prior written permission.
//
// THIS ... | (&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
write!(
f,
"Id: {}, Node ID: {}, Direction: {}, Peer Address: {}, Age: {:.0?}, #Substreams: {}, #Refs: {}",
self.id,
self.peer_node_id.short_str(),
self.direction,
self.address... | fmt | identifier_name |
peer_connection.rs | conditions and the
// following disclaimer in the documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
// products derived from this software without specific prior written permission.
... | address: Arc<Multiaddr>,
direction: ConnectionDirection,
started_at: Instant,
substream_counter: AtomicRefCounter,
handle_counter: Arc<()>,
peer_identity_claim: Option<PeerIdentityClaim>,
}
impl PeerConnection {
pub(crate) fn new(
id: ConnectionId,
request_tx: mpsc::Sender<P... | peer_features: PeerFeatures,
request_tx: mpsc::Sender<PeerConnectionRequest>, | random_line_split |
lib.rs | //! Usage
//! -----
//!
//! For simple applications, use one of the utility functions `listen` and `connect`:
//!
//! `listen` accpets a string that represents a socket address and a Factory, see
//! [Architecture](#architecture).
//!
//! ```no_run
//! // A WebSocket echo server
//!
//! use ws::listen;
//!
//! listen("... |
}
result.map(|_| self)
}
/// Queue an outgoing connection on this WebSocket. This method may be called multiple times,
/// but the actuall connections will not be established until after `run` is called.
pub fn connect(&mut self, url: url::Url) -> Result<&mut WebSocket<F>> {
l... | {
return self.run()
} | conditional_block |
lib.rs | //! Usage
//! -----
//!
//! For simple applications, use one of the utility functions `listen` and `connect`:
//!
//! `listen` accpets a string that represents a socket address and a Factory, see
//! [Architecture](#architecture).
//!
//! ```no_run
//! // A WebSocket echo server
//!
//! use ws::listen;
//!
//! listen("... | <U, F, H>(url: U, factory: F) -> Result<()>
where
U: Borrow<str>,
F: FnMut(Sender) -> H,
H: Handler
{
let mut ws = try!(WebSocket::new(factory));
let parsed = try!(
url::Url::parse(url.borrow())
.map_err(|err| Error::new(
ErrorKind::Internal,
... | connect | identifier_name |
lib.rs | //! Usage
//! -----
//!
//! For simple applications, use one of the utility functions `listen` and `connect`:
//!
//! `listen` accpets a string that represents a socket address and a Factory, see
//! [Architecture](#architecture).
//!
//! ```no_run
//! // A WebSocket echo server
//!
//! use ws::listen;
//!
//! listen("... | let mut config = EventLoopConfig::new();
config.notify_capacity(max + 1000);
WebSocket::with_config(factory, config)
}
/// Create a new WebSocket with a Factory and use the event loop config to provide settings for
/// the event loop.
pub fn with_config(factory: F, config: Event... | where F: Factory
{
/// Create a new WebSocket using the given Factory to create handlers.
pub fn new(mut factory: F) -> Result<WebSocket<F>> {
let max = factory.settings().max_connections; | random_line_split |
mod.rs | use std::mem;
use std::time::SystemTime;
#[cfg(feature="dynamic_mem")]
const MAX_MEMORY_SLOTS: usize = 1024 * 1024 * 2;
#[cfg(not(feature="dynamic_mem"))]
const MAX_MEMORY_SLOTS: usize = 1024 * 128;
type Bits = u128;
const MARK_BITS_PER_SLOT: usize = mem::size_of::<Bits>();
const MARK_BITS: usize = MAX_MEMORY_SLO... | (&mut self, obj: usize, next: usize) {
self.mem[obj + 1] = next;
}
fn mark_object(&mut self, obj: usize) {
self.mark_bits[obj / MARK_BITS_PER_SLOT] |= 1 << (obj % MARK_BITS_PER_SLOT);
}
fn unmark_object(&mut self, obj: usize) {
self.mark_bits[obj / MARK_BITS_PER_SLOT] &=!(1 << (obj % MARK_BITS_PE... | set_fl_next | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.