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 |
|---|---|---|---|---|
lib.rs | //! Adler-32 checksum implementation.
//! | //! - `#![no_std]` support (with `default-features = false`).
#![doc(html_root_url = "https://docs.rs/adler/0.2.2")]
// Deny a few warnings in doctests, since rustdoc `allow`s many warnings by default
#![doc(test(attr(deny(unused_imports, unused_must_use))))]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![warn(missing_debu... | //! This implementation features:
//!
//! - Permissively licensed (0BSD) clean-room implementation.
//! - Zero dependencies.
//! - Decent performance (3-4 GB/s). | random_line_split |
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")... | h.write_slice(buf);
buf.len()
};
reader.consume(len);
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::BufReader;
#[test]
fn zeroes() {
assert_eq!(adler32_slice(&[]), 1);
assert_eq!(adler32_slice(&[0]), 1 | 1 << 16);
assert_eq!(adler3... | return Ok(h.checksum());
}
| conditional_block |
main.rs | extern crate rand;
extern crate getopts;
#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate serde_json;
extern crate bincode;
extern crate rayon;
pub mod aabb;
pub mod background;
pub mod bvh;
pub mod camera;
pub mod deserialize;
pub mod dielectric;
pub mod disc;
pub mod emitter;
pub mod hitabl... | },
material::Scatter::Emit(emission) => {
// println!("Hit light!");
return emission * current_attenuation;
},
material::Scatter::Absorb => {
... | {
let mut current_ray = *ray;
let mut current_attenuation = Vec3::new(1.0, 1.0, 1.0);
for _depth in 0..50 {
if current_attenuation.length() < 1e-8 {
return Vec3::new(0.0, 0.0, 0.0)
}
match world.hit(¤t_ray, 0.00001, 1e20) {
None => {
... | identifier_body |
main.rs | extern crate rand;
extern crate getopts;
#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate serde_json;
extern crate bincode;
extern crate rayon;
pub mod aabb;
pub mod background;
pub mod bvh;
pub mod camera;
pub mod deserialize;
pub mod dielectric;
pub mod disc;
pub mod emitter;
pub mod hitabl... | (args: &Args)
{
let default_output_name = "out".to_string();
let output_name = &args.o.as_ref().unwrap_or(&default_output_name);
let default_input_name = "/dev/stdin".to_string();
let input_name = &args.i.as_ref().unwrap_or(&default_input_name);
let br = BufReader::new(File::open... | write_image | identifier_name |
main.rs | extern crate rand;
extern crate getopts;
#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate serde_json;
extern crate bincode;
extern crate rayon;
pub mod aabb;
pub mod background;
pub mod bvh;
pub mod camera;
pub mod deserialize;
pub mod dielectric;
pub mod disc;
pub mod emitter;
pub mod hitabl... |
//////////////////////////////////////////////////////////////////////////////
// my own bastardized version of a float file format, horrendously inefficient
fn write_image_to_file(image: &Vec<Vec<Vec3>>, samples_so_far: usize, subsample: usize, file_prefix: &String)
{
println!("Writing output to {}",
... | random_line_split | |
main.rs | extern crate rand;
extern crate getopts;
#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate serde_json;
extern crate bincode;
extern crate rayon;
pub mod aabb;
pub mod background;
pub mod bvh;
pub mod camera;
pub mod deserialize;
pub mod dielectric;
pub mod disc;
pub mod emitter;
pub mod hitabl... | ;
let albedo = hr.material.albedo(¤t_ray, &next_values.1, &hr.normal);
current_ray = next_values.1;
current_attenuation = current_attenuation * albedo * next_values.0;
}
}
}
current_attenuation
}
/////////////////////////////////////////... | {
return Vec3::new(0.0, 0.0, 0.0);
} | conditional_block |
mod.rs | use crate::css::{is_not, CallArgs, CssString, Value};
use crate::error::Error;
use crate::output::{Format, Formatted};
use crate::parser::SourcePos;
use crate::sass::{FormalArgs, Name};
use crate::value::Numeric;
use crate::{sass, Scope, ScopeRef};
use lazy_static::lazy_static;
use std::collections::BTreeMap;
use std::... | (
args: FormalArgs,
pos: SourcePos,
scope: ScopeRef,
body: Vec<sass::Item>,
) -> Self {
Function {
args,
pos,
body: FuncImpl::UserDefined(scope, body),
}
}
/// Call the function from a given scope and with a given set of
... | closure | identifier_name |
mod.rs | use crate::css::{is_not, CallArgs, CssString, Value};
use crate::error::Error;
use crate::output::{Format, Formatted};
use crate::parser::SourcePos;
use crate::sass::{FormalArgs, Name};
use crate::value::Numeric;
use crate::{sass, Scope, ScopeRef};
use lazy_static::lazy_static;
use std::collections::BTreeMap;
use std::... | fn get_va_list(s: &Scope, name: Name) -> Result<Vec<Value>, Error> {
get_checked(s, name, check::va_list)
}
fn expected_to<'a, T>(value: &'a T, cond: &str) -> String
where
Formatted<'a, T>: std::fmt::Display,
{
format!(
"Expected {} to {}.",
Formatted {
value,
format... | get_checked(s, name.into(), check::string)
}
| random_line_split |
mod.rs | use crate::css::{is_not, CallArgs, CssString, Value};
use crate::error::Error;
use crate::output::{Format, Formatted};
use crate::parser::SourcePos;
use crate::sass::{FormalArgs, Name};
use crate::value::Numeric;
use crate::{sass, Scope, ScopeRef};
use lazy_static::lazy_static;
use std::collections::BTreeMap;
use std::... |
/// Call the function from a given scope and with a given set of
/// arguments.
pub fn call(
&self,
callscope: ScopeRef,
args: CallArgs,
) -> Result<Value, Error> {
let cs = "%%CALLING_SCOPE%%";
match self.body {
FuncImpl::Builtin(ref body) => {
... | {
Function {
args,
pos,
body: FuncImpl::UserDefined(scope, body),
}
} | identifier_body |
main.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 anyhow;
use fuchsia_async;
use futures::future::join_all;
use io::BufWriter;
use json5format::{Json5Format, ParsedDocument};
use std::{
ffi::OsStri... | let filter = String::from("{foo:.foo, baz:.bar}");
let json5_string = String::from(
r##"{
//Foo
foo: 0,
//Bar
bar: 42
}"##,
);
let format = Json5Format::new().unwrap();
let (parsed_json5, json_string) = reader::read_json5(json5_string).unwrap();
let jq... | );
}
#[fuchsia_async::run_singlethreaded(test)]
async fn run_jq5_deconstruct_filter() { | random_line_split |
main.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 anyhow;
use fuchsia_async;
use futures::future::join_all;
use io::BufWriter;
use json5format::{Json5Format, ParsedDocument};
use std::{
ffi::OsStri... |
#[fuchsia_async::run_singlethreaded(test)]
async fn run_jq5_deconstruct_filter() {
let filter = String::from("{foo:.foo, baz:.bar}");
let json5_string = String::from(
r##"{
//Foo
foo: 0,
//Bar
bar: 42
}"##,
);
let format = Json5Format::new().unwrap();
... | {
let filter = String::from("{foo2: .foo1, bar2: .bar1}");
let input = String::from(r#"{"foo1": 0, "bar1": 42}"#);
let jq_path = Some(PathBuf::from(JQ_PATH_STR));
assert_eq!(
run_jq(&filter, input, &jq_path).await.unwrap(),
r##"{
"foo2": 0,
"bar2": 42
}
"##
... | identifier_body |
main.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 anyhow;
use fuchsia_async;
use futures::future::join_all;
use io::BufWriter;
use json5format::{Json5Format, ParsedDocument};
use std::{
ffi::OsStri... | (
filter: &String,
file: &PathBuf,
jq_path: &Option<PathBuf>,
) -> Result<String, anyhow::Error> {
let (parsed_json5, json_string) = reader::read_json5_fromfile(&file)?;
run_jq5(&filter, parsed_json5, json_string, jq_path).await
}
async fn run(
filter: String,
files: Vec<PathBuf>,
jq_pa... | run_jq5_on_file | identifier_name |
main.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 anyhow;
use fuchsia_async;
use futures::future::join_all;
use io::BufWriter;
use json5format::{Json5Format, ParsedDocument};
use std::{
ffi::OsStri... | else {
Err(anyhow::anyhow!("jq returned exit code 0 but no output or error message"))
}
}
/// Calls jq on the provided json and then fills back comments at correct places.
async fn run_jq5(
filter: &String,
parsed_json5: ParsedDocument,
json_string: String,
jq_path: &Option<PathBuf>,
) -> ... | {
Err(anyhow::anyhow!("jq returned with non-zero exit code but no error message"))
} | conditional_block |
lib.rs | //! ### Request/Response
//!
//! ```no_run
//! # use std::time::Duration;
//! # fn main() -> std::io::Result<()> {
//! let nc = nats::connect("demo.nats.io")?;
//! let resp = nc.request("foo", "Help me?")?;
//!
//! // With a timeout.
//! let resp = nc.request_timeout("foo", "Help me?", Duration::from_secs(2))?;
//!
//!... | (
&self,
subject: &str,
maybe_headers: Option<&HeaderMap>,
maybe_timeout: Option<Duration>,
msg: impl AsRef<[u8]>,
) -> io::Result<Message> {
// Publish a request.
let reply = self.new_inbox();
let sub = self.subscribe(&reply)?;
self.publish_wi... | request_with_headers_or_timeout | identifier_name |
lib.rs |
//! ### Request/Response
//!
//! ```no_run
//! # use std::time::Duration;
//! # fn main() -> std::io::Result<()> {
//! let nc = nats::connect("demo.nats.io")?;
//! let resp = nc.request("foo", "Help me?")?;
//!
//! // With a timeout.
//! let resp = nc.request_timeout("foo", "Help me?", Duration::from_secs(2))?;
//!
//... | unsafe_code,
unused,
unused_qualifications
)
)]
#![cfg_attr(feature = "fault_injection", deny(
// over time, consider enabling the following commented-out lints:
// clippy::else_if_without_else,
// clippy::indexing_slicing,
// clippy::multiple_crate_versions,
// clippy::m... | missing_docs,
nonstandard_style,
rust_2018_idioms,
trivial_casts,
trivial_numeric_casts, | random_line_split |
lib.rs |
io::{self, Error, ErrorKind},
sync::Arc,
time::{Duration, Instant},
};
use lazy_static::lazy_static;
use regex::Regex;
pub use connector::{IntoServerList, ServerAddress};
pub use jetstream::JetStreamOptions;
pub use message::Message;
pub use options::Options;
pub use subscription::{Handler, Subscription}... | {
self.0.client.publish(subject, reply, headers, msg.as_ref())
} | identifier_body | |
s_expressions.rs | //! In this tutorial, we will write parser
//! and evaluator of arithmetic S-expressions,
//! which look like this:
//! ```
//! (+ (* 15 2) 62)
//! ```
/// Currently, rowan doesn't have a hook to add your own interner,
/// but `SmolStr` should be a "good enough" type for representing
/// tokens.
/// Additionally, rowa... | {
Eof,
RParen,
Ok,
}
impl Parser {
fn parse(mut self) -> Parse {
// Make sure that the root node covers all source
self.builder.start_node(ROOT.into());
// Parse a list of S-expressions
loop {
match self.sexp() {
... | SexpRes | identifier_name |
s_expressions.rs | //! In this tutorial, we will write parser
//! and evaluator of arithmetic S-expressions,
//! which look like this:
//! ```
//! (+ (* 15 2) 62)
//! ```
/// Currently, rowan doesn't have a hook to add your own interner,
/// but `SmolStr` should be a "good enough" type for representing
/// tokens.
/// Additionally, rowa... | (+ (* 15 2) 62)
";
let root = parse(sexps);
let res = root.syntax().sexps().map(|it| it.eval()).collect::<Vec<_>>();
eprintln!("{:?}", res);
assert_eq!(res, vec![Some(92), Some(92), None, None, Some(92),])
}
fn lex(text: &str) -> Vec<(SyntaxKind, SmolStr)> {
fn tok(t: SyntaxKind) -> m_lexer::TokenK... | let sexps = "
92
(+ 62 30)
(/ 92 0)
nan | random_line_split |
s_expressions.rs | //! In this tutorial, we will write parser
//! and evaluator of arithmetic S-expressions,
//! which look like this:
//! ```
//! (+ (* 15 2) 62)
//! ```
/// Currently, rowan doesn't have a hook to add your own interner,
/// but `SmolStr` should be a "good enough" type for representing
/// tokens.
/// Additionally, rowa... | "R_PAREN@[14; 15)".to_string(),
]
);
}
/// So far, we've been working with a homogeneous untyped tree.
/// It's nice to provide generic tree operations, like traversals,
/// but it's a bad fit for semantic analysis.
/// This crate itself does not provide AST facilities directly,
/// but it is ... | {
let text = "(+ (* 15 2) 62)";
let node = parse(text);
assert_eq!(
format!("{:?}", node),
"ROOT@[0; 15)", // root node, spanning 15 bytes
);
assert_eq!(node.children().count(), 1);
let list = node.children().next().unwrap();
let children = list.children().map(|child| format!... | identifier_body |
s_expressions.rs | //! In this tutorial, we will write parser
//! and evaluator of arithmetic S-expressions,
//! which look like this:
//! ```
//! (+ (* 15 2) 62)
//! ```
/// Currently, rowan doesn't have a hook to add your own interner,
/// but `SmolStr` should be a "good enough" type for representing
/// tokens.
/// Additionally, rowa... |
}
fn kind(&self) -> SexpKind {
Atom::cast(self.0.clone())
.map(SexpKind::Atom)
.or_else(|| List::cast(self.0.clone()).map(SexpKind::List))
.unwrap()
}
}
// Let's enhance AST nodes with ancillary functions and
// eval.
impl Root {
fn sexps(&self) -> impl Iterat... | {
None
} | conditional_block |
ifd.rs | //! Function for reading TIFF tags
use std::io::{self, Read, Seek};
use std::collections::{HashMap};
use super::stream::{ByteOrder, SmartReader, EndianReader};
use self::Value::{Unsigned, List};
macro_rules! tags {
{$(
$tag:ident
$val:expr;
)*} => {
/// TIFF tag
#[derive(Clo... | (type_: Type, count: u32, offset: [u8; 4] ) -> Entry {
Entry {
type_: type_,
count: count,
offset: offset,
}
}
/// Returns a mem_reader for the offset/value field
pub fn r(&self, byte_order: ByteOrder) -> SmartReader<io::Cursor<Vec<u8>>> {
SmartRe... | new | identifier_name |
ifd.rs | //! Function for reading TIFF tags
use std::io::{self, Read, Seek};
use std::collections::{HashMap};
use super::stream::{ByteOrder, SmartReader, EndianReader};
use self::Value::{Unsigned, List};
macro_rules! tags {
{$(
$tag:ident
$val:expr;
)*} => {
/// TIFF tag
#[derive(Clo... | // tags!{
// // Baseline tags:
// Artist 315; // TODO add support
// // grayscale images PhotometricInterpretation 1 or 3
// BitsPerSample 258;
// CellLength 265; // TODO add support
// CellWidth 264; // TODO add support
// // palette-color images (PhotometricInterpretation 3)
// ColorMa... |
// Note: These tags appear in the order they are mentioned in the TIFF reference
// https://partners.adobe.com/public/developer/en/tiff/TIFF6.pdf | random_line_split |
command.rs | // Copyright 2014 The Gfx-rs 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 ag... | }
}
}
#[allow(missing_docs)]
#[derive(Debug)]
pub struct AccessGuardBuffers<'a, R: Resources> {
buffers: AccessInfoBuffers<'a, R>
}
impl<'a, R: Resources> Iterator for AccessGuardBuffers<'a, R> {
type Item = (&'a handle::RawBuffer<R>, &'a mut R::Mapping);
fn next(&mut self) -> Option<Self::It... | for buffer in self.inner.mapped_reads().chain(self.inner.mapped_writes()) {
unsafe {
buffer.mapping().unwrap().release_access();
} | random_line_split |
command.rs | // Copyright 2014 The Gfx-rs 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 ag... | (&self) -> AccessInfoBuffers<R> {
self.mapped_reads.iter()
}
/// Returns the mapped buffers that The GPU will write to
pub fn mapped_writes(&self) -> AccessInfoBuffers<R> {
self.mapped_writes.iter()
}
/// Is there any mapped buffer reads?
pub fn has_mapped_reads(&self) -> bool ... | mapped_reads | identifier_name |
command.rs | // Copyright 2014 The Gfx-rs 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 ag... |
}
/// Register a buffer write access
pub fn buffer_write(&mut self, buffer: &handle::RawBuffer<R>) {
if buffer.is_mapped() {
self.mapped_writes.insert(buffer.clone());
}
}
/// Returns the mapped buffers that The GPU will read from
pub fn mapped_reads(&self) -> Acce... | {
self.mapped_reads.insert(buffer.clone());
} | conditional_block |
command.rs | // Copyright 2014 The Gfx-rs 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 ag... |
}
/// Informations about what is accessed by a bunch of commands.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AccessInfo<R: Resources> {
mapped_reads: HashSet<handle::RawBuffer<R>>,
mapped_writes: HashSet<handle::RawBuffer<R>>,
}
impl<R: Resources> AccessInfo<R> {
/// Creates empty access informati... | {
ClearColor::Uint([v, 0, 0, 0])
} | identifier_body |
converter.rs | use spirv_cross::{
glsl,
spirv,
};
use shaderc;
use std::{
iter,
path::{Path, PathBuf},
fs::File,
io::Read,
collections::HashMap,
};
use GlslVersion;
use Stage;
use ConvertedShader;
use error::Error;
#[derive(Debug, Clone)]
pub struct ConverterOptions {
/// Additional directories to ... | () -> Self {
ConverterOptions {
include_search_paths: Vec::new(),
macros: HashMap::new(),
target_version: GlslVersion::V1_00Es,
}
}
}
impl ConverterOptions {
pub fn new() -> Self {
Self::default()
}
fn resolve_include(&self,
... | default | identifier_name |
converter.rs | use spirv_cross::{
glsl,
spirv,
};
use shaderc;
use std::{
iter,
path::{Path, PathBuf},
fs::File,
io::Read,
collections::HashMap,
};
use GlslVersion;
use Stage;
use ConvertedShader;
use error::Error;
#[derive(Debug, Clone)]
pub struct ConverterOptions {
/// Additional directories to ... | },
})?;
let shader = ast.compile()?;
let uniforms = find_uniform_mappings(&ast)?;
Ok(ConvertedShader {
shader,
uniforms,
})
}
fn hlsl_to_spirv(&mut self,
source: &str,
source_filename: &str,... | {
let source_path = source_path.into();
let source_filename = source_path.to_string_lossy();
let mut source = String::new();
File::open(&source_path)?.read_to_string(&mut source)?;
let spirv = self.hlsl_to_spirv(&source,
source_filename.as... | identifier_body |
converter.rs | use spirv_cross::{
glsl,
spirv,
};
use shaderc;
use std::{
iter,
path::{Path, PathBuf},
fs::File,
io::Read,
collections::HashMap,
};
use GlslVersion;
use Stage;
use ConvertedShader;
use error::Error;
#[derive(Debug, Clone)]
pub struct ConverterOptions {
/// Additional directories to ... | }))
.collect();
find_source_file(name, &search_paths_and_parent)?
}
_ => find_source_file(name, &self.include_search_paths)?
};
let mut content = String::new();
File::open(&path)
.and_then(|mut include_f... | let path = match (include_type, PathBuf::from(name).parent()) {
(shaderc::IncludeType::Relative, Some(parent_path)) => {
let mut search_paths_and_parent: Vec<_> = iter::once(parent_path)
.chain(self.include_search_paths.iter().map(|path_buf_ref| {
... | random_line_split |
main.rs | #![no_std]
#![no_main]
// pick a panicking behavior
// extern crate panic_halt; // you can put a breakpoint on `rust_begin_unwind` to catch panics
// extern crate panic_abort; // requires nightly
// extern crate panic_itm; // logs messages over ITM; requires ITM support
extern crate panic_semihosting; // logs messages... |
loop {
if can1.tx[0].tir.read().txrq().bit_is_clear() {
break;
}
}
loop {
led.set_high().unwrap();
delay.delay_ms(1000_u32);
led.set_low().unwrap();
delay.delay_ms(1000_u32);
}
}
loop {
... | random_line_split | |
main.rs | #![no_std]
#![no_main]
// pick a panicking behavior
// extern crate panic_halt; // you can put a breakpoint on `rust_begin_unwind` to catch panics
// extern crate panic_abort; // requires nightly
// extern crate panic_itm; // logs messages over ITM; requires ITM support
extern crate panic_semihosting; // logs messages... | (clocks.hclk().0 / 1000000).numtoa_str(10, &mut buffer);
write_bytes_to_serial(&mut tx, &buffer);
write_string_to_serial(&mut tx, "\n");
let mut buffer = [0u8; 20];
write_string_to_serial(&mut tx, "APB1: ");
(clocks.pclk1().0 / 1000000).numtoa_str(10, &mut buffer);
... | {
if let (Some(dp), Some(cp)) = (
stm32::Peripherals::take(),
cortex_m::peripheral::Peripherals::take(),
) {
let gpiob = dp.GPIOB.split();
let mut led = gpiob.pb7.into_push_pull_output();
let rcc = dp.RCC.constrain();
let clocks = rcc.cfgr.sysclk(100.mhz()).freez... | identifier_body |
main.rs | #![no_std]
#![no_main]
// pick a panicking behavior
// extern crate panic_halt; // you can put a breakpoint on `rust_begin_unwind` to catch panics
// extern crate panic_abort; // requires nightly
// extern crate panic_itm; // logs messages over ITM; requires ITM support
extern crate panic_semihosting; // logs messages... |
delay.delay_ms(1000_u32);
write_string_to_serial(&mut tx, "Waiting for INAK to be cleared\n");
}
write_string_to_serial(&mut tx, "INAK cleared\n");
// Set to standard identifier
unsafe {
can1.tx[0]
.tir
.modify(|_, w| w... | {
break;
} | conditional_block |
main.rs | #![no_std]
#![no_main]
// pick a panicking behavior
// extern crate panic_halt; // you can put a breakpoint on `rust_begin_unwind` to catch panics
// extern crate panic_abort; // requires nightly
// extern crate panic_itm; // logs messages over ITM; requires ITM support
extern crate panic_semihosting; // logs messages... | <X, Y>(
uart: USART3,
tx: PD8<X>,
rx: PD9<Y>,
baudrate: Bps,
clocks: Clocks,
) -> hal::serial::Tx<stm32f4::stm32f413::USART3> {
let config = Config {
baudrate,
..Config::default()
};
let tx = tx.into_alternate_af7();
let rx = rx.into_alternate_af7();
let serial = ... | configure | identifier_name |
main.rs | #![feature(array_windows)]
#![feature(format_args_capture)]
#![feature(total_cmp)]
use clap::App;
use fxhash::{FxHashMap as HashMap, FxHashSet as HashSet};
use liblinear::util::TrainingInput;
use liblinear::{Builder as LiblinearBuilder, LibLinearModel as _, SolverType};
use regex::Regex;
use serde::{Deserialize, Seria... | let mut feature_map = FeatureMap { map: mem::take(&mut model.features), features: Vec::new() };
// Classify tests that are not yet classified using the model.
let mut files = HashMap::default();
for dir in &[&root.join("issues"), root] {
for entry in fs::read_dir(dir)? {
let entry =... | let mut model: Model = serde_json::from_str(&model_str)?; | random_line_split |
main.rs | #![feature(array_windows)]
#![feature(format_args_capture)]
#![feature(total_cmp)]
use clap::App;
use fxhash::{FxHashMap as HashMap, FxHashSet as HashSet};
use liblinear::util::TrainingInput;
use liblinear::{Builder as LiblinearBuilder, LibLinearModel as _, SolverType};
use regex::Regex;
use serde::{Deserialize, Seria... |
}
impl ClassifiedTest {
fn max_score(&self) -> f64 {
self.class_scores[0].1
}
}
fn is_id_start(c: char) -> bool {
// This is XID_Start OR '_' (which formally is not a XID_Start).
// We also add fast-path for ascii idents
('a'..='z').contains(&c)
|| ('A'..='Z').contains(&c)
... | {
if let Some(index) = self.map.get(&*feature) {
Some(*index)
} else if read_only {
None
} else {
let new_index = u32::try_from(self.features.len()).unwrap();
self.features.push(feature.clone().into_owned());
self.map.insert(feature.int... | identifier_body |
main.rs | #![feature(array_windows)]
#![feature(format_args_capture)]
#![feature(total_cmp)]
use clap::App;
use fxhash::{FxHashMap as HashMap, FxHashSet as HashSet};
use liblinear::util::TrainingInput;
use liblinear::{Builder as LiblinearBuilder, LibLinearModel as _, SolverType};
use regex::Regex;
use serde::{Deserialize, Seria... | lse if let prefix @ Some(_) = name.strip_suffix(".stderr") {
prefix
} else if let prefix @ Some(_) = name.strip_suffix(".stdout") {
prefix
} else if let prefix @ Some(_) = name.strip_suffix(".fixed") {
prefix
} else {
None
};
if let... | prefix
} e | conditional_block |
main.rs | #![feature(array_windows)]
#![feature(format_args_capture)]
#![feature(total_cmp)]
use clap::App;
use fxhash::{FxHashMap as HashMap, FxHashSet as HashSet};
use liblinear::util::TrainingInput;
use liblinear::{Builder as LiblinearBuilder, LibLinearModel as _, SolverType};
use regex::Regex;
use serde::{Deserialize, Seria... | (s: &str) -> &str {
const KEYWORDS: &[&str] = &[
"_",
"as",
"break",
"const",
"continue",
"crate",
"else",
"enum",
"extern",
"false",
"fn",
"for",
"if",
"impl",
"in",
"let",
"loop"... | generalize | identifier_name |
lib.rs | #![allow(dead_code)]
extern crate libc;
extern crate zmq_ffi;
#[macro_use]
extern crate cfg_if;
mod socket;
mod errno;
pub use socket::*;
pub use errno::*;
use std::ops::{ Deref, DerefMut };
use std::ffi;
use std::vec::Vec;
use std::slice;
use std::mem::transmute;
use libc::{ c_int, c_void, size_t };
pub const ZMQ_... | () -> c_int {
unsafe {
zmq_ffi::zmq_errno()
}
}
fn strerror(errnum: c_int) -> String {
unsafe {
let s = zmq_ffi::zmq_strerror(errnum);
ffi::CStr::from_ptr(s).to_str().unwrap().to_string()
}
}
/// Report 0MQ library version
///
/// Binding of `void zmq_version (int *major, int *... | errno | identifier_name |
lib.rs | #![allow(dead_code)]
extern crate libc;
extern crate zmq_ffi;
#[macro_use]
extern crate cfg_if;
mod socket;
mod errno;
pub use socket::*;
pub use errno::*;
use std::ops::{ Deref, DerefMut };
use std::ffi;
use std::vec::Vec;
use std::slice;
use std::mem::transmute;
use libc::{ c_int, c_void, size_t };
pub const ZMQ_... | pub fn has_capability(capability: &str) -> bool {
let capability_cstr = ffi::CString::new(capability).unwrap();
let rc = unsafe { zmq_ffi::zmq_has(capability_cstr.as_ptr()) };
rc == 1
}
// Encryption functions
/* Encode data with Z85 encoding. Returns encoded data */
//ZMQ_EXPORT ch... | /// Bindng of `int zmq_has (const char *capability);`
///
/// The function shall report whether a specified capability is available in the library | random_line_split |
lib.rs | #![allow(dead_code)]
extern crate libc;
extern crate zmq_ffi;
#[macro_use]
extern crate cfg_if;
mod socket;
mod errno;
pub use socket::*;
pub use errno::*;
use std::ops::{ Deref, DerefMut };
use std::ffi;
use std::vec::Vec;
use std::slice;
use std::mem::transmute;
use libc::{ c_int, c_void, size_t };
pub const ZMQ_... | /// Move content of a message to another message.
///
/// Binding of `int zmq_msg_move (zmq_msg_t *dest, zmq_msg_t *src);`.
///
/// Move the content of the message object referenced by src to the message object referenced by dest.
/// No actual copying of message content is performed,
/// dest... | unsafe {
let mut msg = try!(Message::with_capcity(data.len()));
std::ptr::copy_nonoverlapping(data.as_ptr(), msg.as_mut_ptr(), data.len());
Ok(msg)
}
}
| identifier_body |
lib.rs | #![allow(dead_code)]
extern crate libc;
extern crate zmq_ffi;
#[macro_use]
extern crate cfg_if;
mod socket;
mod errno;
pub use socket::*;
pub use errno::*;
use std::ops::{ Deref, DerefMut };
use std::ffi;
use std::vec::Vec;
use std::slice;
use std::mem::transmute;
use libc::{ c_int, c_void, size_t };
pub const ZMQ_... | e {
unsafe { Some(ffi::CStr::from_ptr(returned_str_ptr).to_str().unwrap()) }
}
}
}
impl Deref for Message {
type Target = [u8];
fn deref<'a>(&'a self) -> &'a [u8] {
unsafe {
let ptr = self.get_const_data_ptr();
let len = self.len() as usize;
... | None
} els | conditional_block |
blk_device.rs | //!
//! This module implements the list_block_devices() gRPC method
//! for listing available disk devices on the current host.
//!
//! The relevant information is obtained via udev.
//! The method works by iterating through udev records and selecting block
//! (ie. SUBSYSTEM=block) devices that represent either disks ... | (
parent: Option<&str>,
disk: &Device,
mounts: &HashMap<OsString, MountInfo>,
) -> Result<Vec<BlockDevice>, Error> {
let mut list: Vec<BlockDevice> = Vec::new();
let mut enumerator = Enumerator::new()?;
enumerator.match_parent(disk)?;
enumerator.match_property("DEVTYPE", "partition")?;
... | get_partitions | identifier_name |
blk_device.rs | //!
//! This module implements the list_block_devices() gRPC method
//! for listing available disk devices on the current host.
//!
//! The relevant information is obtained via udev.
//! The method works by iterating through udev records and selecting block
//! (ie. SUBSYSTEM=block) devices that represent either disks ... |
Some(Filesystem {
fstype: fstype.unwrap_or_else(|| String::from("")),
label: label.unwrap_or_else(|| String::from("")),
uuid: uuid.unwrap_or_else(|| String::from("")),
mountpoint: mountinfo
.map(|m| String::from(m.dest.to_string_lossy()))
.unwrap_or_else(|| St... | {
return None;
} | conditional_block |
blk_device.rs | //!
//! This module implements the list_block_devices() gRPC method
//! for listing available disk devices on the current host.
//!
//! The relevant information is obtained via udev.
//! The method works by iterating through udev records and selecting block
//! (ie. SUBSYSTEM=block) devices that represent either disks ... |
// Iterate through udev to generate a list of all (block) devices
// with DEVTYPE == "disk"
fn get_disks(
all: bool,
mounts: &HashMap<OsString, MountInfo>,
) -> Result<Vec<BlockDevice>, Error> {
let mut list: Vec<BlockDevice> = Vec::new();
let mut enumerator = Enumerator::new()?;
enumerator.matc... | {
let mut table: HashMap<OsString, MountInfo> = HashMap::new();
for mount in (MountIter::new()?).flatten() {
table.insert(OsString::from(mount.source.clone()), mount);
}
Ok(table)
} | identifier_body |
blk_device.rs | //!
//! This module implements the list_block_devices() gRPC method
//! for listing available disk devices on the current host.
//!
//! The relevant information is obtained via udev.
//! The method works by iterating through udev records and selecting block
//! (ie. SUBSYSTEM=block) devices that represent either disks ... |
// Get the list of current filesystem mounts.
fn get_mounts() -> Result<HashMap<OsString, MountInfo>, Error> {
let mut table: HashMap<OsString, MountInfo> = HashMap::new();
for mount in (MountIter::new()?).flatten() {
table.insert(OsString::from(mount.source.clone()), mount);
}
Ok(table)
}
/... | });
}
None
} | random_line_split |
tpm.rs | <u8>)> {
// Set encryption algorithm
let alg = match alg {
Some(a) => a,
None => {
match config_get(
"cloud_agent",
"tpm_encryption_alg",
)?
.as_str()
{
"rsa" => AsymmetricAlgorithm::Rsa,
... | 23 => PcrSlot::Slot23,
bit => return Err(KeylimeError::Other(format!("malformed mask in integrity quote: only pcrs 0-23 can be included, but mask included pcr {:?}", bit))),
},
)
}
}
Ok(pcrs)
}
// This encodes a quote string as input ... | 20 => PcrSlot::Slot20,
21 => PcrSlot::Slot21,
22 => PcrSlot::Slot22, | random_line_split |
tpm.rs | u8>)> {
// Set encryption algorithm
let alg = match alg {
Some(a) => a,
None => {
match config_get(
"cloud_agent",
"tpm_encryption_alg",
)?
.as_str()
{
"rsa" => AsymmetricAlgorithm::Rsa,
... | hasher.update(&keybytes);
let mut hashvec: Vec<u8> = hasher.finish().into();
keydigest.set(HashingAlgorithm::Sha1, Digest::try_from(hashvec)?);
Ok(keydigest)
}
// Reads a mask in the form of some hex value, ex. "0x408000",
// translating bits that are set to pcrs to include in the list.
//
// The mas... | {
let mut keydigest = DigestValues::new();
let keybytes = match pubkey.id() {
Id::RSA => pubkey.rsa()?.public_key_to_pem()?,
other_id => {
return Err(KeylimeError::Other(format!(
"Converting to digest value for key type {:?} is not yet implemented",
other_id
... | identifier_body |
tpm.rs | u8>)> {
// Set encryption algorithm
let alg = match alg {
Some(a) => a,
None => {
match config_get(
"cloud_agent",
"tpm_encryption_alg",
)?
.as_str()
{
"rsa" => AsymmetricAlgorithm::Rsa,
... | () -> Self {
TpmSigScheme::AlgNull
}
}
// Returns TSS struct corresponding to a signature scheme.
pub(crate) fn get_sig_scheme(
scheme: TpmSigScheme,
) -> Result<TPMT_SIG_SCHEME> {
match scheme {
// The TPM2_ALG_NULL sig scheme can be filled out with placeholder data
// in the detai... | default | identifier_name |
foreign.rs | // Copyright 2019 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... |
/// verify slate messages
pub fn verify_slate_messages(slate: &Slate) -> Result<(), Error> {
slate.verify_messages()
}
/// Receive a tx as recipient
/// Note: key_id & output_amounts needed for secure claims, mwc713.
pub fn receive_tx<'a, T:?Sized, C, K>(
w: &mut T,
keychain_mask: Option<&SecretKey>,
slate: &Sla... | {
updater::build_coinbase(&mut *w, keychain_mask, block_fees, test_mode)
} | identifier_body |
foreign.rs | // Copyright 2019 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... | pub fn build_coinbase<'a, T:?Sized, C, K>(
w: &mut T,
keychain_mask: Option<&SecretKey>,
block_fees: &BlockFees,
test_mode: bool,
) -> Result<CbData, Error>
where
T: WalletBackend<'a, C, K>,
C: NodeClient + 'a,
K: Keychain + 'a,
{
updater::build_coinbase(&mut *w, keychain_mask, block_fees, test_mode)
}
/// ver... | })
}
/// Build a coinbase transaction | random_line_split |
foreign.rs | // Copyright 2019 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... | () -> Result<VersionInfo, Error> {
// Proof address will be the onion address (Dalec Paublic Key). It is exactly what we need
Ok(VersionInfo {
foreign_api_version: FOREIGN_API_VERSION,
supported_slate_versions: SlateVersion::iter().collect(),
})
}
/// Build a coinbase transaction
pub fn build_coinbase<'a, T:?Si... | check_version | identifier_name |
foreign.rs | // Copyright 2019 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... |
tx::update_message(&mut *w, keychain_mask, &ret_slate)?;
let excess = ret_slate.calc_excess(Some(&keychain))?;
if let Some(ref mut p) = ret_slate.payment_proof {
if p.sender_address
.public_key
.eq(&p.receiver_address.public_key)
{
debug!("file proof, replace the receiver address with its address");... | {
// Add our contribution to the offset
ret_slate.adjust_offset(&keychain, &mut context)?;
} | conditional_block |
renderer.rs | use crate::fft::*;
use crate::Opt;
use anyhow::Result;
use rustfft::num_traits::Zero;
use std::{fs::File, io::Read, path::PathBuf, slice};
use wgpu::util::DeviceExt;
use winit::{event::*, window::Window};
#[repr(transparent)]
#[derive(Copy, Clone)]
struct PodComplex(FftSample);
unsafe impl bytemuck::Zeroable for PodC... | sc_desc,
swap_chain,
size,
render_pipeline,
render_parameters,
fft_vec,
render_parameters_buffer: render_param_buffer,
fft_vec_buffer,
bind_group,
})
}
pub fn resize(&mut self, new_size: winit::d... | device,
queue, | random_line_split |
renderer.rs | use crate::fft::*;
use crate::Opt;
use anyhow::Result;
use rustfft::num_traits::Zero;
use std::{fs::File, io::Read, path::PathBuf, slice};
use wgpu::util::DeviceExt;
use winit::{event::*, window::Window};
#[repr(transparent)]
#[derive(Copy, Clone)]
struct PodComplex(FftSample);
unsafe impl bytemuck::Zeroable for PodC... |
pub fn render(&mut self) {
let frame = self
.swap_chain
.get_current_frame()
.expect("Timeout getting texture")
.output;
let mut encoder = self
.device
.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label... | {
self.render_parameters = GpuRenderParameters {
screen_wx: self.size.width,
screen_hy: self.size.height,
..self.render_parameters
};
self.queue.write_buffer(
&self.render_parameters_buffer,
0,
bytemuck::cast_slice(slice::fr... | identifier_body |
renderer.rs | use crate::fft::*;
use crate::Opt;
use anyhow::Result;
use rustfft::num_traits::Zero;
use std::{fs::File, io::Read, path::PathBuf, slice};
use wgpu::util::DeviceExt;
use winit::{event::*, window::Window};
#[repr(transparent)]
#[derive(Copy, Clone)]
struct PodComplex(FftSample);
unsafe impl bytemuck::Zeroable for PodC... | (&mut self, new_size: winit::dpi::PhysicalSize<u32>) {
self.size = new_size;
self.sc_desc.width = new_size.width;
self.sc_desc.height = new_size.height;
self.swap_chain = self.device.create_swap_chain(&self.surface, &self.sc_desc);
}
pub fn input(&mut self, event: &WindowEvent) ... | resize | identifier_name |
error.rs | //! Errorand Result types.
use crate::database::Database;
use crate::types::Type;
use std::any::type_name;
use std::error::Error as StdError;
use std::fmt::{self, Debug, Display};
use std::io;
#[allow(unused_macros)]
macro_rules! decode_err {
($s:literal, $($args:tt)*) => {
crate::Error::Decode(format!($s... | #[doc(hidden)]
fn into_box_err(self: Box<Self>) -> Box<dyn StdError + Send + Sync +'static>;
}
impl dyn DatabaseError {
/// Downcast this `&dyn DatabaseError` to a specific database error type:
///
/// * [PgError][crate::postgres::PgError] (if the `postgres` feature is active)
/// * [MySqlError... | #[doc(hidden)]
fn as_mut_err(&mut self) -> &mut (dyn StdError + Send + Sync + 'static);
| random_line_split |
error.rs | //! Errorand Result types.
use crate::database::Database;
use crate::types::Type;
use std::any::type_name;
use std::error::Error as StdError;
use std::fmt::{self, Debug, Display};
use std::io;
#[allow(unused_macros)]
macro_rules! decode_err {
($s:literal, $($args:tt)*) => {
crate::Error::Decode(format!($s... |
}
impl<'de> Deserialize<'de> for Error {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let r = deserializer.deserialize_string(ErrorVisitor)?;
return Ok(Error::from(r));
}
}
#[test]
fn test_json_error(){
l... | {
Ok(v.to_string())
} | identifier_body |
error.rs | //! Errorand Result types.
use crate::database::Database;
use crate::types::Type;
use std::any::type_name;
use std::error::Error as StdError;
use std::fmt::{self, Debug, Display};
use std::io;
#[allow(unused_macros)]
macro_rules! decode_err {
($s:literal, $($args:tt)*) => {
crate::Error::Decode(format!($s... | <DB: Database, T>(expected: DB::TypeInfo) -> Self
where
T: Type<DB>,
{
let ty_name = type_name::<T>();
return decode_err!(
"mismatched types; Rust type `{}` (as SQL type {}) is not compatible with SQL type {}",
ty_name,
T::type_info(),
... | mismatched_types | identifier_name |
emitter.rs | extern crate xml;
use polyfill;
use std::str::FromStr;
use std::collections::BTreeMap;
/// Parse a float with appropriate panic message on failure.
macro_rules! parse_float {
($s:expr) => (f64::from_str($s).expect("Failed to parse float"))
}
pub struct Color {
r: u8, g: u8, b: u8
}
impl Color {
pub fn ... | (&mut self, attributes: &Vec<xml::attribute::OwnedAttribute>) -> Rect {
// x, y, w, h, style
let mut params = (None, None, None, None, None);
for ref attr in attributes {
let name: &str = &attr.name.local_name;
match name {
"x" ... | parse_rect | identifier_name |
emitter.rs | extern crate xml;
use polyfill;
use std::str::FromStr;
use std::collections::BTreeMap;
/// Parse a float with appropriate panic message on failure.
macro_rules! parse_float {
($s:expr) => (f64::from_str($s).expect("Failed to parse float"))
}
pub struct Color {
r: u8, g: u8, b: u8
}
impl Color {
pub fn ... |
for ref attr in attributes {
let name: &str = &attr.name.local_name;
match name {
"x" => params.0 = Some(attr.value.clone()),
"y" => params.1 = Some(attr.value.clone()),
"width" => params.2 = Some(attr.value.clone()),
... | /// Parse a rect with origin at the bottom right (??)
///
pub fn parse_rect(&mut self, attributes: &Vec<xml::attribute::OwnedAttribute>) -> Rect {
// x, y, w, h, style
let mut params = (None, None, None, None, None); | random_line_split |
emitter.rs | extern crate xml;
use polyfill;
use std::str::FromStr;
use std::collections::BTreeMap;
/// Parse a float with appropriate panic message on failure.
macro_rules! parse_float {
($s:expr) => (f64::from_str($s).expect("Failed to parse float"))
}
pub struct Color {
r: u8, g: u8, b: u8
}
impl Color {
pub fn ... |
fn emit_physics(&self, id: &str, physicsbody: &str) {
println!("// Physics for {}", id);
let emit_shape = |a: &[f64; 2], b: &[f64; 2]|
println!(
"{}->addShape(PhysicsShapeEdgeSegment::create(Vec2({:.10}f, {:.10}f), Vec2({:.10}f, {:.10}f)));",
Emitter::v... | {
println!("// Rect for {}", id);
// arguments: origin, destination, color
println!(
"{}->drawSolidRect(Vec2({:.10}f,{:.10}f), Vec2({:.10}f,{:.10}f), {});",
Emitter::varname(id, drawnode),
self.x, self.y,
self.x+self.w, self.y+self.h,
... | identifier_body |
block.rs | use crate::error::{ViuError, ViuResult};
use crate::printer::Printer;
use crate::Config;
use ansi_colours::ansi256_from_rgb;
use image::{DynamicImage, GenericImageView, Rgba};
use std::io::Write;
use termcolor::{Buffer, BufferWriter, Color, ColorChoice, ColorSpec, WriteColor};
use crossterm::cursor::{MoveRight, MoveT... |
}
// enum used to keep track where the current line of pixels processed should be displayed - as
// background or foreground color
#[derive(PartialEq)]
enum Mode {
Top,
Bottom,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_block_printer_small() {
let img = DynamicImage::ImageR... | {
Color::Ansi256(ansi256_from_rgb(rgb))
} | conditional_block |
block.rs | use crate::error::{ViuError, ViuResult};
use crate::printer::Printer;
use crate::Config;
use ansi_colours::ansi256_from_rgb;
use image::{DynamicImage, GenericImageView, Rgba};
use std::io::Write;
use termcolor::{Buffer, BufferWriter, Color, ColorChoice, ColorSpec, WriteColor};
use crossterm::cursor::{MoveRight, MoveT... | if let Some(bg) = c.bg() {
new_color.set_fg(Some(*bg));
out_char = UPPER_HALF_BLOCK;
} else {
execute!(out_buffer, MoveRight(1))?;
continue;
}
out_color = &new_color;
} else {
match (c.fg(... | new_color = ColorSpec::new(); | random_line_split |
block.rs | use crate::error::{ViuError, ViuResult};
use crate::printer::Printer;
use crate::Config;
use ansi_colours::ansi256_from_rgb;
use image::{DynamicImage, GenericImageView, Rgba};
use std::io::Write;
use termcolor::{Buffer, BufferWriter, Color, ColorChoice, ColorSpec, WriteColor};
use crossterm::cursor::{MoveRight, MoveT... | () {
let img = DynamicImage::ImageRgba8(image::RgbaImage::new(2000, 1000));
let config = Config {
width: Some(160),
height: None,
absolute_offset: false,
transparent: true,
..Default::default()
};
let (w, h) = BlockPrinter {}.pr... | test_block_printer_large | identifier_name |
immutable.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may... | <U: ArrowNativeType, T: AsRef<[U]>>(items: &T) -> Self {
let slice = items.as_ref();
let capacity = slice.len() * std::mem::size_of::<U>();
let mut buffer = MutableBuffer::with_capacity(capacity);
buffer.extend_from_slice(slice);
buffer.into()
}
/// Creates a buffer from... | from_slice_ref | identifier_name |
immutable.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may... |
/// Returns a slice of this buffer starting at a certain bit offset.
/// If the offset is byte-aligned the returned buffer is a shallow clone,
/// otherwise a new buffer is allocated and filled with a copy of the bits in the range.
pub fn bit_slice(&self, offset: usize, len: usize) -> Self {
i... | {
// JUSTIFICATION
// Benefit
// Many of the buffers represent specific types, and consumers of `Buffer` often need to re-interpret them.
// Soundness
// * The pointer is non-null by construction
// * alignment asserted below.
let (prefix, offsets... | identifier_body |
immutable.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may... | macro_rules! check_as_typed_data {
($input: expr, $native_t: ty) => {{
let buffer = Buffer::from_slice_ref($input);
let slice: &[$native_t] = unsafe { buffer.typed_data::<$native_t>() };
assert_eq!($input, slice);
}};
}
#[test]
#[allow(clippy::float_c... | assert_eq!(buffer2, buffer_copy.ok().unwrap());
}
| random_line_split |
surface.rs | // Copyright 2013 The Servo Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at ... | (&self,
native_context: &NativeCompositingGraphicsContext,
texture: &Texture,
size: Size2D<isize>) {
// Create the GLX pixmap.
//
// FIXME(pcwalton): RAII for exception safety?
unsafe {
let pixma... | bind_to_texture | identifier_name |
surface.rs | // Copyright 2013 The Servo Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at ... | /// Creates graphics metadata from a metadata descriptor.
pub fn from_descriptor(descriptor: &NativeGraphicsMetadataDescriptor)
-> NativeGraphicsMetadata {
// WARNING: We currently rely on the X display connection being the
// same in both the Painting and Compositing ... | unsafe impl Send for NativeGraphicsMetadata {}
impl NativeGraphicsMetadata { | random_line_split |
surface.rs | // Copyright 2013 The Servo Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at ... |
pub fn mark_wont_leak(&mut self) {
self.will_leak = false;
}
}
| {
self.will_leak = true;
} | identifier_body |
surface.rs | // Copyright 2013 The Servo Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at ... |
}
}
impl PixmapNativeSurface {
fn from_pixmap(pixmap: Pixmap) -> PixmapNativeSurface {
PixmapNativeSurface {
pixmap: pixmap,
will_leak: true,
}
}
pub fn from_skia_shared_gl_context(context: SkiaSkNativeSharedGLContextRef)
... | {
panic!("You should have disposed of the pixmap properly with destroy()! This pixmap \
will leak!");
} | conditional_block |
backend.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... | (&self, hash: Block::Hash) -> Result<Block::Header> {
self.header(hash)?
.ok_or_else(|| Error::UnknownBlock(format!("Expect header: {}", hash)))
}
/// Convert an arbitrary block ID into a block number. Returns `UnknownBlock` error if block is
/// not found.
fn expect_block_number_from_id(&self, id: &BlockId<B... | expect_header | identifier_name |
backend.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... | ,
Ok(None) | Err(_) => {
missing_blocks.push(BlockId::<Block>::Number(parent_number));
break
},
}
route_head = meta.parent;
},
Err(_e) => {
missing_blocks.push(BlockId::<Block>::Hash(route_head));
break
},
}
}
}
if!missing_blocks.is_empty... | {
break
} | conditional_block |
backend.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... | Unknown,
} | pub enum BlockStatus {
/// Already in the blockchain.
InChain,
/// Not in the queue or the blockchain. | random_line_split |
mod.rs | //! General actions
#![allow(unused_imports)]
#![allow(dead_code)]
use chrono::*;
use std::{env,fs};
use std::time;
use std::fmt::Write;
use std::path::{Path,PathBuf};
use util;
use super::BillType;
use storage::{Storage,StorageDir,Storable,StorageResult};
use project::Project;
#[cfg(feature="document_export")]
u... |
/// Testing only, tries to run complete spec on all projects.
/// TODO make this not panic :D
/// TODO move this to `spec::all_the_things`
pub fn spec() -> Result<()> {
use project::spec::*;
let luigi = try!(setup_luigi());
//let projects = super::execute(||luigi.open_projects(StorageDir::All));
let p... | {
let metadata = try!(fs::metadata(path));
let accessed = try!(metadata.accessed());
Ok(try!(accessed.elapsed()))
} | identifier_body |
mod.rs | //! General actions
#![allow(unused_imports)]
#![allow(dead_code)]
use chrono::*;
use std::{env,fs};
use std::time;
use std::fmt::Write;
use std::path::{Path,PathBuf};
use util;
use super::BillType;
use storage::{Storage,StorageDir,Storable,StorageResult};
use project::Project;
#[cfg(feature="document_export")]
u... | }
/// Command UNARCHIVE <YEAR> <NAME>
/// TODO: return a list of files that have to be updated in git
pub fn unarchive_projects(year:i32, search_terms:&[&str]) -> Result<Vec<PathBuf>> {
let luigi = try!(setup_luigi_with_git());
Ok(try!( luigi.unarchive_projects(year, search_terms) ))
} | random_line_split | |
mod.rs | //! General actions
#![allow(unused_imports)]
#![allow(dead_code)]
use chrono::*;
use std::{env,fs};
use std::time;
use std::fmt::Write;
use std::path::{Path,PathBuf};
use util;
use super::BillType;
use storage::{Storage,StorageDir,Storable,StorageResult};
use project::Project;
#[cfg(feature="document_export")]
u... | (projects:&[Project]) -> Result<String>{
let mut string = String::new();
let splitter = ";";
try!(writeln!(&mut string, "{}", [ "Rnum", "Bezeichnung", "Datum", "Rechnungsdatum", "Betreuer", "Verantwortlich", "Bezahlt am", "Betrag", "Canceled"].join(splitter)));
for project in projects{
try!(writ... | projects_to_csv | identifier_name |
mod.rs | //! General actions
#![allow(unused_imports)]
#![allow(dead_code)]
use chrono::*;
use std::{env,fs};
use std::time;
use std::fmt::Write;
use std::path::{Path,PathBuf};
use util;
use super::BillType;
use storage::{Storage,StorageDir,Storable,StorageResult};
use project::Project;
#[cfg(feature="document_export")]
u... |
else {
debug!("I expected there to be a {}, but there wasn't any?", trash_file.display())
}
}
if pdffile.exists(){
debug!("now there is be a {:?} -> {:?}", pdffile, target);
try!(fs::rename(&pdffile, &target));
... | {
try!(fs::remove_file(&trash_file));
debug!("just deleted: {}", trash_file.display())
} | conditional_block |
main.rs |
use std::time::{SystemTime, UNIX_EPOCH};
fn f0() {
println!("Hello, Rust");
}
fn f1() {
let a = 12;
println!("a is {}", a);
println!("a is {}, a again is {}", a, a);
println!("a is {0}, a again is {0}", a);
}
fn f2() {
println!("{{}}");
}
fn f3() {
let x = 5;
let x = x + 1;
let x =... | u32,
}
impl Rectangle {
fn create(width: u32, height: u32) -> Rectangle {
Rectangle { width, height }
}
}
fn f37() {
let rect = Rectangle::create(30, 50);
println!("{:?}", rect);
}
#[derive(Debug)]
enum Book {
Papery, Electronic
}
fn f38() {
let book = Book::Papery;
println!("{:?... | ;
println!("{}", rect1.wider(&rect2));
}
struct Rectangle4 {
width: u32,
height: | identifier_body |
main.rs |
use std::time::{SystemTime, UNIX_EPOCH};
fn f0() {
println!("Hello, Rust");
}
fn f1() {
let a = 12;
println!("a is {}", a);
println!("a is {}, a again is {}", a, a);
println!("a is {0}, a again is {0}", a);
}
fn f2() {
println!("{{}}");
}
fn f3() {
let x = 5;
let x = x + 1;
let x =... | b = -1;
}
else {
b = 0;
}
println!("b is {}", b);
}
fn f14() {
let a = 3;
let number = if a > 0 { 1 } else { -1 };
println!("number 为 {}", number);
}
fn f15() {
let mut number = 1;
while number!= 4 {
println!("{}", number);
number += 1;
}
println... | b = 1;
}
else if a < 0 {
| conditional_block |
main.rs | use std::time::{SystemTime, UNIX_EPOCH};
fn f0() {
println!("Hello, Rust");
}
fn f1() {
let a = 12;
println!("a is {}", a);
println!("a is {}, a again is {}", a, a);
println!("a is {0}, a again is {0}", a);
}
fn f2() {
println!("{{}}");
}
fn f3() {
let x = 5;
let x = x + 1;
let x = ... | let sub = &s[0..2];
println!("{}", sub);
}
fn f60() {
let s = String::from("ENEEEEEE");
let sub = &s[0..3];
println!("{}", sub);
}
pub struct ClassName {
field: i32,
}
impl ClassName {
pub fn new(value: i32) -> ClassName {
ClassName {
field: value
}
}
... | }
fn f59() {
let s = String::from("EN中文"); | random_line_split |
main.rs |
use std::time::{SystemTime, UNIX_EPOCH};
fn f0() {
println!("Hello, Rust");
}
fn f1() {
let a = 12;
println!("a is {}", a);
println!("a is {}, a again is {}", a, a);
println!("a is {0}, a again is {0}", a);
}
fn f2() {
println!("{{}}");
}
fn f3() {
let x = 5;
let x = x + 1;
let x =... | let some_string = String::from("hello");
// some_string 被声明有效
return some_string;
// some_string 被当作返回值移动出函数
}
fn takes_and_gives_back(a_string: String) -> String {
// a_string 被声明有效
a_string // a_string 被当作返回值移出函数
}
fn f23() {
let s1 = String::from("hello");
let s2 = &s1;
println... | ring {
| identifier_name |
wakers.rs | // This file is Copyright its original authors, visible in version control
// history.
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// You may... | }
}
mod std_future {
use core::task::Waker;
pub struct StdWaker(pub Waker);
impl super::FutureCallback for StdWaker {
fn call(&self) { self.0.wake_by_ref() }
}
}
/// (C-not exported) as Rust Futures aren't usable in language bindings.
impl<'a> StdFuture for Future {
type Output = ();
fn poll(self: Pin<&mut ... | } else {
state.callbacks.push(callback);
} | random_line_split |
wakers.rs | // This file is Copyright its original authors, visible in version control
// history.
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// You may... | (&self) { (self)(); }
}
pub(crate) struct FutureState {
callbacks: Vec<Box<dyn FutureCallback>>,
complete: bool,
}
impl FutureState {
fn complete(&mut self) {
for callback in self.callbacks.drain(..) {
callback.call();
}
self.complete = true;
}
}
/// A simple future which can complete once, and calls so... | call | identifier_name |
wakers.rs | // This file is Copyright its original authors, visible in version control
// history.
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// You may... |
#[cfg(any(test, feature = "_test_utils"))]
pub fn notify_pending(&self) -> bool {
self.notify_pending.lock().unwrap().0
}
}
/// A callback which is called when a [`Future`] completes.
///
/// Note that this MUST NOT call back into LDK directly, it must instead schedule actions to be
/// taken later. Rust users ... | {
let mut lock = self.notify_pending.lock().unwrap();
if lock.0 {
Future {
state: Arc::new(Mutex::new(FutureState {
callbacks: Vec::new(),
complete: false,
}))
}
} else if let Some(existing_state) = &lock.1 {
Future { state: Arc::clone(&existing_state) }
} else {
let state = Arc::n... | identifier_body |
gamestate.rs | Board;
use crate::common::tile::{ TileId, Tile };
use crate::common::player::{ Player, PlayerId, PlayerColor };
use crate::common::penguin::Penguin;
use crate::common::action::{ Move, Placement };
use crate::common::boardposn::BoardPosn;
use crate::common::util;
use std::collections::HashSet;
use std::rc::Rc;
use std:... | () {
let board = Board::with_no_holes(3, 3, 3);
let gamestate = GameState::new(board, 4); // create game with 4 players
assert_eq!(gamestate.players.len(), 4);
// should have 6-n penguins per player
assert!(gamestate.players.iter().all(|(_, player)| player.penguins.len() == 2));... | test_new | identifier_name |
gamestate.rs | Board;
use crate::common::tile::{ TileId, Tile };
use crate::common::player::{ Player, PlayerId, PlayerColor };
use crate::common::penguin::Penguin;
use crate::common::action::{ Move, Placement };
use crate::common::boardposn::BoardPosn;
use crate::common::util;
use std::collections::HashSet;
use std::rc::Rc;
use std:... | };
board_string.push_str(&tile_string);
board_string.push_str(" ");
}
board_string.push_str("\n");
}
writeln!(f, "{}", board_string)?;
// Write each player, their score, and their penguin positions
for (player_i... | {
let mut board_string = String::new();
for y in 0..self.board.height {
if y % 2 == 1 {
board_string.push_str(" ");
}
for x in 0..self.board.width {
let tile_string = match self.board.get_tile_id(x, y) {
Some(id) ... | identifier_body |
gamestate.rs | Board;
use crate::common::tile::{ TileId, Tile };
use crate::common::player::{ Player, PlayerId, PlayerColor };
use crate::common::penguin::Penguin;
use crate::common::action::{ Move, Placement };
use crate::common::boardposn::BoardPosn;
use crate::common::util;
use std::collections::HashSet;
use std::rc::Rc;
use std:... |
self.players.remove(&player_id);
self.turn_order.retain(|id| *id!= player_id);
// Now actually advance the turn after the player is removed to properly
// handle the case where we skip the turns of possibly multiple players
// whose penguins are all stuck.
... | {
self.previous_turn_index();
} | conditional_block |
gamestate.rs | ::Board;
use crate::common::tile::{ TileId, Tile };
use crate::common::player::{ Player, PlayerId, PlayerColor };
use crate::common::penguin::Penguin;
use crate::common::action::{ Move, Placement };
use crate::common::boardposn::BoardPosn;
use crate::common::util;
use std::collections::HashSet;
use std::rc::Rc;
use st... | assert_eq!(gamestate.move_avatar_for_player_without_changing_turn(player_id, tile_0, tile_0), None);
assert_eq!(gamestate.move_avatar_for_player_without_changing_turn(player_id, tile_0, unreachable_tile), None);
// success, penguin should now be on tile 5
assert_eq!(gamestate.move_avata... | // Move failed: tile not reachable from tile 0 | random_line_split |
main.rs | //! [![github]](https://github.com/dtolnay/star-history) [![crates-io]](https://crates.io/crates/star-history) [![docs-rs]](https://docs.rs/star-history)
//!
//! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github
//! [crates-io]: https://img.shields.io/badge... | {
query: String,
}
#[derive(Deserialize, Debug)]
struct Response {
message: Option<String>,
#[serde(default, deserialize_with = "deserialize_data")]
data: VecDeque<Data>,
#[serde(default)]
errors: Vec<Message>,
}
#[derive(Deserialize, Debug)]
struct Message {
message: String,
}
#[derive(... | Request | identifier_name |
main.rs | //! [![github]](https://github.com/dtolnay/star-history) [![crates-io]](https://crates.io/crates/star-history) [![docs-rs]](https://docs.rs/star-history)
//!
//! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github
//! [crates-io]: https://img.shields.io/badge... |
}
}
let mut data = String::new();
data += "var data = [\n";
for arg in &args {
data += " {\"name\":\"";
data += &arg.to_string();
data += "\", \"values\":[\n";
let stars = &stars[arg];
for (i, star) in stars.iter().enumerate() {
data += ... | {
set.insert(Star {
time: now,
node: Default::default(),
});
} | conditional_block |
main.rs | //! [![github]](https://github.com/dtolnay/star-history) [![crates-io]](https://crates.io/crates/star-history) [![docs-rs]](https://docs.rs/star-history)
//!
//! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github
//! [crates-io]: https://img.shields.io/badge... | E: de::Error,
{
Ok(VecDeque::new())
}
}
deserializer.deserialize_any(ResponseVisitor)
}
fn non_nulls<'de, D, T>(deserializer: D) -> Result<Vec<T>, D::Error>
where
D: Deserializer<'de>,
T: Deserialize<'de>,
{
struct NonNullsVisitor<T>(PhantomData<fn() -> T>);... | random_line_split | |
main.rs | //! [![github]](https://github.com/dtolnay/star-history) [![crates-io]](https://crates.io/crates/star-history) [![docs-rs]](https://docs.rs/star-history)
//!
//! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github
//! [crates-io]: https://img.shields.io/badge... |
}
struct Work {
series: Series,
cursor: Cursor,
}
#[derive(Serialize)]
struct Request {
query: String,
}
#[derive(Deserialize, Debug)]
struct Response {
message: Option<String>,
#[serde(default, deserialize_with = "deserialize_data")]
data: VecDeque<Data>,
#[serde(default)]
errors: V... | {
match &self.0 {
Some(cursor) => {
formatter.write_str("\"")?;
formatter.write_str(cursor)?;
formatter.write_str("\"")?;
}
None => formatter.write_str("null")?,
}
Ok(())
} | identifier_body |
lib.rs | //! Implements sampling of loot tables.
use ahash::AHashMap;
use feather_items::{Item, ItemStack};
use feather_loot_model as model;
use inlinable_string::InlinableString;
use itertools::Itertools;
use model::{Condition, Entry, EntryKind, Function, FunctionKind, LootTableSet, Pool};
use once_cell::sync::Lazy;
use rand:... |
#[test]
fn grass_block_condition() {
let table = loot_table("blocks/grass_block").unwrap_or_else(|| {
panic!(
"missing loot table for grass block\nnote: loaded keys: {:?}",
STORE.keys()
);
});
let mut rng = StepRng::new(0, 1);
... | {
let table = loot_table("blocks/dirt").expect("missing loot table for dirt block");
let mut rng = StepRng::new(0, 1);
let items = table.sample(&mut rng, &Conditions::default()).unwrap();
assert_eq!(items.as_slice(), &[ItemStack::new(Item::Dirt, 1)]);
} | identifier_body |
lib.rs | //! Implements sampling of loot tables.
use ahash::AHashMap;
use feather_items::{Item, ItemStack};
use feather_loot_model as model;
use inlinable_string::InlinableString;
use itertools::Itertools;
use model::{Condition, Entry, EntryKind, Function, FunctionKind, LootTableSet, Pool};
use once_cell::sync::Lazy;
use rand:... |
})
.expect("entry finding algorithm incorrect");
sample_entry(entry, rng, results, conditions)?;
}
// apply functions to results
results
.iter_mut()
.try_for_each(|item| apply_functions(pool.functions.iter(), item, rng, conditions))?;
Ok(())
}
fn sample_... | {
cumulative_weight += entry.weight;
false
} | conditional_block |
lib.rs | //! Implements sampling of loot tables.
use ahash::AHashMap;
use feather_items::{Item, ItemStack};
use feather_loot_model as model;
use inlinable_string::InlinableString;
use itertools::Itertools;
use model::{Condition, Entry, EntryKind, Function, FunctionKind, LootTableSet, Pool};
use once_cell::sync::Lazy;
use rand:... | // the result. This algorithm is O(n) computaitonally, but this is unlikely
// to matter in practice, because loot tables rarely
// have more than one or two entries per pool.
let n = rng.gen_range(0, weight_sum);
let mut cumulative_weight = 0;
let entry = entries
... | for _ in 0..pool.rolls.sample(rng) {
// We choose an integer at random from [0, weight_sum) and
// determine which entry has a cumulative weight matching | random_line_split |
lib.rs | //! Implements sampling of loot tables.
use ahash::AHashMap;
use feather_items::{Item, ItemStack};
use feather_loot_model as model;
use inlinable_string::InlinableString;
use itertools::Itertools;
use model::{Condition, Entry, EntryKind, Function, FunctionKind, LootTableSet, Pool};
use once_cell::sync::Lazy;
use rand:... | <'a>(
mut conditions: impl Iterator<Item = &'a Condition>,
input: &Conditions,
rng: &mut impl Rng,
) -> bool {
conditions.all(|condition| match condition {
Condition::MatchTool { predicate } => {
if let Some(item) = &predicate.item {
match &input.item {
... | satisfies_conditions | identifier_name |
memory_index.rs | -> (PolicyDecision, Box<dyn Policy>);
}
/// Placeholder Policy that keeps everything.
struct KeepPolicy;
impl KeepPolicy {
fn new() -> KeepPolicy {
KeepPolicy
}
}
impl Policy for KeepPolicy {
fn handle(&mut self, property: &str, object: Object)
-> (PolicyDecision, Box<dyn ... | /// Directory where objects are stored on disk.
path: PathBuf,
/// All objects, indexed by their ID.
objects: HashMap<ID, Object>,
/// Back references: value is all references pointing to the key.
backlinks: HashMap<ID, HashSet<(Backkey, ID)>>,
/// All claim objects, whether they are valid f... | multimap.insert(key.clone(), set);
}
/// The in-memory index, that loads all objects from the disk on startup.
pub struct MemoryIndex { | random_line_split |
memory_index.rs | -> (PolicyDecision, Box<dyn Policy>);
}
/// Placeholder Policy that keeps everything.
struct KeepPolicy;
impl KeepPolicy {
fn new() -> KeepPolicy {
KeepPolicy
}
}
impl Policy for KeepPolicy {
fn handle(&mut self, property: &str, object: Object)
-> (PolicyDecision, Box<dyn P... | <K: Clone + Eq + ::std::hash::Hash,
V: Eq + ::std::hash::Hash>(
multimap: &mut HashMap<K, HashSet<V>>,
key: &K,
value: V)
{
if let Some(set) = multimap.get_mut(key) {
set.insert(value);
return;
}
let mut set = HashSet::new();
set.insert(value);
mul... | insert_into_multimap | identifier_name |
memory_index.rs | -> (PolicyDecision, Box<dyn Policy>);
}
/// Placeholder Policy that keeps everything.
struct KeepPolicy;
impl KeepPolicy {
fn new() -> KeepPolicy {
KeepPolicy
}
}
impl Policy for KeepPolicy {
fn handle(&mut self, property: &str, object: Object)
-> (PolicyDecision, Box<dyn P... |
}
}
}
}
fn insert_into_multimap<K: Clone + Eq + ::std::hash::Hash,
V: Eq + ::std::hash::Hash>(
multimap: &mut HashMap<K, HashSet<V>>,
key: &K,
value: V)
{
if let Some(set) = multimap.get_mut(key) {
set.insert(value);
return;
}
let... | {
let mut map = BTreeMap::new();
swap(&mut self.claims, &mut map);
let mut map = map.into_iter();
let (k, v) = match self.sort {
Sort::Ascending(_) => map.next_back().unwrap(),
Sort::Descendin... | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.