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 |
|---|---|---|---|---|
error.rs | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
use core::{convert::TryInto, fmt, ptr::NonNull, task::Poll};
use errno::{errno, Errno};
use libc::c_char;
use s2n_tls_sys::*;
use std::{convert::TryFrom, ffi::CStr};
#[non_exhaustive]
#[derive(Debug, PartialEq... | (&self) -> bool {
matches!(self.kind(), ErrorType::Blocked)
}
}
#[cfg(feature = "quic")]
impl Error {
/// s2n-tls does not send specific errors.
///
/// However, we can attempt to map local errors into the alerts
/// that we would have sent if we sent alerts.
///
/// This API is cur... | is_retryable | identifier_name |
constants.rs | use std::os::raw::{c_int, c_uint};
// Standard return values from Symisc public interfaces
const SXRET_OK: c_int = 0; /* Not an error */
const SXERR_MEM: c_int = -1; /* Out of memory */
const SXERR_IO: c_int = -2; /* IO error */
const SXERR_EMPTY: c_int = -3; /* Empty field */
const SXERR_LOCKED: c_int = -4; /* L... | pub const UNQLITE_SYNC_NORMAL: c_int = 0x00002;
pub const UNQLITE_SYNC_FULL: c_int = 0x00003;
pub const UNQLITE_SYNC_DATAONLY: c_int = 0x00010;
// File Locking Levels
//
// UnQLite uses one of these integer values as the second
// argument to calls it makes to the xLock() and xUnlock() methods
// of an [unqlite_io_meth... | random_line_split | |
fetch.rs | use std::io::{self, Write};
use std::cmp::min;
use std::collections::{HashMap, HashSet, VecDeque};
use std::net::SocketAddr;
use std::str::from_utf8;
use std::sync::{Arc, Mutex};
use std::time::{Instant, Duration};
use std::u64;
use abstract_ns::Address;
use futures::{Sink, Async, Stream};
use futures::future::{Future... | #[derive(Debug)]
struct State {
offset: u64,
eof: u32,
last_line: Vec<u8>,
last_request: Instant,
}
#[derive(Debug)]
struct Cursor {
url: Arc<Url>,
state: Option<State>,
}
struct Requests {
cursors: VecDeque<Arc<Mutex<Cursor>>>,
timeout: Timeout,
}
#[derive(Debug)]
pub struct Request ... | #[cfg(feature="tls_rustls")] use webpki_roots;
| random_line_split |
fetch.rs | use std::io::{self, Write};
use std::cmp::min;
use std::collections::{HashMap, HashSet, VecDeque};
use std::net::SocketAddr;
use std::str::from_utf8;
use std::sync::{Arc, Mutex};
use std::time::{Instant, Duration};
use std::u64;
use abstract_ns::Address;
use futures::{Sink, Async, Stream};
use futures::future::{Future... | "/etc/ssl/certs/ca-certificates.crt", e);
}
}
cfg.root_store.add_server_trust_anchors(
&webpki_roots::TLS_SERVER_ROOTS);
cfg
});
let cfg = Config::new().done();
return Box::new(
join_all(urls_by_host.into_iter().map(move |(host, lis... | {
use std::io::BufReader;
use std::fs::File;
if urls_by_host.len() == 0 {
return Box::new(ok(()));
}
let resolver = resolver.clone();
let tls = Arc::new({
let mut cfg = ClientConfig::new();
let read_root = File::open("/etc/ssl/certs/ca-certificates.crt")
.map... | identifier_body |
fetch.rs | use std::io::{self, Write};
use std::cmp::min;
use std::collections::{HashMap, HashSet, VecDeque};
use std::net::SocketAddr;
use std::str::from_utf8;
use std::sync::{Arc, Mutex};
use std::time::{Instant, Duration};
use std::u64;
use abstract_ns::Address;
use futures::{Sink, Async, Stream};
use futures::future::{Future... | (resolver: &Router, urls_by_host: HashMap<String, Vec<Arc<Url>>>)
-> Box<Future<Item=(), Error=()>>
{
let resolver = resolver.clone();
let cfg = Config::new()
.keep_alive_timeout(Duration::new(25, 0))
.done();
return Box::new(
join_all(urls_by_host.into_iter().map(move |(host, list... | http | identifier_name |
time.rs | //!Constants and structures from time classes
//!
//! This includes include/uapi/linux/time.h, //include/linux/time.h, and /include/linux/time64.h
///A structure that contains the number of seconds and nanoseconds since an epoch.
///
///If in doubt, assume we're talking about the UNIX epoch.
#[repr(C)]
#[derive(Debug... |
///The amount of time left until expiration (Need to verify)
pub it_value: timeval
}
///A system-wide clock that measures time from the "real world"
///
///This clock **is** affected by discontinuous jumps in system time, NTP, and user changes
pub const CLOCK_REALTIME: ::clockid_t = 0;
///A clock that me... | ///The period of time this timer should run for (Need to verify)
pub it_interval: timeval, | random_line_split |
time.rs | //!Constants and structures from time classes
//!
//! This includes include/uapi/linux/time.h, //include/linux/time.h, and /include/linux/time64.h
///A structure that contains the number of seconds and nanoseconds since an epoch.
///
///If in doubt, assume we're talking about the UNIX epoch.
#[repr(C)]
#[derive(Debug... | {
///The number of seconds contained in this timespec
pub tv_sec: ::time_t,
///The number of nanoseconds contained in this timespec
pub tv_nsec: ::c_long
}
impl timespec {
///Creates a new timespec with both values defaulting to zero
pub fn new() -> timespec {
timespec { tv_sec: ... | timespec | identifier_name |
tls-server.rs | // SPDX-FileCopyrightText: Copyright (c) 2017-2023 slowtec GmbH <post@slowtec.de>
// SPDX-License-Identifier: MIT OR Apache-2.0
// load_certs() and particially load_keys() functions were copied from an example of the tokio tls library, available at:
// https://github.com/tokio-rs/tls/blob/master/tokio-rustls/examples/... | (socket_addr: SocketAddr) -> anyhow::Result<()> {
println!("Starting up server on {socket_addr}");
let listener = TcpListener::bind(socket_addr).await?;
let server = Server::new(listener);
let on_connected = |stream, _socket_addr| async move {
let cert_path = Path::new("./pki/server.pem");
... | server_context | identifier_name |
tls-server.rs | // SPDX-FileCopyrightText: Copyright (c) 2017-2023 slowtec GmbH <post@slowtec.de>
// SPDX-License-Identifier: MIT OR Apache-2.0
// load_certs() and particially load_keys() functions were copied from an example of the tokio tls library, available at:
// https://github.com/tokio-rs/tls/blob/master/tokio-rustls/examples/... | Ok(values) => future::ready(Ok(Response::ReadInputRegisters(values))),
Err(err) => future::ready(Err(err)),
}
}
Request::ReadHoldingRegisters(addr, cnt) => {
match register_read(&self.holding_registers.lock().unwrap(), addr,... | fn call(&self, req: Self::Request) -> Self::Future {
match req {
Request::ReadInputRegisters(addr, cnt) => {
match register_read(&self.input_registers.lock().unwrap(), addr, cnt) { | random_line_split |
tls-server.rs | // SPDX-FileCopyrightText: Copyright (c) 2017-2023 slowtec GmbH <post@slowtec.de>
// SPDX-License-Identifier: MIT OR Apache-2.0
// load_certs() and particially load_keys() functions were copied from an example of the tokio tls library, available at:
// https://github.com/tokio-rs/tls/blob/master/tokio-rustls/examples/... | Err(err) => future::ready(Err(err)),
}
}
Request::WriteSingleRegister(addr, value) => {
match register_write(
&mut self.holding_registers.lock().unwrap(),
addr,
std::slice::from_ref(&v... | {
match req {
Request::ReadInputRegisters(addr, cnt) => {
match register_read(&self.input_registers.lock().unwrap(), addr, cnt) {
Ok(values) => future::ready(Ok(Response::ReadInputRegisters(values))),
Err(err) => future::ready(Err(err)),
... | identifier_body |
packer.rs | // Copyright 2020 The Grin Developers
//
// 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 agree... |
/// Get Sender info. It is needed to send the response back
pub fn get_recipient(&self) -> Option<DalekPublicKey> {
self.recipient.clone()
}
/// Convert this slate back to the resulting slate. Since the slate pack contain only the change set,
/// to recover the data it is required original slate to merge with... | {
self.sender.clone()
} | identifier_body |
packer.rs | // Copyright 2020 The Grin Developers
//
// 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 agree... | (&self) -> SlatePurpose {
self.content.clone()
}
/// Get Sender info. It is needed to send the response back
pub fn get_sender(&self) -> Option<DalekPublicKey> {
self.sender.clone()
}
/// Get Sender info. It is needed to send the response back
pub fn get_recipient(&self) -> Option<DalekPublicKey> {
self.r... | get_content | identifier_name |
packer.rs | // Copyright 2020 The Grin Developers
//
// 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 agree... | 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31, 32, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32,
];
let sk = SecretKey::from_slice(&bytes_32).unwrap();
let secp = Secp25... | random_line_split | |
core.rs | // Copyright 2020 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::allowed_hosts::{HostsStore, OutboundRequestFilter};
use crate::connection::Connection;
use crate::websocket;
use crate::websocket::TSWebsocketStream;
use futures::channel::mpsc;
use futures::stream::{SplitSi... | (&self, uri: &str) -> TSWebsocketStream {
let ws_stream = match websocket::Connection::new(uri).connect().await {
Ok(ws_stream) => {
info!("* connected to local websocket server at {}", uri);
ws_stream
}
Err(WebsocketConnectionError::Connection... | connect_websocket | identifier_name |
core.rs | // Copyright 2020 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::allowed_hosts::{HostsStore, OutboundRequestFilter};
use crate::connection::Connection;
use crate::websocket;
use crate::websocket::TSWebsocketStream;
use futures::channel::mpsc;
use futures::stream::{SplitSi... | return_address,
),
Request::Send(conn_id, data, closed) => {
self.handle_proxy_send(controller_sender, conn_id, data, closed)
}
}
}
/// Start all subsystems
pub async fn run(&mut self) {
let websocket_stream = self.connect... | {
// try to treat each received mix message as a service provider request
let deserialized_request = match Request::try_from_bytes(raw_request) {
Ok(request) => request,
Err(err) => {
error!("Failed to deserialized received request! - {}", err);
re... | identifier_body |
core.rs | // Copyright 2020 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::allowed_hosts::{HostsStore, OutboundRequestFilter};
use crate::connection::Connection;
use crate::websocket;
use crate::websocket::TSWebsocketStream;
use futures::channel::mpsc;
use futures::stream::{SplitSi... | mut mix_reader: mpsc::UnboundedReceiver<(Response, Recipient)>,
) {
// TODO: wire SURBs in here once they're available
while let Some((response, return_address)) = mix_reader.next().await {
// make'request' to native-websocket client
let response_message = ClientReque... | mut websocket_writer: SplitSink<TSWebsocketStream, Message>, | random_line_split |
config.rs | // Copyright 2012-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-MI... |
pub fn is_test_or_bench(attr: &ast::Attribute) -> bool {
attr.check_name("test") || attr.check_name("bench")
}
| {
attr.check_name("cfg")
} | identifier_body |
config.rs | // Copyright 2012-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-MI... | (&mut self, item: ast::TraitItem) -> SmallVector<ast::TraitItem> {
fold::noop_fold_trait_item(configure!(self, item), self)
}
fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
// Don't configure interpolated AST (c.f. #34171).
// Interpolated AST will get configured once the surroundi... | fold_trait_item | identifier_name |
config.rs | // Copyright 2012-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-MI... |
pub fn configure_foreign_mod(&mut self, foreign_mod: ast::ForeignMod) -> ast::ForeignMod {
ast::ForeignMod {
abi: foreign_mod.abi,
items: foreign_mod.items.into_iter().filter_map(|item| self.configure(item)).collect(),
}
}
fn configure_variant_data(&mut self, vdata:... | } | random_line_split |
login.rs | use super::Encode;
use bitflags::bitflags;
use byteorder::{LittleEndian, WriteBytesExt};
use bytes::BytesMut;
use io::{Cursor, Write};
use std::{borrow::Cow, io};
uint_enum! {
#[repr(u32)]
#[derive(PartialOrd)]
pub enum FeatureLevel {
SqlServerV7 = 0x70000000,
SqlServer2000 = 0x71000000,
... |
}
/// the login packet
pub struct LoginMessage<'a> {
/// the highest TDS version the client supports
pub tds_version: FeatureLevel,
/// the requested packet size
pub packet_size: u32,
/// the version of the interface library
pub client_prog_ver: u32,
/// the process id of the client applic... | {
if self as u8 >= FeatureLevel::SqlServer2005 as u8 {
8
} else {
4
}
} | identifier_body |
login.rs | use super::Encode;
use bitflags::bitflags;
use byteorder::{LittleEndian, WriteBytesExt};
use bytes::BytesMut;
use io::{Cursor, Write};
use std::{borrow::Cow, io};
uint_enum! {
#[repr(u32)]
#[derive(PartialOrd)]
pub enum FeatureLevel {
SqlServerV7 = 0x70000000,
SqlServer2000 = 0x71000000,
... | ;
cursor.write_u16::<LittleEndian>(length as u16)?;
continue;
}
// jump into the data portion of the output
let bak = cursor.position();
cursor.set_position(data_offset as u64);
for codepoint in value.encode_utf16() {
... | {
0
} | conditional_block |
login.rs | use super::Encode;
use bitflags::bitflags;
use byteorder::{LittleEndian, WriteBytesExt};
use bytes::BytesMut;
use io::{Cursor, Write};
use std::{borrow::Cow, io};
uint_enum! {
#[repr(u32)]
#[derive(PartialOrd)]
pub enum FeatureLevel {
SqlServerV7 = 0x70000000,
SqlServer2000 = 0x71000000,
... | (self) -> u8 {
if self as u8 >= FeatureLevel::SqlServer2005 as u8 {
8
} else {
4
}
}
}
/// the login packet
pub struct LoginMessage<'a> {
/// the highest TDS version the client supports
pub tds_version: FeatureLevel,
/// the requested packet size
pub ... | done_row_count_bytes | identifier_name |
login.rs | use super::Encode;
use bitflags::bitflags;
use byteorder::{LittleEndian, WriteBytesExt};
use bytes::BytesMut;
use io::{Cursor, Write};
use std::{borrow::Cow, io};
uint_enum! {
#[repr(u32)]
#[derive(PartialOrd)]
pub enum FeatureLevel {
SqlServerV7 = 0x70000000,
SqlServer2000 = 0x71000000,
... | // ibSSPI
if i == 10 {
let length = if let Some(ref bytes) = self.integrated_security {
let bak = cursor.position();
cursor.set_position(data_offset as u64);
cursor.write_all(bytes)?;
data_offset +=... | cursor.write_u16::<LittleEndian>(data_offset as u16)?;
| random_line_split |
vdpa.rs | // Copyright (C) 2021 Red Hat, Inc. All rights reserved.
// SPDX-License-Identifier: Apache-2.0 or BSD-3-Clause
//! Kernel-based vhost-vdpa backend.
use std::fs::{File, OpenOptions};
use std::io::Error as IOError;
use std::os::raw::{c_uchar, c_uint};
use std::os::unix::fs::OpenOptionsExt;
use std::os::unix::io::{AsRa... | (&self) -> u64 {
self.backend_features_acked
}
fn set_backend_features_acked(&mut self, features: u64) {
self.backend_features_acked = features;
}
}
#[cfg(test)]
mod tests {
const VHOST_VDPA_PATH: &str = "/dev/vhost-vdpa-0";
use std::alloc::{alloc, dealloc, Layout};
use vm_mem... | get_backend_features_acked | identifier_name |
vdpa.rs | // Copyright (C) 2021 Red Hat, Inc. All rights reserved.
// SPDX-License-Identifier: Apache-2.0 or BSD-3-Clause
//! Kernel-based vhost-vdpa backend.
use std::fs::{File, OpenOptions};
use std::io::Error as IOError;
use std::os::raw::{c_uchar, c_uint};
use std::os::unix::fs::OpenOptionsExt;
use std::os::unix::io::{AsRa... | let config = VringConfigData {
queue_max_size: 32,
queue_size: 32,
flags: 0,
desc_table_addr: 0x1000,
used_ring_addr: 0x2000,
avail_ring_addr: 0x3000,
log_addr: None,
};
vdpa.set_vring_addr(0, &config).unwrap();
... | random_line_split | |
vdpa.rs | // Copyright (C) 2021 Red Hat, Inc. All rights reserved.
// SPDX-License-Identifier: Apache-2.0 or BSD-3-Clause
//! Kernel-based vhost-vdpa backend.
use std::fs::{File, OpenOptions};
use std::io::Error as IOError;
use std::os::raw::{c_uchar, c_uint};
use std::os::unix::fs::OpenOptionsExt;
use std::os::unix::io::{AsRa... |
}
impl<AS: GuestAddressSpace> AsRawFd for VhostKernVdpa<AS> {
fn as_raw_fd(&self) -> RawFd {
self.fd.as_raw_fd()
}
}
impl<AS: GuestAddressSpace> VhostKernFeatures for VhostKernVdpa<AS> {
fn get_backend_features_acked(&self) -> u64 {
self.backend_features_acked
}
fn set_backend_fe... | {
&self.mem
} | identifier_body |
lib.rs | use core::fmt;
use std::convert::{TryFrom, TryInto};
use std::ops::Deref;
use std::str::FromStr;
use bulletproofs::r1cs::Prover;
use bulletproofs::{BulletproofGens, PedersenGens};
use bulletproofs_gadgets::fixed_deposit_tree::builder::{FixedDepositTree, FixedDepositTreeBuilder};
use bulletproofs_gadgets::poseidon::bui... |
};
if note_val.len()!= 128 {
return Err(OpStatusCode::InvalidNoteSecrets);
}
let r = hex::decode(¬e_val[..64])
.map(|v| v.try_into())
.map(|r| r.map(Scalar::from_bytes_mod_order))
.map_err(|_| OpStatusCode::InvalidHexLength)?
.map_err(|_| OpStatusCode::HexParsingFailed)?;
let nullifier = h... | {
let bn = parts[4].parse().map_err(|_| OpStatusCode::InvalidNoteBlockNumber)?;
(Some(bn), parts[5])
} | conditional_block |
lib.rs | use core::fmt;
use std::convert::{TryFrom, TryInto};
use std::ops::Deref;
use std::str::FromStr;
use bulletproofs::r1cs::Prover;
use bulletproofs::{BulletproofGens, PedersenGens};
use bulletproofs_gadgets::fixed_deposit_tree::builder::{FixedDepositTree, FixedDepositTreeBuilder};
use bulletproofs_gadgets::poseidon::bui... | (opts: PoseidonHasherOptions) -> Self {
let pc_gens = PedersenGens::default();
let bp_gens = opts
.bp_gens
.clone()
.unwrap_or_else(|| BulletproofGens::new(BULLETPROOF_GENS_SIZE, 1));
let inner = PoseidonBuilder::new(opts.width)
.sbox(PoseidonSbox::Exponentiation3)
.bulletproof_gens(bp_gens)
.p... | with_options | identifier_name |
lib.rs | use core::fmt;
use std::convert::{TryFrom, TryInto};
use std::ops::Deref;
use std::str::FromStr;
use bulletproofs::r1cs::Prover;
use bulletproofs::{BulletproofGens, PedersenGens};
use bulletproofs_gadgets::fixed_deposit_tree::builder::{FixedDepositTree, FixedDepositTreeBuilder};
use bulletproofs_gadgets::poseidon::bui... |
pub fn hash(&self, left: Uint8Array, right: Uint8Array) -> Result<Uint8Array, JsValue> {
let xl = ScalarWrapper::try_from(left)?;
let xr = ScalarWrapper::try_from(right)?;
let hash = Poseidon_hash_2(*xl, *xr, &self.inner);
Ok(ScalarWrapper(hash).into())
}
}
#[wasm_bindgen]
pub struct NoteGenerator {
hashe... | {
let pc_gens = PedersenGens::default();
let bp_gens = opts
.bp_gens
.clone()
.unwrap_or_else(|| BulletproofGens::new(BULLETPROOF_GENS_SIZE, 1));
let inner = PoseidonBuilder::new(opts.width)
.sbox(PoseidonSbox::Exponentiation3)
.bulletproof_gens(bp_gens)
.pedersen_gens(pc_gens)
.build();
S... | identifier_body |
lib.rs | use core::fmt;
use std::convert::{TryFrom, TryInto};
use std::ops::Deref;
use std::str::FromStr;
use bulletproofs::r1cs::Prover;
use bulletproofs::{BulletproofGens, PedersenGens};
use bulletproofs_gadgets::fixed_deposit_tree::builder::{FixedDepositTree, FixedDepositTreeBuilder};
use bulletproofs_gadgets::poseidon::bui... | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
NoteVersion::V1 => write!(f, "v1"),
}
}
}
impl FromStr for NoteVersion {
type Err = OpStatusCode;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"v1" => Ok(NoteVersion::V1),
_ => Err(OpStatusCode::InvalidNoteVersio... |
impl fmt::Display for NoteVersion { | random_line_split |
aggr.rs | use crate::lang::{Closure, Argument, ExecutionContext, Value, ColumnType, RowsReader, Row, JobJoinHandle};
use crate::lang::stream::{Readable, ValueSender};
use crate::lang::errors::{CrushResult, argument_error, mandate, error};
use crate::lib::command_util::{find_field, find_field_from_str};
use crate::lang::printer::... | (config: Config, printer: &Printer, env: &Env, mut input: impl Readable, uninitialized_output: ValueSender) -> JobResult<()> {
let (writer_output, writer_input) = bounded::<Row>(16);
let mut output_names = input.get_type().iter().map(|t| t.name.clone()).collect::<Vec<Option<String>>>();
output_names.remove... | run | identifier_name |
aggr.rs | use crate::lang::{Closure, Argument, ExecutionContext, Value, ColumnType, RowsReader, Row, JobJoinHandle};
use crate::lang::stream::{Readable, ValueSender};
use crate::lang::errors::{CrushResult, argument_error, mandate, error};
use crate::lib::command_util::{find_field, find_field_from_str};
use crate::lang::printer::... | }))
}
pub fn pump_table(
job_output: &mut impl Readable,
outputs: Vec<OutputStream>,
output_definition: &Vec<(String, usize, Closure)>) -> JobResult<()> {
let stream_to_column_mapping = output_definition.iter().map(|(_, off, _)| *off).collect::<Vec<usize>>();
loop {
match job_outpu... | Ok(()) | random_line_split |
bpf.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#![allow(non_snake_case)]
pub use libc::sock_filter;
use syscalls::Errno;
use syscalls::Sysno;
us... |
let prog = libc::sock_fprog {
// Note: length is guaranteed to be less than `u16::MAX` because of
// the above check.
len: len as u16,
filter: self.filter.as_ptr() as *mut _,
};
let ptr = &prog as *const libc::sock_fprog;
let value = Er... | {
return Err(Errno::EINVAL);
} | conditional_block |
bpf.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#![allow(non_snake_case)]
pub use libc::sock_filter;
use syscalls::Errno;
use syscalls::Sysno;
us... | (&self) -> bool {
self.filter.is_empty()
}
fn install(&self, flags: FilterFlags) -> Result<i32, Errno> {
let len = self.filter.len();
if len == 0 || len > BPF_MAXINSNS {
return Err(Errno::EINVAL);
}
let prog = libc::sock_fprog {
// Note: length ... | is_empty | identifier_name |
bpf.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#![allow(non_snake_case)]
pub use libc::sock_filter;
use syscalls::Errno;
use syscalls::Sysno;
us... |
}
/// Returns a seccomp-bpf filter containing the given list of instructions.
///
/// This can be concatenated with other seccomp-BPF programs.
///
/// Note that this is not a true BPF program. Seccomp-bpf is a subset of BPF and
/// so many instructions are not available.
///
/// When executing instructions, the BPF ... | {
filter.push(self)
} | identifier_body |
bpf.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#![allow(non_snake_case)]
pub use libc::sock_filter;
use syscalls::Errno;
use syscalls::Sysno;
us... | pub const AUDIT_ARCH_X86_64: u32 = EM_X86_64 | __AUDIT_ARCH_64BIT | __AUDIT_ARCH_LE;
pub const AUDIT_ARCH_ARM: u32 = EM_ARM | __AUDIT_ARCH_LE;
pub const AUDIT_ARCH_AARCH64: u32 = EM_AARCH64 | __AUDIT_ARCH_64BIT | __AUDIT_ARCH_LE;
pub const AUDIT_ARCH_MIPS: u32 = EM_MIPS;
pub const AUDIT_ARCH_PPC: u32 = EM_PPC;
pub cons... | const __AUDIT_ARCH_64BIT: u32 = 0x8000_0000;
const __AUDIT_ARCH_LE: u32 = 0x4000_0000;
// These are defined in `/include/uapi/linux/audit.h`.
pub const AUDIT_ARCH_X86: u32 = EM_386 | __AUDIT_ARCH_LE; | random_line_split |
vec.rs | // This file is part of ICU4X. For terms of use, please see the file
// called LICENSE at the top level of the ICU4X source tree
// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).
use crate::ule::*;
use alloc::vec::Vec;
use core::cmp::{Ord, Ordering, PartialOrd};
use core::fmt;
use core::ops::De... | > Vec<u8> {
match self {
VarZeroVec::Owned(vec) => vec.into_bytes(),
VarZeroVec::Borrowed(vec) => vec.as_bytes().to_vec(),
}
}
/// Return whether the [`VarZeroVec`] is operating on owned or borrowed
/// data. [`VarZeroVec::into_owned()`] and [`VarZeroVec::make_mut()`... | es(self) - | identifier_name |
vec.rs | // This file is part of ICU4X. For terms of use, please see the file
// called LICENSE at the top level of the ICU4X source tree
// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).
use crate::ule::*;
use alloc::vec::Vec;
use core::cmp::{Ord, Ordering, PartialOrd};
use core::fmt;
use core::ops::De... | <'a, T:?Sized, F> From<VarZeroVecOwned<T, F>> for VarZeroVec<'a, T, F> {
#[inline]
fn from(other: VarZeroVecOwned<T, F>) -> Self {
VarZeroVec::Owned(other)
}
}
impl<'a, T:?Sized, F> From<&'a VarZeroSlice<T, F>> for VarZeroVec<'a, T, F> {
fn from(other: &'a VarZeroSlice<T, F>) -> Self {
... | VarZeroSlice::fmt(self, f)
}
}
impl | identifier_body |
vec.rs | // This file is part of ICU4X. For terms of use, please see the file
// called LICENSE at the top level of the ICU4X source tree
// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).
use crate::ule::*;
use alloc::vec::Vec;
use core::cmp::{Ord, Ordering, PartialOrd};
use core::fmt;
use core::ops::De... | /// # use zerovec::ule::ZeroVecError;
/// use zerovec::ule::*;
/// use zerovec::VarZeroVec;
/// use zerovec::ZeroSlice;
/// use zerovec::ZeroVec;
///
/// // The structured list correspond to the list of integers.
/// let numbers: &[&[u32]] = &[
/// &[12, 25, 38],
/// &[39179, 100],
/// &[42, 55555],
/// ... | /// # use std::str::Utf8Error; | random_line_split |
mod.rs | .
//!
//! An endpoint is concerned with executing the abstract behaviours given by the backend in terms
//! of the actions of the endpoint types. This means translating Redirect errors to the correct
//! Redirect http response for example or optionally sending internal errors to loggers. The
//! frontends, which are th... |
}
impl<'a, W: WebRequest, S: Scopes<W> + 'a +?Sized> Scopes<W> for &'a mut S {
fn scopes(&mut self, request: &mut W) -> &[Scope] {
(**self).scopes(request)
}
}
impl<'a, W: WebRequest, S: Scopes<W> + 'a +?Sized> Scopes<W> for Box<S> {
fn scopes(&mut self, request: &mut W) -> &[Scope] {
(**... | {
self
} | identifier_body |
mod.rs | .
//!
//! An endpoint is concerned with executing the abstract behaviours given by the backend in terms
//! of the actions of the endpoint types. This means translating Redirect errors to the correct
//! Redirect http response for example or optionally sending internal errors to loggers. The
//! frontends, which are th... | (
&mut self, request: &mut W, solicitation: Solicitation,
) -> OwnerConsent<W::Response> {
(**self).check_consent(request, solicitation)
}
}
impl<W: WebRequest> Scopes<W> for [Scope] {
fn scopes(&mut self, _: &mut W) -> &[Scope] {
self
}
}
impl<W: WebRequest> Scopes<W> for Vec<... | check_consent | identifier_name |
mod.rs | flows.
//!
//! An endpoint is concerned with executing the abstract behaviours given by the backend in terms
//! of the actions of the endpoint types. This means translating Redirect errors to the correct
//! Redirect http response for example or optionally sending internal errors to loggers. The
//! frontends, which ... | mod query;
#[cfg(test)]
mod tests;
use std::borrow::Cow;
use std::marker::PhantomData;
pub use crate::primitives::authorizer::Authorizer;
pub use crate::primitives::issuer::Issuer;
pub use crate::primitives::registrar::Registrar;
pub use crate::primitives::scope::Scope;
use crate::code_grant::resource::{Error as Re... | random_line_split | |
lib.rs | #[macro_use] extern crate bitflags;
#[macro_use] extern crate enum_primitive;
extern crate libc;
pub use libc::{c_void, c_char, c_int, c_long, c_ulong, size_t, c_double, off_t};
use std::convert::From;
#[link(name = "mpg123")]
extern {
pub fn mpg123_init() -> c_int;
pub fn mpg123_exit();
pub fn mpg123_ne... | (&self) -> usize {
unsafe {
mpg123_encsize(self.bits()) as usize
}
}
}
bitflags!{
pub flags ChannelCount : i32 {
const CHAN_MONO = 1,
const CHAN_STEREO = 2,
}
}
| size | identifier_name |
lib.rs | #[macro_use] extern crate bitflags;
#[macro_use] extern crate enum_primitive;
extern crate libc;
pub use libc::{c_void, c_char, c_int, c_long, c_ulong, size_t, c_double, off_t};
use std::convert::From;
#[link(name = "mpg123")]
extern {
pub fn mpg123_init() -> c_int;
pub fn mpg123_exit();
pub fn mpg123_ne... |
// Decoder selection
pub fn mpg123_decoders() -> *const *const c_char;
pub fn mpg123_supported_decoders() -> *const *const c_char;
pub fn mpg123_decoder(handle: *mut Mpg123Handle) -> c_int;
pub fn mpg123_current_decoder(handle: *mut Mpg123Handle) -> *const c_char;
// Output format
pub fn m... | pub fn mpg123_strerror(handle: *mut Mpg123Handle) -> *const c_char;
pub fn mpg123_errcode(handle: *mut Mpg123Handle) -> Mpg123Error; | random_line_split |
combat.rs | use super::*;
use rand::Rng;
use crate::r#const::*;
use crate::types::*;
use crate::types::Tcod;
use crate::types::Messages;
use crate::func::*;
use crate::types::object::Object;
use tcod::input::{self, Event, Mouse};
use tcod::colors::{self, Color};
/// returns a clicked monster inside FOV up to a range, or None if r... | game.log.add(format!("The eyes of {} look vacant, as he starts to stumble around!",
objects[monster_id].name),
colors::LIGHT_GREEN);
UseResult::UsedUp
} else { // no enemy fonud within maximum range
game.log.add("No enemy is close en... | objects[monster_id].ai = Some(Ai::Confused {
previous_ai: Box::new(old_ai),
num_turns: CONFUSE_NUM_TURNS,
}); | random_line_split |
combat.rs | use super::*;
use rand::Rng;
use crate::r#const::*;
use crate::types::*;
use crate::types::Tcod;
use crate::types::Messages;
use crate::func::*;
use crate::types::object::Object;
use tcod::input::{self, Event, Mouse};
use tcod::colors::{self, Color};
/// returns a clicked monster inside FOV up to a range, or None if r... |
pub fn monster_death(monster: &mut Object, messages: &mut Messages) {
// transform it into a nasty corpse! it doesn't block, can't be
// attacked and doesn't move
// TODO Replace with game.log.add()
// message(messages, format!("{} is dead!", monster.name), colors::ORANGE);
message(messages, forma... | {
// the game ended!
// TODO Replace with game.log.add()
message(messages, "You died!", colors::DARK_RED);
// for added effect, transform the player into a corpse!
player.char = CORPSE;
player.color = colors::DARK_RED;
} | identifier_body |
combat.rs | use super::*;
use rand::Rng;
use crate::r#const::*;
use crate::types::*;
use crate::types::Tcod;
use crate::types::Messages;
use crate::func::*;
use crate::types::object::Object;
use tcod::input::{self, Event, Mouse};
use tcod::colors::{self, Color};
/// returns a clicked monster inside FOV up to a range, or None if r... |
}
render_all(tcod, objects, game, false);
let (x, y) = (tcod.mouse.cx as i32, tcod.mouse.cy as i32);
// accept the target if the player clicked in FOV, and in case a range
// is specified, if it's in that range
let in_fov = (x < MAP_WIDTH) && (y... | {} | conditional_block |
combat.rs | use super::*;
use rand::Rng;
use crate::r#const::*;
use crate::types::*;
use crate::types::Tcod;
use crate::types::Messages;
use crate::func::*;
use crate::types::object::Object;
use tcod::input::{self, Event, Mouse};
use tcod::colors::{self, Color};
/// returns a clicked monster inside FOV up to a range, or None if r... | (monster_id: usize, game: &mut Game, objects: &mut [Object], fov_map: &FovMap) -> Ai {
// a basic monster takes its turn. If you can see it, it can see you
let (monster_x, monster_y) = objects[monster_id].pos();
if fov_map.is_in_fov(monster_x, monster_y) {
if objects[monster_id].distance_to(&objects... | ai_basic | identifier_name |
allocator.rs | use std::rc::Rc;
use std::cell::RefCell;
use std::sync::{Arc, Mutex};
use std::any::Any;
use std::sync::mpsc::{Sender, Receiver, channel};
use std::collections::VecDeque;
use std::marker::PhantomData;
use columnar::{Columnar, ColumnarStack};
use communication::{Pushable, Pullable};
use networking::networking::MessageH... | (&self) -> u64 { 1 }
fn new_channel<T:'static>(&mut self) -> (Vec<Box<Pushable<T>>>, Box<Pullable<T>>) {
let shared = Rc::new(RefCell::new(VecDeque::<T>::new()));
return (vec![Box::new(shared.clone()) as Box<Pushable<T>>], Box::new(shared.clone()) as Box<Pullable<T>>)
}
}
// A specific Communi... | peers | identifier_name |
allocator.rs | use std::rc::Rc;
use std::cell::RefCell;
use std::sync::{Arc, Mutex};
use std::any::Any;
use std::sync::mpsc::{Sender, Receiver, channel};
use std::collections::VecDeque;
use std::marker::PhantomData;
use columnar::{Columnar, ColumnarStack};
use communication::{Pushable, Pullable};
use networking::networking::MessageH... | }
}
}
impl<T:Columnar+'static> Pushable<T> for BinaryPushable<T> {
#[inline]
fn push(&mut self, data: T) {
let mut bytes = if let Some(buffer) = self.receiver.try_recv().ok() { buffer } else { Vec::new() };
bytes.clear();
self.stack.push(data);
self.stack.encode(&mu... | sender: sender,
receiver: receiver,
phantom: PhantomData,
buffer: Vec::new(),
stack: Default::default(), | random_line_split |
load_balancer.rs | /*
* Copyright 2020 Google LLC
*
* 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 i... |
}
}
#[test]
fn round_robin_load_balancer_policy() {
let addresses = vec![
"127.0.0.1:8080".parse().unwrap(),
"127.0.0.2:8080".parse().unwrap(),
"127.0.0.3:8080".parse().unwrap(),
];
let yaml = "
policy: ROUND_ROBIN
";
let filter ... | {
assert_eq!(expected, result.unwrap(), "{}", name);
} | conditional_block |
load_balancer.rs | /*
* Copyright 2020 Google LLC
*
* 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 i... | {
#[serde(default)]
policy: Policy,
}
impl TryFrom<ProtoConfig> for Config {
type Error = ConvertProtoConfigError;
fn try_from(p: ProtoConfig) -> Result<Self, Self::Error> {
let policy = p
.policy
.map(|policy| {
map_proto_enum!(
value ... | Config | identifier_name |
load_balancer.rs | /*
* Copyright 2020 Google LLC
*
* 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 i... | policy: Some(PolicyValue {
value: ProtoPolicy::Random as i32,
}),
},
Some(Config {
policy: Policy::Random,
}),
),
(
"RoundRobinPolicy",
... | fn convert_proto_config() {
let test_cases = vec![
(
"RandomPolicy",
ProtoConfig { | random_line_split |
forall.rs | use itertools::Itertools;
use std::collections::HashMap;
use std::collections::HashSet;
use crate::Line;
use crate::Constraint;
use crate::Problem;
use indicatif::ProgressStyle;
use indicatif::ProgressBar;
use chrono::prelude::*;
struct Comb{
max : Vec<usize>,
state : Vec<usize>,
first : bool
}
impl Comb ... | return None;
}
if v[i] > 0 {
v[i+1] += 1;
v[i] -= 1;
if v[i+1] <= m[i+1] {
break;
}
}
i += 1;
}
let mut res ... | random_line_split | |
forall.rs |
use itertools::Itertools;
use std::collections::HashMap;
use std::collections::HashSet;
use crate::Line;
use crate::Constraint;
use crate::Problem;
use indicatif::ProgressStyle;
use indicatif::ProgressBar;
use chrono::prelude::*;
struct Comb{
max : Vec<usize>,
state : Vec<usize>,
first : bool
}
impl Comb... |
}
}
}
}
}
let mut groups = Vec::with_capacity(delta);
groups.push(uni.clone());
for (i,(ga,_)) in c1.iter().enumerate() {
for (j,(gb,_)) in c2.iter().enumerate() {
for _ in 0..x[i].state... | {
let u1 = c1[i1].0.clone() & c2[j1].0.clone();
let u2 = c1[i2].0.clone() & c2[j2].0.clone();
let u3 = c1[i1].0.clone() & c2[j2].0.clone();
let u4 = c1[i2].0.clone() & c2[j1].0.clone();
... | conditional_block |
forall.rs |
use itertools::Itertools;
use std::collections::HashMap;
use std::collections::HashSet;
use crate::Line;
use crate::Constraint;
use crate::Problem;
use indicatif::ProgressStyle;
use indicatif::ProgressBar;
use chrono::prelude::*;
struct Comb{
max : Vec<usize>,
state : Vec<usize>,
first : bool
}
impl Comb... |
fn transform(&mut self, n : usize, max : impl Iterator<Item=usize>) {
let mut i = 0;
for x in max {
self.max[i] = x;
i += 1;
}
assert!(i == self.max.len());
let mut res = n;
let mut i = 0;
while res > 0 {
let cur = std::cm... | {
let mut state = vec![0;max.len()];
let mut res = n;
let mut i = 0;
while res > 0 {
let cur = std::cmp::min(max[i],res);
state[i] = cur;
res -= cur;
i += 1;
}
Comb {
max, state, first:true
}
} | identifier_body |
forall.rs |
use itertools::Itertools;
use std::collections::HashMap;
use std::collections::HashSet;
use crate::Line;
use crate::Constraint;
use crate::Problem;
use indicatif::ProgressStyle;
use indicatif::ProgressBar;
use chrono::prelude::*;
struct Comb{
max : Vec<usize>,
state : Vec<usize>,
first : bool
}
impl Comb... | {
state : Vec<Comb>,
first : bool,
v1 : Vec<usize>
}
impl Matches {
fn new(v1 : Vec<usize>, mut v2 : Vec<usize>) -> Self {
let mut s = vec![];
for &x in &v1 {
let mut c = Comb::new(x,v2.clone());
c.next();
for i in 0..v2.len() {
v2[i]... | Matches | identifier_name |
policy_handler.rs | // Copyright 2020 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::base::SettingType;
use crate::handler::base::{Payload as HandlerPayload, Request, Response as SettingResponse};
use crate::handler::setting_hand... | verify_payload(HandlerPayload::Request(Request::Rebroadcast).into(), &mut receptor, None)
.await
}
}
| {
let setting_type = SettingType::Unknown;
let service_delegate = service::MessageHub::create_hub();
let (_, mut receptor) = service_delegate
.create(MessengerType::Addressable(service::Address::Handler(setting_type)))
.await
.expect("service receptor create... | identifier_body |
policy_handler.rs | // Copyright 2020 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::base::SettingType;
use crate::handler::base::{Payload as HandlerPayload, Request, Response as SettingResponse};
use crate::handler::setting_hand... | (
&self,
policy_info: PolicyInfo,
id: ftrace::Id,
) -> Result<UpdateState, PolicyError> {
let policy_type = (&policy_info).into();
let mut receptor = self
.service_messenger
.message(
storage::Payload::Request(storage::StorageRequest::Wri... | write_policy | identifier_name |
policy_handler.rs | // Copyright 2020 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::base::SettingType;
use crate::handler::base::{Payload as HandlerPayload, Request, Response as SettingResponse};
use crate::handler::setting_hand... |
impl ClientProxy {
/// Sends a setting request to the underlying setting proxy this policy handler controls.
pub(crate) fn send_setting_request(
&self,
setting_type: SettingType,
request: Request,
) -> service::message::Receptor {
self.service_messenger
.message(
... | random_line_split | |
lib.rs | //! This is a platform-agnostic Rust driver for the ADS1013, ADS1014, ADS1015,
//! ADS1113, ADS1114, and ADS1115 ultra-small, low-power
//! analog-to-digital converters (ADC), based on the [`embedded-hal`] traits.
//!
//! [`embedded-hal`]: https://github.com/rust-embedded/embedded-hal
//!
//! This driver allows you to:... | //! ```no_run
//! use linux_embedded_hal::I2cdev;
//! use ads1x1x::{Ads1x1x, SlaveAddr};
//!
//! let dev = I2cdev::new("/dev/i2c-1").unwrap();
//! let (bit1, bit0) = (true, false); // last two bits of address
//! let address = SlaveAddr::Alternative(bit1, bit0);
//! let adc = Ads1x1x::new_ads1013(dev, address);
//! ```... | random_line_split | |
lib.rs | //! This is a platform-agnostic Rust driver for the ADS1013, ADS1014, ADS1015,
//! ADS1113, ADS1114, and ADS1115 ultra-small, low-power
//! analog-to-digital converters (ADC), based on the [`embedded-hal`] traits.
//!
//! [`embedded-hal`]: https://github.com/rust-embedded/embedded-hal
//!
//! This driver allows you to:... | impl Register {
const CONVERSION: u8 = 0x00;
const CONFIG: u8 = 0x01;
const LOW_TH: u8 = 0x02;
const HIGH_TH: u8 = 0x03;
}
struct BitFlags;
impl BitFlags {
const OS: u16 = 0b1000_0000_0000_0000;
const MUX2: u16 = 0b0100_0000_0000_0000;
const MUX1: u16 = 0b0010_0000_0000_0000;
const MUX0... | gister;
| identifier_name |
lib.rs | #![cfg_attr(not(feature = "std"), no_std)]
#[allow(unused)]
#[cfg(all(feature = "std", test))]
mod mock;
#[cfg(all(feature = "std", test))]
mod tests;
#[cfg(not(feature = "std"))]
use rstd::borrow::ToOwned;
use rstd::{cmp, fmt::Debug, mem, prelude::*, result};
use sr_primitives::{
traits::{
Bounded, CheckedAdd, Ch... | <T: Trait>(T::Balance);
impl<T: Trait> NegativeImbalance<T> {
/// Create a new negative imbalance from a balance.
pub fn new(amount: T::Balance) -> Self {
NegativeImbalance(amount)
}
}
impl<T: Trait> Imbalance<T::Balance> for PositiveImbalance<T> {
type Opposite = NegativeImbalance<T>;
fn zero() -> S... | NegativeImbalance | identifier_name |
lib.rs | #![cfg_attr(not(feature = "std"), no_std)]
#[allow(unused)]
#[cfg(all(feature = "std", test))]
mod mock;
#[cfg(all(feature = "std", test))]
mod tests;
#[cfg(not(feature = "std"))]
use rstd::borrow::ToOwned;
use rstd::{cmp, fmt::Debug, mem, prelude::*, result};
use sr_primitives::{
traits::{
Bounded, CheckedAdd, Ch... |
impl<T: Trait> Drop for PositiveImbalance<T> {
/// Basic drop handler will just square up the total issuance.
fn drop(&mut self) {
<super::TotalIssuance<T>>::mutate(|v| *v = v.saturating_add(self.0));
}
}
impl<T: Trait> Drop for NegativeImbalance<T> {
/// Basic drop handler will just square up the total... | random_line_split | |
lib.rs | #![cfg_attr(not(feature = "std"), no_std)]
#[allow(unused)]
#[cfg(all(feature = "std", test))]
mod mock;
#[cfg(all(feature = "std", test))]
mod tests;
#[cfg(not(feature = "std"))]
use rstd::borrow::ToOwned;
use rstd::{cmp, fmt::Debug, mem, prelude::*, result};
use sr_primitives::{
traits::{
Bounded, CheckedAdd, Ch... |
// # <weight>
// Despite iterating over a list of locks, they are limited by the number of
// lock IDs, which means the number of runtime modules that intend to use and create locks.
// # </weight>
fn ensure_can_withdraw(
who: &T::AccountId,
_amount: T::Balance,
reasons: WithdrawReasons,
new_balance: T::... | {
<FreeBalance<T>>::get(who)
} | identifier_body |
lib.rs | #![cfg_attr(not(feature = "std"), no_std)]
#[allow(unused)]
#[cfg(all(feature = "std", test))]
mod mock;
#[cfg(all(feature = "std", test))]
mod tests;
#[cfg(not(feature = "std"))]
use rstd::borrow::ToOwned;
use rstd::{cmp, fmt::Debug, mem, prelude::*, result};
use sr_primitives::{
traits::{
Bounded, CheckedAdd, Ch... |
}
fn split(self, amount: T::Balance) -> (Self, Self) {
let first = self.0.min(amount);
let second = self.0 - first;
mem::forget(self);
(Self(first), Self(second))
}
fn merge(mut self, other: Self) -> Self {
self.0 = self.0.saturating_add(other.0);
mem::forget(other);
self
}
fn subsum... | {
Err(self)
} | conditional_block |
mod.rs | use crate::closure;
use wasm_bindgen::prelude::*;
/// Since the `copy` option can be either a function or a boolean, this enum
/// encapsulates the possible values for the copy option.
///
/// The closure signature is `(el, handle)`, the element to check and the
/// element that was directly clicked on.
pub enum CopyV... |
#[wasm_bindgen(setter = invalid)]
pub fn set_invalid_func(&mut self, val: JsValue) {
self.invalid_func = val;
}
#[wasm_bindgen(getter = copy)]
pub fn copy_func_or_bool(&self) -> JsValue {
self.copy_func_or_bool.clone()
}
#[wasm_bindgen(setter = copy)]
pub fn set_copy_... | {
self.invalid_func.clone()
} | identifier_body |
mod.rs | use crate::closure;
use wasm_bindgen::prelude::*;
/// Since the `copy` option can be either a function or a boolean, this enum
/// encapsulates the possible values for the copy option.
///
/// The closure signature is `(el, handle)`, the element to check and the
/// element that was directly clicked on.
pub enum CopyV... | /// for this particular [`Drake`](crate::Drake) instance.
///
/// This closure will be invoked with the element that is being checked for
/// whether it is a container.
pub is_container: Box<dyn FnMut(JsValue) -> bool>,
/// You can define a `moves` closure which will be invoked with `(el, source... | /// Besides the containers that you pass to [`dragula`](crate::dragula()),
/// or the containers you dynamically add, you can also use this closure to
/// specify any sort of logic that defines what is a container | random_line_split |
mod.rs | use crate::closure;
use wasm_bindgen::prelude::*;
/// Since the `copy` option can be either a function or a boolean, this enum
/// encapsulates the possible values for the copy option.
///
/// The closure signature is `(el, handle)`, the element to check and the
/// element that was directly clicked on.
pub enum CopyV... | () -> Self {
OptionsImpl::from(Options::default())
}
}
#[wasm_bindgen]
#[doc(hidden)]
impl OptionsImpl {
#[wasm_bindgen(getter = isContainer)]
pub fn is_container_func(&self) -> JsValue {
self.is_container_func.clone()
}
#[wasm_bindgen(setter = isContainer)]
pub fn set_is_conta... | default | identifier_name |
retransmit_stage.rs | solana_runtime::{bank::Bank, bank_forks::BankForks},
solana_sdk::{clock::Slot, epoch_schedule::EpochSchedule, pubkey::Pubkey, timing::timestamp},
solana_streamer::sendmmsg::{multi_target_send, SendPktsError},
std::{
collections::{BTreeSet, HashMap, HashSet},
net::UdpSocket,
ops::{... |
true
} else {
false
}
}
fn maybe_reset_shreds_received_cache(
shreds_received: &Mutex<ShredFilterAndHasher>,
hasher_reset_ts: &mut Instant,
) {
const UPDATE_INTERVAL: Duration = Duration::from_secs(1);
if hasher_reset_ts.elapsed() >= UPDATE_INTERVAL {
*hasher_reset_ts =... | {
*first_shreds_received_locked =
first_shreds_received_locked.split_off(&(root_bank.slot() + 1));
} | conditional_block |
retransmit_stage.rs | solana_runtime::{bank::Bank, bank_forks::BankForks},
solana_sdk::{clock::Slot, epoch_schedule::EpochSchedule, pubkey::Pubkey, timing::timestamp},
solana_streamer::sendmmsg::{multi_target_send, SendPktsError},
std::{
collections::{BTreeSet, HashMap, HashSet},
net::UdpSocket,
ops::{... | (
shred_slot: Slot,
first_shreds_received: &Mutex<BTreeSet<Slot>>,
root_bank: &Bank,
) -> bool {
if shred_slot <= root_bank.slot() {
return false;
}
let mut first_shreds_received_locked = first_shreds_received.lock().unwrap();
if first_shreds_received_locked.insert(shred_slot) {
... | check_if_first_shred_received | identifier_name |
retransmit_stage.rs |
solana_runtime::{bank::Bank, bank_forks::BankForks},
solana_sdk::{clock::Slot, epoch_schedule::EpochSchedule, pubkey::Pubkey, timing::timestamp},
solana_streamer::sendmmsg::{multi_target_send, SendPktsError},
std::{
collections::{BTreeSet, HashMap, HashSet},
net::UdpSocket,
ops:... | sockets: &[UdpSocket],
stats: &mut RetransmitStats,
cluster_nodes_cache: &ClusterNodesCache<RetransmitStage>,
hasher_reset_ts: &mut Instant,
shreds_received: &Mutex<ShredFilterAndHasher>,
max_slots: &MaxSlots,
first_shreds_received: &Mutex<BTreeSet<Slot>>,
rpc_subscriptions: Option<&RpcS... | thread_pool: &ThreadPool,
bank_forks: &RwLock<BankForks>,
leader_schedule_cache: &LeaderScheduleCache,
cluster_info: &ClusterInfo,
shreds_receiver: &Receiver<Vec<Shred>>, | random_line_split |
tbs.rs | //! hash functions for DNSSec operations
use super::rdata::{sig, DNSSECRData, SIG};
use crate::error::*;
use crate::rr::dnssec::Algorithm;
use crate::rr::{DNSClass, Name, RData, Record, RecordType};
use crate::serialize::binary::{BinEncodable, BinEncoder, EncodeMode};
/// Data To Be Signed.
pub struct TBS(Vec<u8>);
... | (
name: &Name,
dns_class: DNSClass,
sig: &SIG,
records: &[Record],
) -> ProtoResult<TBS> {
rrset_tbs(
name,
dns_class,
sig.num_labels(),
sig.type_covered(),
sig.algorithm(),
sig.original_ttl(),
sig.sig_expiration(),
sig.sig_inception(),... | rrset_tbs_with_sig | identifier_name |
tbs.rs | //! hash functions for DNSSec operations
use super::rdata::{sig, DNSSECRData, SIG};
use crate::error::*;
use crate::rr::dnssec::Algorithm;
use crate::rr::{DNSClass, Name, RData, Record, RecordType};
use crate::serialize::binary::{BinEncodable, BinEncoder, EncodeMode};
/// Data To Be Signed.
pub struct TBS(Vec<u8>);
... | let mut buf: Vec<u8> = Vec::new();
{
let mut encoder: BinEncoder<'_> = BinEncoder::new(&mut buf);
encoder.set_canonical_names(true);
// signed_data = RRSIG_RDATA | RR(1) | RR(2)... where
//
// "|" denotes concatenation
//
// ... | {
// TODO: change this to a BTreeSet so that it's preordered, no sort necessary
let mut rrset: Vec<&Record> = Vec::new();
// collect only the records for this rrset
for record in records {
if dns_class == record.dns_class()
&& type_covered == record.rr_type()
&& name == ... | identifier_body |
tbs.rs | //! hash functions for DNSSec operations
use super::rdata::{sig, DNSSECRData, SIG};
use crate::error::*;
use crate::rr::dnssec::Algorithm;
use crate::rr::{DNSClass, Name, RData, Record, RecordType};
use crate::serialize::binary::{BinEncodable, BinEncoder, EncodeMode};
/// Data To Be Signed.
pub struct TBS(Vec<u8>);
... | {
let mut rdata_encoder = BinEncoder::new(&mut rdata_buf);
rdata_encoder.set_canonical_names(true);
if let Some(rdata) = record.data() {
assert!(rdata.emit(&mut rdata_encoder).is_ok());
}
}
assert!(en... | random_line_split | |
tbs.rs | //! hash functions for DNSSec operations
use super::rdata::{sig, DNSSECRData, SIG};
use crate::error::*;
use crate::rr::dnssec::Algorithm;
use crate::rr::{DNSClass, Name, RData, Record, RecordType};
use crate::serialize::binary::{BinEncodable, BinEncoder, EncodeMode};
/// Data To Be Signed.
pub struct TBS(Vec<u8>);
... |
// if rrsig_labels < fqdn_labels,
// name = "*." | the rightmost rrsig_label labels of the
// fqdn
if num_labels < fqdn_labels {
let mut star_name: Name = Name::from_labels(vec![b"*" as &[u8]]).unwrap();
let rightmost = na... | {
return Ok(name.clone());
} | conditional_block |
mod.rs | // Copyright 2022 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 aes::cipher::generic_array::GenericArray;
use aes::{Aes128, BlockDecrypt, BlockEncrypt, NewBlockCipher};
use fuchsia_inspect::{self as inspect, Propert... | // Marking a key as used should "refresh" the key's position. It is no longer the LRU key
// that will be evicted.
let account_key2 = AccountKey::new([2; 16]);
assert_matches!(list.mark_used(&account_key2), Ok(_));
// Inserting a new key at capacity will evict the LRU key (not `a... | {
let mut list = AccountKeyList::with_capacity_and_keys(MAX_ACCOUNT_KEYS, vec![]);
let max: u8 = MAX_ACCOUNT_KEYS as u8;
for i in 1..max + 1 {
let key = AccountKey::new([i; 16]);
list.save(key.clone());
assert_eq!(list.keys().len(), i as usize);
a... | identifier_body |
mod.rs | // Copyright 2022 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 aes::cipher::generic_array::GenericArray;
use aes::{Aes128, BlockDecrypt, BlockEncrypt, NewBlockCipher};
use fuchsia_inspect::{self as inspect, Propert... | /// A long-lived key that allows the Provider to be recognized as belonging to a certain user
/// account.
#[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)]
pub struct AccountKey(SharedSecret);
impl AccountKey {
pub fn new(bytes: [u8; 16]) -> Self {
Self(SharedSecret::new(bytes))
}
... | }
| random_line_split |
mod.rs | // Copyright 2022 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 aes::cipher::generic_array::GenericArray;
use aes::{Aes128, BlockDecrypt, BlockEncrypt, NewBlockCipher};
use fuchsia_inspect::{self as inspect, Propert... |
Ok(Self(src))
}
}
impl From<ModelId> for [u8; 3] {
fn from(src: ModelId) -> [u8; 3] {
let mut bytes = [0; 3];
bytes[..3].copy_from_slice(&src.0.to_be_bytes()[1..]);
bytes
}
}
/// A key used during the Fast Pair Pairing Procedure.
/// This key is a temporary value that liv... | {
return Err(Error::InvalidModelId(src));
} | conditional_block |
mod.rs | // Copyright 2022 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 aes::cipher::generic_array::GenericArray;
use aes::{Aes128, BlockDecrypt, BlockEncrypt, NewBlockCipher};
use fuchsia_inspect::{self as inspect, Propert... | () {
let invalid_id = 0x1ffabcd;
assert_matches!(ModelId::try_from(invalid_id), Err(_));
}
#[test]
fn empty_account_key_list_service_data() {
let empty = AccountKeyList::with_capacity_and_keys(1, vec![]);
let service_data = empty.service_data().expect("can build service data... | invalid_model_id_conversion_is_error | identifier_name |
utils.rs | use cairo;
use cairo::enums::{FontSlant, FontWeight};
use cairo::prelude::SurfaceExt;
use clap::{
crate_authors, crate_description, crate_name, crate_version, value_t, App, AppSettings, Arg,
};
use css_color_parser::Color as CssColor;
use font_loader::system_fonts;
use itertools::Itertools;
use log::debug;
use rege... | ;
let loaded_font = load_font(&font_family);
AppConfig {
font_family,
font_size,
loaded_font,
hint_chars,
margin,
text_color,
text_color_alt,
bg_color,
fill,
print_only,
horizontal_align,
vertical_align,
}
}
/... | {
(
value_t!(matches, "horizontal_align", HorizontalAlign).unwrap(),
value_t!(matches, "vertical_align", VerticalAlign).unwrap(),
)
} | conditional_block |
utils.rs | use cairo;
use cairo::enums::{FontSlant, FontWeight};
use cairo::prelude::SurfaceExt;
use clap::{
crate_authors, crate_description, crate_name, crate_version, value_t, App, AppSettings, Arg,
};
use css_color_parser::Color as CssColor;
use font_loader::system_fonts;
use itertools::Itertools;
use log::debug;
use rege... | () {
assert!(!intersects((1905, 705, 31, 82), (2000, 723, 38, 64)));
}
}
| test_no_intersect | identifier_name |
utils.rs | use cairo;
use cairo::enums::{FontSlant, FontWeight};
use cairo::prelude::SurfaceExt;
use clap::{
crate_authors, crate_description, crate_name, crate_version, value_t, App, AppSettings, Arg,
};
use css_color_parser::Color as CssColor;
use font_loader::system_fonts;
use itertools::Itertools;
use log::debug;
use rege... | let grab_pointer_reply = grab_pointer_cookie
.get_reply()
.map_err(|_| "Couldn't communicate with X")?;
if grab_pointer_reply.status() == xcb::GRAB_STATUS_SUCCESS as u8 {
return Ok(());
}
sleep(Duration::from_millis(1));
}
}
/// Sort list of `Deskt... | {
let now = Instant::now();
loop {
if now.elapsed() > timeout {
return Err(format!(
"Couldn't grab keyboard input within {:?}",
now.elapsed()
));
}
let grab_pointer_cookie = xcb::xproto::grab_pointer(
&conn,
... | identifier_body |
utils.rs | use cairo;
use cairo::enums::{FontSlant, FontWeight};
use cairo::prelude::SurfaceExt;
use clap::{
crate_authors, crate_description, crate_name, crate_version, value_t, App, AppSettings, Arg,
};
use css_color_parser::Color as CssColor;
use font_loader::system_fonts;
use itertools::Itertools;
use log::debug;
use rege... | "bottom" => Ok(VerticalAlign::Bottom),
_ => Err(()),
}
}
}
/// Checks whether the provided fontconfig font `f` is valid.
fn is_truetype_font(f: String) -> Result<(), String> {
let v: Vec<_> = f.split(':').collect();
let (family, size) = (v.get(0), v.get(1));
if family.is... | "top" => Ok(VerticalAlign::Top),
"center" => Ok(VerticalAlign::Center), | random_line_split |
mysql_interactive_worker.rs | // Copyright 2020 Datafuse Labs.
//
// 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 ... | fn build_runtime() -> Result<tokio::runtime::Runtime> {
tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.map_err(|tokio_error| ErrorCode::TokioError(format!("{}", tokio_error)))
}
}
impl<W: std::io::Write> InteractiveWorker<W> {
pub fn create(sess... | }
| random_line_split |
mysql_interactive_worker.rs | // Copyright 2020 Datafuse Labs.
//
// 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 ... | (&self) -> &str {
"mysql_native_password"
}
fn auth_plugin_for_username(&self, _user: &[u8]) -> &str {
"mysql_native_password"
}
fn salt(&self) -> [u8; 20] {
self.salt
}
fn authenticate(
&self,
auth_plugin: &str,
username: &[u8],
salt: &... | default_auth_plugin | identifier_name |
mysql_interactive_worker.rs | // Copyright 2020 Datafuse Labs.
//
// 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 ... |
fn encoding_password(
auth_plugin: &str,
salt: &[u8],
input: &[u8],
user_password: &[u8],
) -> Result<Vec<u8>> {
match auth_plugin {
"mysql_native_password" if input.is_empty() => Ok(vec![]),
"mysql_native_password" => {
// SHA1( ... | {
let user_name = &info.user_name;
let address = &info.user_client_address;
let user_manager = self.session.get_user_manager();
let user_info = user_manager.get_user(user_name).await?;
let input = &info.user_password;
let saved = &user_info.password;
let encode_... | identifier_body |
lib.rs | use itertools::multiunzip;
use rust_htslib::{bam, bam::ext::BamRecordExtensions};
use std::collections::HashMap;
use std::fmt::{Debug, Display};
/// Merge two lists into a sorted list
/// Normal sort is supposed to be very fast on two sorted lists
/// <https://doc.rust-lang.org/std/vec/struct.Vec.html#current-implemen... | <T>(v: &[T]) -> bool
where
T: Ord,
{
v.windows(2).all(|w| w[0] <= w[1])
}
/// search a sorted array for insertions positions of another sorted array
/// returned index i satisfies
/// left
/// a\[i-1\] < v <= a\[i\]
/// right
/// a\[i-1\] <= v < a\[i\]
/// <https://numpy.org/doc/stable/reference/generated/nump... | is_sorted | identifier_name |
lib.rs | use itertools::multiunzip;
use rust_htslib::{bam, bam::ext::BamRecordExtensions};
use std::collections::HashMap;
use std::fmt::{Debug, Display};
/// Merge two lists into a sorted list
/// Normal sort is supposed to be very fast on two sorted lists
/// <https://doc.rust-lang.org/std/vec/struct.Vec.html#current-implemen... | let ending_block = aligned_block_pairs.len();
let mut pos_mapping = HashMap::new();
for cur_pos in positions {
pos_mapping.insert(cur_pos, (-1, i64::MAX));
let mut current_block = 0;
for block_index in starting_block..ending_block {
// get the current alignment block
... | );
// find the closest position for every position
let mut starting_block = 0; | random_line_split |
lib.rs | use itertools::multiunzip;
use rust_htslib::{bam, bam::ext::BamRecordExtensions};
use std::collections::HashMap;
use std::fmt::{Debug, Display};
/// Merge two lists into a sorted list
/// Normal sort is supposed to be very fast on two sorted lists
/// <https://doc.rust-lang.org/std/vec/struct.Vec.html#current-implemen... | else {
let aligned_block_pairs: Vec<([i64; 2], [i64; 2])> = record.aligned_block_pairs().collect();
liftover_exact(&aligned_block_pairs, reference_positions, true)
}
}
| {
reference_positions.iter().map(|_x| None).collect()
} | conditional_block |
lib.rs | use itertools::multiunzip;
use rust_htslib::{bam, bam::ext::BamRecordExtensions};
use std::collections::HashMap;
use std::fmt::{Debug, Display};
/// Merge two lists into a sorted list
/// Normal sort is supposed to be very fast on two sorted lists
/// <https://doc.rust-lang.org/std/vec/struct.Vec.html#current-implemen... |
/// get positions on the complimented sequence in the cigar record
pub fn positions_on_complimented_sequence_in_place(
record: &bam::Record,
input_positions: &mut Vec<i64>,
part_of_range: bool,
) {
if!record.is_reverse() {
return;
}
let seq_len = i64::try_from(record.seq_len()).unwrap(... | {
// reverse positions if needed
let positions: Vec<i64> = if record.is_reverse() {
let seq_len = i64::try_from(record.seq_len()).unwrap();
input_positions
.iter()
.rev()
.map(|p| seq_len - p - 1)
.collect()
} else {
input_positions.to_... | identifier_body |
chown.rs | // This file is part of the uutils coreutils package.
//
// (c) Jian Zeng <anonymousknight96@gmail.com>
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
// spell-checker:ignore (ToDO) COMFOLLOW Chowner Passwd RFILE RFILE's derefer dgid du... | (spec: &str) -> UResult<(Option<u32>, Option<u32>)> {
let args = spec.split_terminator(':').collect::<Vec<_>>();
let usr_only = args.len() == 1 &&!args[0].is_empty();
let grp_only = args.len() == 2 && args[0].is_empty();
let usr_grp = args.len() == 2 &&!args[0].is_empty() &&!args[1].is_empty();
let ... | parse_spec | identifier_name |
chown.rs | // This file is part of the uutils coreutils package.
//
// (c) Jian Zeng <anonymousknight96@gmail.com>
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
// spell-checker:ignore (ToDO) COMFOLLOW Chowner Passwd RFILE RFILE's derefer dgid du... | )
.arg(
Arg::with_name(options::traverse::NO_TRAVERSE)
.short(options::traverse::NO_TRAVERSE)
.help("do not traverse any symbolic links (default)")
.overrides_with_all(&[options::traverse::TRAVERSE, options::traverse::EVERY]),
)
.arg... | .arg(
Arg::with_name(options::traverse::EVERY)
.short(options::traverse::EVERY)
.help("traverse every symbolic link to a directory encountered")
.overrides_with_all(&[options::traverse::TRAVERSE, options::traverse::NO_TRAVERSE]), | random_line_split |
chown.rs | // This file is part of the uutils coreutils package.
//
// (c) Jian Zeng <anonymousknight96@gmail.com>
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
// spell-checker:ignore (ToDO) COMFOLLOW Chowner Passwd RFILE RFILE's derefer dgid du... |
Err(e) => {
if self.verbosity!= Verbosity::Silent {
show_error!("{}", e);
}
1
}
}
}
ret
}
fn obtain_meta<P: AsRef<Path>>(&self, path: P, follow: bool) -> Option<Metad... | {
if !n.is_empty() {
show_error!("{}", n);
}
0
} | conditional_block |
bls12_377_scalar.rs | //! This module implements field arithmetic for BLS12-377's scalar field.
use std::cmp::Ordering::Less;
use std::convert::TryInto;
use std::ops::{Add, Div, Mul, Neg, Sub};
use rand::Rng;
use unroll::unroll_for_loops;
use crate::{add_no_overflow, cmp, Field, sub, field_to_biguint, rand_range, rand_range_from_rng};
us... | }
}
impl Field for Bls12377Scalar {
const BITS: usize = 253;
const BYTES: usize = 32;
const ZERO: Self = Self { limbs: [0; 4] };
const ONE: Self = Self { limbs: Self::R };
const TWO: Self = Self { limbs: [17304940830682775525, 10017539527700119523, 14770643272311271387, 570918138838421475] };
... |
Self { limbs: sub(Self::ORDER, self.limbs) }
}
| conditional_block |
bls12_377_scalar.rs | //! This module implements field arithmetic for BLS12-377's scalar field.
use std::cmp::Ordering::Less;
use std::convert::TryInto;
use std::ops::{Add, Div, Mul, Neg, Sub};
use rand::Rng;
use unroll::unroll_for_loops;
use crate::{add_no_overflow, cmp, Field, sub, field_to_biguint, rand_range, rand_range_from_rng};
us... | ) {
assert_eq!(Bls12377Scalar::from_canonical_u64(0b10101).num_bits(), 5);
assert_eq!(Bls12377Scalar::from_canonical_u64(u64::max_value()).num_bits(), 64);
assert_eq!(Bls12377Scalar::from_canonical([0, 1, 0, 0]).num_bits(), 64 + 1);
assert_eq!(Bls12377Scalar::from_canonical([0, 0, 0, 1])... | um_bits( | identifier_name |
bls12_377_scalar.rs | //! This module implements field arithmetic for BLS12-377's scalar field.
use std::cmp::Ordering::Less;
use std::convert::TryInto;
use std::ops::{Add, Div, Mul, Neg, Sub};
use rand::Rng;
use unroll::unroll_for_loops;
use crate::{add_no_overflow, cmp, Field, sub, field_to_biguint, rand_range, rand_range_from_rng};
us... | }
impl Div<Bls12377Scalar> for Bls12377Scalar {
type Output = Self;
fn div(self, rhs: Self) -> Self {
self * rhs.multiplicative_inverse().expect("No inverse")
}
}
impl Neg for Bls12377Scalar {
type Output = Self;
fn neg(self) -> Self {
if self == Self::ZERO {
Self::ZE... | } | random_line_split |
bls12_377_scalar.rs | //! This module implements field arithmetic for BLS12-377's scalar field.
use std::cmp::Ordering::Less;
use std::convert::TryInto;
use std::ops::{Add, Div, Mul, Neg, Sub};
use rand::Rng;
use unroll::unroll_for_loops;
use crate::{add_no_overflow, cmp, Field, sub, field_to_biguint, rand_range, rand_range_from_rng};
us... | }
impl Mul<Self> for Bls12377Scalar {
type Output = Self;
fn mul(self, rhs: Self) -> Self {
Self { limbs: Self::montgomery_multiply(self.limbs, rhs.limbs) }
}
}
impl Div<Bls12377Scalar> for Bls12377Scalar {
type Output = Self;
fn div(self, rhs: Self) -> Self {
self * rhs.multipli... |
let limbs = if cmp(self.limbs, rhs.limbs) == Less {
// Underflow occurs, so we compute the difference as `self + (-rhs)`.
add_no_overflow(self.limbs, (-rhs).limbs)
} else {
// No underflow, so it's faster to subtract directly.
sub(self.limbs, rhs.limbs)
... | identifier_body |
lib.rs | //! Adler-32 checksum implementation.
//!
//! This implementation features:
//!
//! - Permissively licensed (0BSD) clean-room implementation.
//! - Zero dependencies.
//! - Decent performance (3-4 GB/s).
//! - `#![no_std]` support (with `default-features = false`).
#![doc(html_root_url = "https://docs.rs/adler/0.2.2")... |
/// Returns the calculated checksum at this point in time.
#[inline]
pub fn checksum(&self) -> u32 {
(u32::from(self.b) << 16) | u32::from(self.a)
}
/// Adds `bytes` to the checksum calculation.
///
/// If efficiency matters, this should be called with Byte slices that contain at ... | {
Adler32 {
a: sum as u16,
b: (sum >> 16) as u16,
}
} | identifier_body |
lib.rs | //! Adler-32 checksum implementation.
//!
//! This implementation features:
//!
//! - Permissively licensed (0BSD) clean-room implementation.
//! - Zero dependencies.
//! - Decent performance (3-4 GB/s).
//! - `#![no_std]` support (with `default-features = false`).
#![doc(html_root_url = "https://docs.rs/adler/0.2.2")... | {
a: u16,
b: u16,
}
impl Adler32 {
/// Creates a new Adler-32 instance with default state.
#[inline]
pub fn new() -> Self {
Self::default()
}
/// Creates an `Adler32` instance from a precomputed Adler-32 checksum.
///
/// This allows resuming checksum calculation without h... | Adler32 | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.