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 |
|---|---|---|---|---|
count_fast.rs | use crate::word_count::WordCount;
use super::WordCountable;
#[cfg(any(target_os = "linux", target_os = "android"))]
use std::fs::OpenOptions;
use std::io::{self, ErrorKind, Read};
#[cfg(unix)]
use libc::S_IFREG;
#[cfg(unix)]
use nix::sys::stat;
#[cfg(any(target_os = "linux", target_os = "android"))]
use std::os::uni... | Ok(res) => {
byte_count += res;
// Silent the warning as we want to the error message
#[allow(clippy::question_mark)]
if splice_exact(&pipe_rd, &null_file, res).is_err() {
return Err(byte_count);
}
... | loop {
match splice(fd, &pipe_wr, SPLICE_SIZE) {
Ok(0) => break, | random_line_split |
custom_build.rs | use std::collections::HashMap;
use std::fs::{self, File};
use std::io::prelude::*;
use std::path::PathBuf;
use std::str;
use std::sync::Mutex;
use core::{Package, Target, PackageId, PackageSet, Profile};
use util::{CargoResult, human, Human};
use util::{internal, ChainError, profile};
use super::job::Work;
use super:... | }
}
}
impl BuildOutput {
// Parses the output of a script.
// The `pkg_name` is used for error messages.
pub fn parse(input: &str, pkg_name: &str) -> CargoResult<BuildOutput> {
let mut library_paths = Vec::new();
let mut library_links = Vec::new();
let mut cfgs = Vec::ne... | outputs.insert((id, Kind::Target), output);
} | random_line_split |
custom_build.rs | use std::collections::HashMap;
use std::fs::{self, File};
use std::io::prelude::*;
use std::path::PathBuf;
use std::str;
use std::sync::Mutex;
use core::{Package, Target, PackageId, PackageSet, Profile};
use util::{CargoResult, human, Human};
use util::{internal, ChainError, profile};
use super::job::Work;
use super:... | (input: &str, pkg_name: &str) -> CargoResult<BuildOutput> {
let mut library_paths = Vec::new();
let mut library_links = Vec::new();
let mut cfgs = Vec::new();
let mut metadata = Vec::new();
let whence = format!("build script of `{}`", pkg_name);
for line in input.lines()... | parse | identifier_name |
custom_build.rs | use std::collections::HashMap;
use std::fs::{self, File};
use std::io::prelude::*;
use std::path::PathBuf;
use std::str;
use std::sync::Mutex;
use core::{Package, Target, PackageId, PackageSet, Profile};
use util::{CargoResult, human, Human};
use util::{internal, ChainError, profile};
use super::job::Work;
use super:... | };
match flag {
"-l" => library_links.push(value.to_string()),
"-L" => library_paths.push(PathBuf::from(value)),
// was already checked above
_ => return Err(human("only -l and -L flags are allowed"))
};
}
... | {
let value = value.trim();
let mut flags_iter = value.split(|c: char| c.is_whitespace())
.filter(|w| w.chars().any(|c| !c.is_whitespace()));
let (mut library_links, mut library_paths) = (Vec::new(), Vec::new());
loop {
let flag = match flags... | identifier_body |
custom_build.rs | use std::collections::HashMap;
use std::fs::{self, File};
use std::io::prelude::*;
use std::path::PathBuf;
use std::str;
use std::sync::Mutex;
use core::{Package, Target, PackageId, PackageSet, Profile};
use util::{CargoResult, human, Human};
use util::{internal, ChainError, profile};
use super::job::Work;
use super:... |
// This loop is both the recursive and additive portion of this
// function, the key part of the logic being around determining the
// right `kind` to recurse on. If a dependency fits in the kind that
// we've got specified, then we just keep plazing a trail, but otherwise
// w... | {
return &out[&(id, target, profile, kind)]
} | conditional_block |
minmax.rs | /// `MinMaxResult` is an enum returned by `minmax`.
///
/// See [`.minmax()`](crate::Itertools::minmax) for more detail.
#[derive(Copy, Clone, PartialEq, Debug)]
pub enum MinMaxResult<T> {
/// Empty iterator
NoElements,
/// Iterator with one element, so the minimum and maximum are the same
OneElement(T... | None => return MinMaxResult::OneElement(x),
Some(y) => {
let xk = key_for(&x);
let yk = key_for(&y);
if!lt(&y, &x, &yk, &xk) {(x, y, xk, yk)} else {(y, x, yk, xk)}
}
}
}
};
loop {
... | match it.next() { | random_line_split |
minmax.rs |
/// `MinMaxResult` is an enum returned by `minmax`.
///
/// See [`.minmax()`](crate::Itertools::minmax) for more detail.
#[derive(Copy, Clone, PartialEq, Debug)]
pub enum MinMaxResult<T> {
/// Empty iterator
NoElements,
/// Iterator with one element, so the minimum and maximum are the same
OneElement(... |
}
/// Implementation guts for `minmax` and `minmax_by_key`.
pub fn minmax_impl<I, K, F, L>(mut it: I, mut key_for: F,
mut lt: L) -> MinMaxResult<I::Item>
where I: Iterator,
F: FnMut(&I::Item) -> K,
L: FnMut(&I::Item, &I::Item, &K, &K) -> bool,
{
let (mut min,... | {
match self {
MinMaxResult::NoElements => None,
MinMaxResult::OneElement(x) => Some((x.clone(), x)),
MinMaxResult::MinMax(x, y) => Some((x, y))
}
} | identifier_body |
minmax.rs |
/// `MinMaxResult` is an enum returned by `minmax`.
///
/// See [`.minmax()`](crate::Itertools::minmax) for more detail.
#[derive(Copy, Clone, PartialEq, Debug)]
pub enum MinMaxResult<T> {
/// Empty iterator
NoElements,
/// Iterator with one element, so the minimum and maximum are the same
OneElement(... | else if!lt(&first, &max, &first_key, &max_key) {
max = first;
}
break;
}
Some(x) => x
};
let first_key = key_for(&first);
let second_key = key_for(&second);
if!lt(&second, &first, &second_key, &first_key) {
... | {
min = first;
} | conditional_block |
minmax.rs |
/// `MinMaxResult` is an enum returned by `minmax`.
///
/// See [`.minmax()`](crate::Itertools::minmax) for more detail.
#[derive(Copy, Clone, PartialEq, Debug)]
pub enum MinMaxResult<T> {
/// Empty iterator
NoElements,
/// Iterator with one element, so the minimum and maximum are the same
OneElement(... | <I, K, F, L>(mut it: I, mut key_for: F,
mut lt: L) -> MinMaxResult<I::Item>
where I: Iterator,
F: FnMut(&I::Item) -> K,
L: FnMut(&I::Item, &I::Item, &K, &K) -> bool,
{
let (mut min, mut max, mut min_key, mut max_key) = match it.next() {
None => return M... | minmax_impl | identifier_name |
datastore.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::io::Cursor;
use std::io::Write;
use anyhow::format_err;
use anyhow::Result;
use byteorder::BigEndian;
use byteorder::ReadBytesExt... | buf[pos] = value as u8;
value >>= 8;
}
assert!(value == 0 && pos == 0);
writer.write_all(&buf[0..len])?;
Ok(())
}
/// Converts a buffer to an integer using a special format used in the datapack format.
fn bin_to_u64(buf: &[u8]) -> u64 {
let mut n: u64 = 0;
for byte in buf.iter(... | let mut buf = [0; 8];
let len = u64_to_bin_len(value) as usize;
let mut pos = len;
while value > 0 {
pos -= 1; | random_line_split |
datastore.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::io::Cursor;
use std::io::Write;
use anyhow::format_err;
use anyhow::Result;
use byteorder::BigEndian;
use byteorder::ReadBytesExt... | (value: u64) -> u16 {
let mut value = value;
let mut count = 0;
while value > 0 {
count += 1;
value >>= 8;
}
count
}
/// Converts an integer into a buffer using a special format used in the datapack format.
fn u64_to_bin<T: Write>(value: u64, writer: &mut T) -> Result<()> {
let ... | u64_to_bin_len | identifier_name |
datastore.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::io::Cursor;
use std::io::Write;
use anyhow::format_err;
use anyhow::Result;
use byteorder::BigEndian;
use byteorder::ReadBytesExt... |
}
if let Some(size) = self.size {
Metadata::write_meta(b's', size, &mut buf)?;
}
writer.write_u32::<BigEndian>(buf.len() as u32)?;
writer.write_all(buf.as_ref())?;
Ok(())
}
fn write_meta<T: Write>(flag: u8, value: u64, writer: &mut T) -> Result<()> ... | {
Metadata::write_meta(b'f', flags, &mut buf)?;
} | conditional_block |
datastore.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::io::Cursor;
use std::io::Write;
use anyhow::format_err;
use anyhow::Result;
use byteorder::BigEndian;
use byteorder::ReadBytesExt... |
fn write_meta<T: Write>(flag: u8, value: u64, writer: &mut T) -> Result<()> {
writer.write_u8(flag as u8)?;
writer.write_u16::<BigEndian>(u64_to_bin_len(value))?;
u64_to_bin(value, writer)?;
Ok(())
}
pub fn read(cur: &mut Cursor<&[u8]>) -> Result<Metadata> {
let me... | {
let mut buf = vec![];
if let Some(flags) = self.flags {
if flags != 0 {
Metadata::write_meta(b'f', flags, &mut buf)?;
}
}
if let Some(size) = self.size {
Metadata::write_meta(b's', size, &mut buf)?;
}
writer.write_u32... | identifier_body |
cartesian_rectangle.rs | use crate::geometry::Point;
pub struct | {
center: Point,
width: f64,
height: f64
}
impl CartesianRectangle {
pub fn new(center: Point, width: f64, height: f64) -> Self {
Self {
center,
width,
height
}
}
pub fn x_bounds(&self) -> Point {
Point::new(self.center.x - self.widt... | CartesianRectangle | identifier_name |
cartesian_rectangle.rs | use crate::geometry::Point;
pub struct CartesianRectangle {
center: Point,
width: f64,
height: f64
}
impl CartesianRectangle {
pub fn new(center: Point, width: f64, height: f64) -> Self {
Self {
center,
width,
height
}
}
pub fn x_bounds(&sel... | && point.y > y_bounds.x
}
} |
point.x < x_bounds.y
&& point.x > x_bounds.x
&& point.y < y_bounds.y | random_line_split |
cartesian_rectangle.rs | use crate::geometry::Point;
pub struct CartesianRectangle {
center: Point,
width: f64,
height: f64
}
impl CartesianRectangle {
pub fn new(center: Point, width: f64, height: f64) -> Self {
Self {
center,
width,
height
}
}
pub fn x_bounds(&sel... |
}
| {
let x_bounds = self.x_bounds();
let y_bounds = self.y_bounds();
point.x < x_bounds.y
&& point.x > x_bounds.x
&& point.y < y_bounds.y
&& point.y > y_bounds.x
} | identifier_body |
cursor.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! A list of common mouse cursors per CSS3-UI § 8.1.1.
use super::{CssWriter, ToCss};
macro_rules! define_curso... | "s-resize" => SResize = 22,
"se-resize" => SeResize = 23,
"sw-resize" => SwResize = 24,
"w-resize" => WResize = 25,
"ew-resize" => EwResize = 26,
"ns-resize" => NsResize = 27,
"nesw-resize" => NeswResize = 28,
"nwse-resize" => NwseResize = 29,
"col... | "e-resize" => EResize = 18,
"n-resize" => NResize = 19,
"ne-resize" => NeResize = 20,
"nw-resize" => NwResize = 21, | random_line_split |
method-self-arg-trait.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn foo2(self) {
unsafe { COUNT *= 3; }
}
fn foo3(self: Box<Foo>) {
unsafe { COUNT *= 5; }
}
}
impl Foo {
fn baz(self) {
unsafe { COUNT *= 17; }
// Test internal call.
Bar::foo1(&self);
Bar::foo2(self);
Bar::foo3(box self);
Bar::bar... | {
unsafe { COUNT *= 2; }
} | identifier_body |
method-self-arg-trait.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | unsafe { COUNT *= 3; }
}
fn foo3(self: Box<Foo>) {
unsafe { COUNT *= 5; }
}
}
impl Foo {
fn baz(self) {
unsafe { COUNT *= 17; }
// Test internal call.
Bar::foo1(&self);
Bar::foo2(self);
Bar::foo3(box self);
Bar::bar1(&self);
Bar:... | }
fn foo2(self) { | random_line_split |
method-self-arg-trait.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (self) {
unsafe { COUNT *= 3; }
}
fn foo3(self: Box<Foo>) {
unsafe { COUNT *= 5; }
}
}
impl Foo {
fn baz(self) {
unsafe { COUNT *= 17; }
// Test internal call.
Bar::foo1(&self);
Bar::foo2(self);
Bar::foo3(box self);
Bar::bar1(&self);
... | foo2 | identifier_name |
tag-variant-disr-dup.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | red = 0xff0000,
green = 0x00ff00,
blue = 0x0000ff,
black = 0x000000,
white = 0x000000,
} | enum color { | random_line_split |
tag-variant-disr-dup.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
red = 0xff0000,
green = 0x00ff00,
blue = 0x0000ff,
black = 0x000000,
white = 0x000000,
}
| color | identifier_name |
iter.rs | /*
* iter.rs: Iterator implementation for rbtree.
* Copyright (C) 2019 Oddcoder
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your optio... | else {
return None;
}
if let Some(node) = self.right.pop() {
self.add_subtree(node);
}
result
}
}
| {
result = Some((node.key(), node.aug_data(), node.data()));
} | conditional_block |
iter.rs | /*
* iter.rs: Iterator implementation for rbtree.
* Copyright (C) 2019 Oddcoder
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your optio... |
}
| {
let result;
if let Some(node) = self.current.take() {
result = Some((node.key(), node.aug_data(), node.data()));
} else {
return None;
}
if let Some(node) = self.right.pop() {
self.add_subtree(node);
}
result
} | identifier_body |
iter.rs | /*
* iter.rs: Iterator implementation for rbtree.
* Copyright (C) 2019 Oddcoder
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your optio... | (&mut self, root: RBTree<K, A, V>) {
let mut node: RBTree<K, A, V> = root;
while node.is_node() {
if node.right_ref().is_node() {
self.right.push(node.right());
}
if node.left_ref().is_node() {
let tmp = node.left();
sel... | add_subtree | identifier_name |
iter.rs | /*
* iter.rs: Iterator implementation for rbtree.
* Copyright (C) 2019 Oddcoder
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your optio... | return None;
}
if let Some(node) = self.right.pop() {
self.add_subtree(node);
}
result
}
} | let result;
if let Some(node) = self.current.take() {
result = Some((node.key(), node.aug_data(), node.data()));
} else { | random_line_split |
interface.rs | use std::io::{self, Write, BufWriter};
use super::{MatchWithPositions, match_and_score_with_positions};
use ansi::{clear, color, cursor, style};
use terminal::{self, Terminal, Key, Event};
use rayon::prelude::*;
#[derive(Debug)]
pub enum Error {
Exit,
Write(io::Error),
Reset(terminal::Error)
}
impl From... |
}
| {
self.matches.iter().
nth(self.selected).
map(|choice| choice.0).
unwrap_or(&self.search)
} | identifier_body |
interface.rs | use std::io::{self, Write, BufWriter};
use super::{MatchWithPositions, match_and_score_with_positions};
use ansi::{clear, color, cursor, style};
use terminal::{self, Terminal, Key, Event};
use rayon::prelude::*;
#[derive(Debug)]
pub enum Error {
Exit,
Write(io::Error),
Reset(terminal::Error)
}
impl From... | (&mut self) {
let ref search = self.search;
self.matches = self.lines.
par_iter().
filter_map(|line| match_and_score_with_positions(search, line)).
collect();
self.matches.par_sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap().reverse());
}
// Matches an... | filter_matches | identifier_name |
interface.rs | use std::io::{self, Write, BufWriter};
use super::{MatchWithPositions, match_and_score_with_positions};
use ansi::{clear, color, cursor, style};
use terminal::{self, Terminal, Key, Event};
use rayon::prelude::*;
#[derive(Debug)]
pub enum Error {
Exit,
Write(io::Error),
Reset(terminal::Error)
}
impl From... | self.render()?;
},
Key::Backspace | Key::Ctrl('h') => {
self.search.pop();
self.filter_matches();
self.render()?;
}
Key::Ctrl('u') => {
... | random_line_split | |
interface.rs | use std::io::{self, Write, BufWriter};
use super::{MatchWithPositions, match_and_score_with_positions};
use ansi::{clear, color, cursor, style};
use terminal::{self, Terminal, Key, Event};
use rayon::prelude::*;
#[derive(Debug)]
pub enum Error {
Exit,
Write(io::Error),
Reset(terminal::Error)
}
impl From... | ,
Key::Ctrl('n') => {
self.selected += 1;
self.render()?;
},
Key::Ctrl('p') => {
self.selected = self.selected.saturating_sub(1);
self.render()?;
... | {
break;
} | conditional_block |
sample_index.rs | use std::{
cmp::Ordering,
error::Error,
fmt,
ops::{Add, AddAssign, Sub},
};
use metadata::Duration;
use super::{SampleIndexRange, Timestamp};
#[derive(Debug)]
pub struct DecrementError;
impl fmt::Display for DecrementError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
... | (self, rhs: SampleIndexRange) -> SampleIndex {
SampleIndex(self.0 + rhs.as_usize())
}
}
impl AddAssign<SampleIndexRange> for SampleIndex {
#[track_caller]
fn add_assign(&mut self, rhs: SampleIndexRange) {
*self = SampleIndex(self.0 + rhs.as_usize());
}
}
impl Sub<SampleIndexRange> for ... | add | identifier_name |
sample_index.rs | use std::{
cmp::Ordering,
error::Error,
fmt,
ops::{Add, AddAssign, Sub},
};
use metadata::Duration;
use super::{SampleIndexRange, Timestamp};
#[derive(Debug)]
pub struct DecrementError;
impl fmt::Display for DecrementError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
... | #[track_caller]
fn add_assign(&mut self, rhs: SampleIndexRange) {
*self = SampleIndex(self.0 + rhs.as_usize());
}
}
impl Sub<SampleIndexRange> for SampleIndex {
type Output = SampleIndex;
#[track_caller]
fn sub(self, rhs: SampleIndexRange) -> SampleIndex {
SampleIndex(self.0 - ... | impl AddAssign<SampleIndexRange> for SampleIndex { | random_line_split |
sample_index.rs | use std::{
cmp::Ordering,
error::Error,
fmt,
ops::{Add, AddAssign, Sub},
};
use metadata::Duration;
use super::{SampleIndexRange, Timestamp};
#[derive(Debug)]
pub struct DecrementError;
impl fmt::Display for DecrementError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
... |
}
impl Sub for SampleIndex {
type Output = SampleIndexRange;
#[track_caller]
fn sub(self, rhs: SampleIndex) -> SampleIndexRange {
SampleIndexRange::new(self.0 - rhs.0)
}
}
impl Add<SampleIndexRange> for SampleIndex {
type Output = SampleIndex;
#[track_caller]
fn add(self, rhs: S... | {
Self(range.as_usize())
} | identifier_body |
sample_index.rs | use std::{
cmp::Ordering,
error::Error,
fmt,
ops::{Add, AddAssign, Sub},
};
use metadata::Duration;
use super::{SampleIndexRange, Timestamp};
#[derive(Debug)]
pub struct DecrementError;
impl fmt::Display for DecrementError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
... |
}
pub fn inc(&mut self) {
*self = SampleIndex(self.0 + 1);
}
#[must_use = "this returns the result of the operation, without modifying the original"]
pub fn checked_sub(self, rhs: Self) -> Option<SampleIndexRange> {
self.0.checked_sub(rhs.0).map(SampleIndexRange::new)
}
#... | {
Err(DecrementError)
} | conditional_block |
lib.rs | // ams - Advanced Memory Scanner
// Copyright (C) 2018 th0rex
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any ... |
self.write_index.compare_and_swap(
current_write_index,
current_write_index + 1,
Ordering::SeqCst,
)!= current_write_index
} {}
unsafe {
let slice = &mut **self.data.get();
slice[self.count_to_index(curren... | {
return false;
} | conditional_block |
lib.rs | // ams - Advanced Memory Scanner
// Copyright (C) 2018 th0rex
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any ... | impl<T: Clone + Default> Queue<T> {
pub fn new(size: usize) -> Queue<T> {
Queue {
size,
count: AtomicUsize::new(0),
write_index: AtomicUsize::new(0),
read_index: AtomicUsize::new(0),
max_read_index: AtomicUsize::new(0),
data: UnsafeCell... | read_index: AtomicUsize,
max_read_index: AtomicUsize,
data: UnsafeCell<Box<[T]>>,
}
| random_line_split |
lib.rs | // ams - Advanced Memory Scanner
// Copyright (C) 2018 th0rex
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any ... | <T> {
size: usize,
count: AtomicUsize,
write_index: AtomicUsize,
read_index: AtomicUsize,
max_read_index: AtomicUsize,
data: UnsafeCell<Box<[T]>>,
}
impl<T: Clone + Default> Queue<T> {
pub fn new(size: usize) -> Queue<T> {
Queue {
size,
count: AtomicUsize::ne... | Queue | identifier_name |
lib.rs | // ams - Advanced Memory Scanner
// Copyright (C) 2018 th0rex
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any ... |
}
unsafe impl<T> Sync for Queue<T> {}
| {
to % self.size
} | identifier_body |
config.rs | extern crate toml;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
#[derive(Deserialize)]
pub struct | {
pub inoreader_appkey: String,
pub inoreader_appid: String,
pub inoreader_token: String,
pub inoreader_endpoint: String,
telegram_token: String,
telegram_endpoint: String,
pub db_path: String,
pub timeout: u64,
}
impl Config {
pub fn new(path: &str) -> Config {
let file_na... | Config | identifier_name |
config.rs | extern crate toml;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
#[derive(Deserialize)]
pub struct Config {
pub inoreader_appkey: String, | pub db_path: String,
pub timeout: u64,
}
impl Config {
pub fn new(path: &str) -> Config {
let file_name = Path::new(path);
let mut file = File::open(&file_name).unwrap();
let mut content = String::new();
//читаем содержимое файла, если ошибка паникуем
file.read_to... | pub inoreader_appid: String,
pub inoreader_token: String,
pub inoreader_endpoint: String,
telegram_token: String,
telegram_endpoint: String, | random_line_split |
config.rs | extern crate toml;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
#[derive(Deserialize)]
pub struct Config {
pub inoreader_appkey: String,
pub inoreader_appid: String,
pub inoreader_token: String,
pub inoreader_endpoint: String,
telegram_token: String,
telegram_endpoint: Stri... | = self.telegram_endpoint.to_owned();
let bot_ep = format!("/bot{}", &self.telegram_token);
main_ep.push_str(&bot_ep);
main_ep
}
} | {
let file_name = Path::new(path);
let mut file = File::open(&file_name).unwrap();
let mut content = String::new();
//читаем содержимое файла, если ошибка паникуем
file.read_to_string(&mut content).unwrap();
// производим маппинг настроек из файла в стуруктуру
... | identifier_body |
tensor.rs | use std::ffi::CString;
use std::fmt;
use std::ptr::{self, NonNull};
use dynet_sys;
use super::{ApiResult, Dim, Result, Wrap};
/// A struct to represent a tensor.
///
/// # Examples
///
/// ```
/// # use dynet::{DynetParams, ParameterCollection, ParameterInitGlorot};
/// dynet::initialize(&mut DynetParams::from_args(... |
}
| {
unsafe {
let mut size: usize = 0;
check_api_status!(dynet_sys::dynetRepresentTensorAsString(
self.as_ptr(),
ptr::null_mut(),
&mut size,
));
let buffer = CString::new(vec![b'0'; size]).unwrap().into_raw();
... | identifier_body |
tensor.rs | use std::ffi::CString;
use std::fmt;
use std::ptr::{self, NonNull};
use dynet_sys;
use super::{ApiResult, Dim, Result, Wrap};
/// A struct to represent a tensor.
///
/// # Examples
///
/// ```
/// # use dynet::{DynetParams, ParameterCollection, ParameterInitGlorot};
/// dynet::initialize(&mut DynetParams::from_args(... | (&self) -> Dim {
unsafe {
let mut dim_ptr: *mut dynet_sys::dynetDim_t = ptr::null_mut();
check_api_status!(dynet_sys::dynetGetTensorDim(self.as_ptr(), &mut dim_ptr));
Dim::from_raw(dim_ptr, true)
}
}
/// Retrieves one internal value in the tensor.
///
... | dim | identifier_name |
tensor.rs | use std::ffi::CString;
use std::fmt;
use std::ptr::{self, NonNull};
use dynet_sys;
use super::{ApiResult, Dim, Result, Wrap};
/// A struct to represent a tensor.
///
/// # Examples
///
/// ```
/// # use dynet::{DynetParams, ParameterCollection, ParameterInitGlorot};
/// dynet::initialize(&mut DynetParams::from_args(... | }
}
}
impl fmt::Display for Tensor {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
unsafe {
let mut size: usize = 0;
check_api_status!(dynet_sys::dynetRepresentTensorAsString(
self.as_ptr(),
ptr::null_mut(),
&mut s... | self.as_ptr(),
retval.as_mut_ptr(),
&mut size,
));
retval | random_line_split |
mod.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... | mod bloom;
mod block;
mod complete;
mod fork;
pub mod generator;
pub use self::complete::BlockFinalizer;
pub use self::generator::{ChainGenerator, ChainIterator}; | // GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
| random_line_split |
send-is-not-static-par-for.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn sum(x: &[i32]) {
let sum_lengths = Mutex::new(0);
par_for(x.windows(4), |x| {
*sum_lengths.lock().unwrap() += x.len()
});
assert_eq!(*sum_lengths.lock().unwrap(), (x.len() - 3) * 4);
}
fn main() {
let mut elements = [0; 20];
// iterators over references into this stack frame
... | {
for item in iter {
f(item)
}
} | identifier_body |
send-is-not-static-par-for.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | fn sum(x: &[i32]) {
let sum_lengths = Mutex::new(0);
par_for(x.windows(4), |x| {
*sum_lengths.lock().unwrap() += x.len()
});
assert_eq!(*sum_lengths.lock().unwrap(), (x.len() - 3) * 4);
}
fn main() {
let mut elements = [0; 20];
// iterators over references into this stack frame
pa... | }
}
| random_line_split |
send-is-not-static-par-for.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (x: &[i32]) {
let sum_lengths = Mutex::new(0);
par_for(x.windows(4), |x| {
*sum_lengths.lock().unwrap() += x.len()
});
assert_eq!(*sum_lengths.lock().unwrap(), (x.len() - 3) * 4);
}
fn main() {
let mut elements = [0; 20];
// iterators over references into this stack frame
par_for(... | sum | identifier_name |
x86.rs | use std::any::{Any, TypeId};
use std::mem;
use runtime::{Object, Imp, Sel};
use super::Super;
pub fn msg_send_fn<R: Any>(obj: *mut Object, _: Sel) -> (Imp, *mut Object) {
// Structures 1 or 2 bytes in size are placed in EAX.
// Structures 4 or 8 bytes in size are placed in: EAX and EDX.
// Structures of o... | else {
objc_msgSendSuper_stret
};
(msg_fn, sup as *const Super as *mut Object)
}
| {
objc_msgSendSuper
} | conditional_block |
x86.rs | use std::any::{Any, TypeId};
use std::mem;
use runtime::{Object, Imp, Sel};
use super::Super;
pub fn msg_send_fn<R: Any>(obj: *mut Object, _: Sel) -> (Imp, *mut Object) {
// Structures 1 or 2 bytes in size are placed in EAX.
// Structures 4 or 8 bytes in size are placed in: EAX and EDX.
// Structures of o... | <R: Any>(sup: &Super, _: Sel) -> (Imp, *mut Object) {
extern {
fn objc_msgSendSuper();
fn objc_msgSendSuper_stret();
}
let size = mem::size_of::<R>();
let msg_fn = if size == 0 || size == 1 || size == 2 || size == 4 || size == 8 {
objc_msgSendSuper
} else {
objc_msgS... | msg_send_super_fn | identifier_name |
x86.rs | use std::any::{Any, TypeId};
use std::mem;
use runtime::{Object, Imp, Sel};
use super::Super;
pub fn msg_send_fn<R: Any>(obj: *mut Object, _: Sel) -> (Imp, *mut Object) {
// Structures 1 or 2 bytes in size are placed in EAX.
// Structures 4 or 8 bytes in size are placed in: EAX and EDX.
// Structures of o... | } | random_line_split | |
x86.rs | use std::any::{Any, TypeId};
use std::mem;
use runtime::{Object, Imp, Sel};
use super::Super;
pub fn msg_send_fn<R: Any>(obj: *mut Object, _: Sel) -> (Imp, *mut Object) | objc_msgSend_stret
};
(msg_fn, obj)
}
pub fn msg_send_super_fn<R: Any>(sup: &Super, _: Sel) -> (Imp, *mut Object) {
extern {
fn objc_msgSendSuper();
fn objc_msgSendSuper_stret();
}
let size = mem::size_of::<R>();
let msg_fn = if size == 0 || size == 1 || size == 2 || ... | {
// Structures 1 or 2 bytes in size are placed in EAX.
// Structures 4 or 8 bytes in size are placed in: EAX and EDX.
// Structures of other sizes are placed at the address supplied by the caller.
// https://developer.apple.com/library/mac/documentation/DeveloperTools/Conceptual/LowLevelABI/130-IA-32_F... | identifier_body |
cmp.rs | //! Comparison traits for `[T]`.
use crate::cmp;
use crate::cmp::Ordering::{self, Greater, Less};
use crate::mem;
use super::from_raw_parts;
use super::memchr;
extern "C" {
/// Calls implementation provided memcmp.
///
/// Interprets the data as u8.
///
/// Returns 0 for equal, < 0 for less than ... |
}
// Generic slice equality
impl<A, B> SlicePartialEq<B> for [A]
where
A: PartialEq<B>,
{
default fn equal(&self, other: &[B]) -> bool {
if self.len()!= other.len() {
return false;
}
self.iter().zip(other.iter()).all(|(x, y)| x == y)
}
}
// Use memcmp for bytewise equ... | {
!self.equal(other)
} | identifier_body |
cmp.rs | //! Comparison traits for `[T]`.
use crate::cmp;
use crate::cmp::Ordering::{self, Greater, Less};
use crate::mem;
use super::from_raw_parts;
use super::memchr;
extern "C" {
/// Calls implementation provided memcmp.
///
/// Interprets the data as u8.
///
/// Returns 0 for equal, < 0 for less than ... | left.len().partial_cmp(&right.len())
}
}
// This is the impl that we would like to have. Unfortunately it's not sound.
// See `partial_ord_slice.rs`.
/*
impl<A> SlicePartialOrd for A
where
A: Ord,
{
default fn partial_compare(left: &[A], right: &[A]) -> Option<Ordering> {
Some(SliceOrd::com... | Some(Ordering::Equal) => (),
non_eq => return non_eq,
}
}
| random_line_split |
cmp.rs | //! Comparison traits for `[T]`.
use crate::cmp;
use crate::cmp::Ordering::{self, Greater, Less};
use crate::mem;
use super::from_raw_parts;
use super::memchr;
extern "C" {
/// Calls implementation provided memcmp.
///
/// Interprets the data as u8.
///
/// Returns 0 for equal, < 0 for less than ... | (&self, other: &[B]) -> bool {
if self.len()!= other.len() {
return false;
}
self.iter().zip(other.iter()).all(|(x, y)| x == y)
}
}
// Use memcmp for bytewise equality when the types allow
impl<A, B> SlicePartialEq<B> for [A]
where
A: BytewiseEquality<B>,
{
fn equal(&se... | equal | identifier_name |
sequential.rs | // Copyright 2015 The tiny-http Contributors
//
// 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... | type Item = SequentialReader<R>;
fn next(&mut self) -> Option<SequentialReader<R>> {
let (tx, rx) = channel();
let inner = mem::replace(&mut self.inner, SequentialReaderBuilderInner::NotFirst(rx));
match inner {
SequentialReaderBuilderInner::First(reader) => {
... | impl<R: Read + Send> Iterator for SequentialReaderBuilder<R> { | random_line_split |
sequential.rs | // Copyright 2015 The tiny-http Contributors
//
// 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... |
}
impl<W: Write + Send> SequentialWriterBuilder<W> {
pub fn new(writer: W) -> SequentialWriterBuilder<W> {
SequentialWriterBuilder {
writer: Arc::new(Mutex::new(writer)),
next_trigger: None,
}
}
}
impl<R: Read + Send> Iterator for SequentialReaderBuilder<R> {
type ... | {
SequentialReaderBuilder {
inner: SequentialReaderBuilderInner::First(reader),
}
} | identifier_body |
sequential.rs | // Copyright 2015 The tiny-http Contributors
//
// 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... | (reader: R) -> SequentialReaderBuilder<R> {
SequentialReaderBuilder {
inner: SequentialReaderBuilderInner::First(reader),
}
}
}
impl<W: Write + Send> SequentialWriterBuilder<W> {
pub fn new(writer: W) -> SequentialWriterBuilder<W> {
SequentialWriterBuilder {
writ... | new | identifier_name |
buffer.rs | use std::ops;
use std::sync::Arc;
#[derive(Debug, Clone)]
pub struct Buffer {
pub uri: Option<String>,
pub name: Option<String>,
data: Vec<u8>
}
impl Buffer {
pub fn new(uri: Option<String>, name: Option<String>, data: Vec<u8>) -> Arc<Buffer> {
return Arc::new(Buffer { uri: uri, name: name, data: data }... | #[test]
fn test_as_slice() {
let buffer = Buffer::new(None, None, vec![0, 1, 2, 3]);
assert_eq!(buffer.as_slice(), &[0, 1, 2, 3]);
}
#[test]
fn test_deref() {
let buffer = Buffer::new(None, None, vec![0, 1, 2, 3]);
assert_eq!(&**buffer, &[0, 1, 2, 3]);
}
#[test]
fn test_index() {
... |
#[cfg(test)]
mod tests {
use super::*;
| random_line_split |
buffer.rs | use std::ops;
use std::sync::Arc;
#[derive(Debug, Clone)]
pub struct Buffer {
pub uri: Option<String>,
pub name: Option<String>,
data: Vec<u8>
}
impl Buffer {
pub fn new(uri: Option<String>, name: Option<String>, data: Vec<u8>) -> Arc<Buffer> {
return Arc::new(Buffer { uri: uri, name: name, data: data }... | (&self) -> &[u8] {
return &self[..];
}
}
impl ops::Index<usize> for Buffer {
type Output = u8;
#[inline(always)]
fn index(&self, index: usize) -> &u8 {
return &self.data[index];
}
}
impl ops::Index<ops::Range<usize>> for Buffer {
type Output = [u8];
#[inline(always)]
fn index(&self, index: o... | as_slice | identifier_name |
buffer.rs | use std::ops;
use std::sync::Arc;
#[derive(Debug, Clone)]
pub struct Buffer {
pub uri: Option<String>,
pub name: Option<String>,
data: Vec<u8>
}
impl Buffer {
pub fn new(uri: Option<String>, name: Option<String>, data: Vec<u8>) -> Arc<Buffer> {
return Arc::new(Buffer { uri: uri, name: name, data: data }... |
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_as_slice() {
let buffer = Buffer::new(None, None, vec![0, 1, 2, 3]);
assert_eq!(buffer.as_slice(), &[0, 1, 2, 3]);
}
#[test]
fn test_deref() {
let buffer = Buffer::new(None, None, vec![0, 1, 2, 3]);
assert_eq!(&**buffer, &[0, 1, ... | {
return self.data.deref();
} | identifier_body |
lib.rs | #![warn(clippy::pedantic)]
#![allow(clippy::clippy::cast_possible_truncation)]
#![allow(clippy::inline_always)]
#![allow(clippy::cast_precision_loss)]
#![allow(clippy::shadow_unrelated)]
#![allow(clippy::module_name_repetitions)]
#![allow(clippy::missing_errors_doc)]
#![allow(clippy::cast_sign_loss)]
#![allow(clippy::m... | {
/// TV episodes.
Season,
Movie,
Special,
OVA,
ONA,
Music,
}
impl Into<&'static str> for SeriesKind {
fn into(self) -> &'static str {
match self {
Self::Season => "Season",
Self::Movie => "Movie",
Self::Special => "Special",
Self... | SeriesKind | identifier_name |
lib.rs | #![warn(clippy::pedantic)]
#![allow(clippy::clippy::cast_possible_truncation)]
#![allow(clippy::inline_always)]
#![allow(clippy::cast_precision_loss)]
#![allow(clippy::shadow_unrelated)]
#![allow(clippy::module_name_repetitions)]
#![allow(clippy::missing_errors_doc)]
#![allow(clippy::cast_sign_loss)]
#![allow(clippy::m... |
if max_score < min_confidence {
return None;
}
best_match
}
| {
let mut max_score = 0.0;
let mut best_match = None;
for (i, item) in items.into_iter().enumerate() {
let score = match matcher(&item) {
Some(score) => score,
None => continue,
};
if score > max_score {
best_match = Some((i, item));
... | identifier_body |
lib.rs | #![warn(clippy::pedantic)]
#![allow(clippy::clippy::cast_possible_truncation)]
#![allow(clippy::inline_always)]
#![allow(clippy::cast_precision_loss)]
#![allow(clippy::shadow_unrelated)]
#![allow(clippy::module_name_repetitions)]
#![allow(clippy::missing_errors_doc)]
#![allow(clippy::cast_sign_loss)]
#![allow(clippy::m... |
max_score = score;
}
}
if max_score < min_confidence {
return None;
}
best_match
} | } | random_line_split |
test_delete_stream.rs | extern crate serde;
extern crate serde_json;
extern crate uuid;
extern crate http_event_store as hes;
#[macro_use]
mod support;
use support::task_domain::*;
use hes::write::Event;
use hes::read::BodyEntry;
use hes::client::Client;
use hes::expected_version::ExpectedVersion;
use hes::error::ApiError::*;
| let stream_name = test_stream_name();
client.append_to_stream(&stream_name, ExpectedVersion::NoStream, events).unwrap();
assert!(client.read_stream_events_forward::<BodyEntry>(&stream_name, 0, 1, true).is_ok());
assert!(client.delete_stream(&stream_name, ExpectedVersion::Any).is_ok());
let result =... | #[test]
fn should_delete_stream() {
let events: Vec<Event> = vec![TaskCreated { name: "Created".to_string(), event_id: uuid::Uuid::new_v4() }.into()];
let client = Client::default(); | random_line_split |
test_delete_stream.rs | extern crate serde;
extern crate serde_json;
extern crate uuid;
extern crate http_event_store as hes;
#[macro_use]
mod support;
use support::task_domain::*;
use hes::write::Event;
use hes::read::BodyEntry;
use hes::client::Client;
use hes::expected_version::ExpectedVersion;
use hes::error::ApiError::*;
#[test]
fn | () {
let events: Vec<Event> = vec![TaskCreated { name: "Created".to_string(), event_id: uuid::Uuid::new_v4() }.into()];
let client = Client::default();
let stream_name = test_stream_name();
client.append_to_stream(&stream_name, ExpectedVersion::NoStream, events).unwrap();
assert!(client.read_strea... | should_delete_stream | identifier_name |
test_delete_stream.rs | extern crate serde;
extern crate serde_json;
extern crate uuid;
extern crate http_event_store as hes;
#[macro_use]
mod support;
use support::task_domain::*;
use hes::write::Event;
use hes::read::BodyEntry;
use hes::client::Client;
use hes::expected_version::ExpectedVersion;
use hes::error::ApiError::*;
#[test]
fn s... |
fn test_stream_name() -> String {
format!("task-{}", uuid::Uuid::new_v4().simple())
}
| {
let events: Vec<Event> = vec![TaskCreated { name: "Created".to_string(), event_id: uuid::Uuid::new_v4() }.into()];
let client = Client::default();
let stream_name = test_stream_name();
client.append_to_stream(&stream_name, ExpectedVersion::NoStream, events).unwrap();
let result = client.delete_s... | identifier_body |
constants.rs | use crate::{
analysis::imports::Imports,
codegen::general::{
self, cfg_condition, cfg_deprecated, doc_alias, version_condition, version_condition_string,
},
env::Env,
file_saver, library,
};
use std::path::Path;
pub fn | (env: &Env, root_path: &Path, mod_rs: &mut Vec<String>) {
let path = root_path.join("constants.rs");
let mut imports = Imports::new(&env.library);
if env.analysis.constants.is_empty() {
return;
}
let sys_crate_name = env.main_sys_crate_name();
imports.add("std::ffi::CStr");
file_s... | generate | identifier_name |
constants.rs | use crate::{
analysis::imports::Imports,
codegen::general::{
self, cfg_condition, cfg_deprecated, doc_alias, version_condition, version_condition_string,
},
env::Env,
file_saver, library,
};
use std::path::Path;
pub fn generate(env: &Env, root_path: &Path, mod_rs: &mut Vec<String>) | if let library::Type::Fundamental(library::Fundamental::Utf8) = type_ {
cfg_deprecated(w, env, None, constant.deprecated_version, false, 0)?;
cfg_condition(w, constant.cfg_condition.as_ref(), false, 0)?;
version_condition(w, env, None, constant.version, false,... | {
let path = root_path.join("constants.rs");
let mut imports = Imports::new(&env.library);
if env.analysis.constants.is_empty() {
return;
}
let sys_crate_name = env.main_sys_crate_name();
imports.add("std::ffi::CStr");
file_saver::save_to_file(path, env.config.make_backup, |w| {
... | identifier_body |
constants.rs | use crate::{
analysis::imports::Imports,
codegen::general::{
self, cfg_condition, cfg_deprecated, doc_alias, version_condition, version_condition_string,
},
env::Env,
file_saver, library,
};
use std::path::Path;
pub fn generate(env: &Env, root_path: &Path, mod_rs: &mut Vec<String>) {
le... |
if env.analysis.constants.is_empty() {
return;
}
let sys_crate_name = env.main_sys_crate_name();
imports.add("std::ffi::CStr");
file_saver::save_to_file(path, env.config.make_backup, |w| {
general::start_comments(w, &env.config)?;
general::uses(w, env, &imports, None)?;
... | let mut imports = Imports::new(&env.library); | random_line_split |
constants.rs | use crate::{
analysis::imports::Imports,
codegen::general::{
self, cfg_condition, cfg_deprecated, doc_alias, version_condition, version_condition_string,
},
env::Env,
file_saver, library,
};
use std::path::Path;
pub fn generate(env: &Env, root_path: &Path, mod_rs: &mut Vec<String>) {
le... |
mod_rs.push(format!("pub use self::constants::{};", constant.name));
}
}
Ok(())
});
}
| {
mod_rs.push(cfg);
} | conditional_block |
validation.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use crate::setcommon::{add_generations_by_bonsai, BonsaiInputStream};
use crate::BonsaiNodeStream;
use anyhow::Error;
use changeset_fetcher... | (fb: FacebookInit) {
let ctx = CoreContext::test_mock(fb);
let repo = Arc::new(linear::getrepo(fb).await);
let nodestream = single_changeset_id(
ctx.clone(),
string_to_bonsai(fb, &repo, "cb15ca4a43a59acff5388cea9648c162afde8372")
.await
.clo... | wrong_order_panics | identifier_name |
validation.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use crate::setcommon::{add_generations_by_bonsai, BonsaiInputStream};
use crate::BonsaiNodeStream;
use anyhow::Error;
use changeset_fetcher... |
self.last_generation = Some(gen);
Ok(Async::Ready(Some(hash)))
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::fixtures::linear;
use crate::setcommon::NotReadyEmptyStream;
use crate::tests::TestChangesetFetcher;
use fbinit::FacebookInit;
use futures::{compat::Stream01... | ); | random_line_split |
validation.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use crate::setcommon::{add_generations_by_bonsai, BonsaiInputStream};
use crate::BonsaiNodeStream;
use anyhow::Error;
use changeset_fetcher... | }
}
#[fbinit::test]
#[should_panic]
async fn wrong_order_panics(fb: FacebookInit) {
let ctx = CoreContext::test_mock(fb);
let repo = Arc::new(linear::getrepo(fb).await);
let nodestream = single_changeset_id(
ctx.clone(),
string_to_bonsai(fb, &re... | {
let ctx = CoreContext::test_mock(fb);
let repo = Arc::new(linear::getrepo(fb).await);
let head_csid =
string_to_bonsai(fb, &repo, "a5ffa77602a066db7d5cfb9fb5823a0895717c5a").await;
let nodestream = single_changeset_id(ctx.clone(), head_csid.clone(), &repo)
.cha... | identifier_body |
validation.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use crate::setcommon::{add_generations_by_bonsai, BonsaiInputStream};
use crate::BonsaiNodeStream;
use anyhow::Error;
use changeset_fetcher... |
}
}
}
}
| {} | conditional_block |
mod.rs | // SPDX-License-Identifier: Unlicense | //! debug console. Other devices are managed through user-level threads
//! and by receiving the relevant capabilities which allow them to access
//! the necessary system resources - chiefly physical memory and interrupts.
pub mod intc;
pub mod serial;
pub mod virtio;
use crate::archs::arch::Arch;
use crate::archs::D... |
//! A module for the kernel devices which must be used from the kernel.
//!
//! This is a very short list - interrupt controller, VM swap disk, and | random_line_split |
mod.rs | // SPDX-License-Identifier: Unlicense
//! A module for the kernel devices which must be used from the kernel.
//!
//! This is a very short list - interrupt controller, VM swap disk, and
//! debug console. Other devices are managed through user-level threads
//! and by receiving the relevant capabilities which allow th... | () -> Result<()> {
major!("init");
let dtb_root = get_dtb_root()?;
Arch::device_init(dtb_root.clone())?;
virtio::init(dtb_root)
}
fn get_dtb_root() -> Result<StructItems<'static>> {
let virt_addr = get_range(RangeContent::DTB)?.base();
let reader = unsafe {
dtb::Reader::read_from_add... | init | identifier_name |
jobs_load.rs | use db;
use elephant;
use json_loader_elephant::json_loader_elephant;
use rusqlite::Connection;
use rustc_serialize::json::Json;
use std::collections::HashMap;
use std::fs::File;
use std::io::Read;
use std::path::Path;
pub fn listy2(direcory: &str) -> Vec<String> {
let mut items = Vec::<String>::new();
let pa... | }
return items;
}
pub fn loader(name: &str) -> String {
let mut f = File::open(name).expect("file not found");
let mut contents = String::new();
f.read_to_string(&mut contents)
.expect("something went wrong reading the file");
return contents;
}
pub fn json_loader_name(conn: &Connecti... | let pb_2 = path.as_path();
let as_path_buf = pb_2.as_os_str();
let path = String::new() + as_path_buf.to_str().unwrap();
items.push(path);
} | random_line_split |
jobs_load.rs | use db;
use elephant;
use json_loader_elephant::json_loader_elephant;
use rusqlite::Connection;
use rustc_serialize::json::Json;
use std::collections::HashMap;
use std::fs::File;
use std::io::Read;
use std::path::Path;
pub fn listy2(direcory: &str) -> Vec<String> | }
}
return items;
}
pub fn loader(name: &str) -> String {
let mut f = File::open(name).expect("file not found");
let mut contents = String::new();
f.read_to_string(&mut contents)
.expect("something went wrong reading the file");
return contents;
}
pub fn json_loader_name(conn... | {
let mut items = Vec::<String>::new();
let path = Path::new(direcory);
if path.exists() == false {
return items;
}
if path.is_dir() == false {
return items;
}
for entry in path.read_dir().expect("read_dir call failed") {
if let Ok(entry) = entry {
let pa... | identifier_body |
jobs_load.rs | use db;
use elephant;
use json_loader_elephant::json_loader_elephant;
use rusqlite::Connection;
use rustc_serialize::json::Json;
use std::collections::HashMap;
use std::fs::File;
use std::io::Read;
use std::path::Path;
pub fn listy2(direcory: &str) -> Vec<String> {
let mut items = Vec::<String>::new();
let pa... | (name: &str) -> String {
let mut f = File::open(name).expect("file not found");
let mut contents = String::new();
f.read_to_string(&mut contents)
.expect("something went wrong reading the file");
return contents;
}
pub fn json_loader_name(conn: &Connection, pk_file: &i32, content: &str) {
... | loader | identifier_name |
lib.rs | according to those terms.
// Do not remove on snapshot creation. Needed for bootstrap. (Issue #22364)
#![cfg_attr(stage0, feature(custom_attribute))]
#![crate_name = "rustdoc"]
#![unstable(feature = "rustdoc", issue = "27812")]
#![staged_api]
#![crate_type = "dylib"]
#![crate_type = "rlib"]
#![doc(html_logo_url = "ht... | (input: &str) -> Result<Output, String> {
let mut bytes = Vec::new();
match File::open(input).and_then(|mut f| f.read_to_end(&mut bytes)) {
Ok(_) => {}
Err(e) => return Err(format!("couldn't open {}: {}", input, e)),
};
match json::from_reader(&mut &bytes[..]) {
Err(s) => Err(for... | json_input | identifier_name |
lib.rs | except according to those terms.
// Do not remove on snapshot creation. Needed for bootstrap. (Issue #22364)
#![cfg_attr(stage0, feature(custom_attribute))]
#![crate_name = "rustdoc"]
#![unstable(feature = "rustdoc", issue = "27812")]
#![staged_api]
#![crate_type = "dylib"]
#![crate_type = "rlib"]
#![doc(html_logo_ur... | // "schema": version,
// "crate": { parsed crate... },
// "plugins": { output of plugins... }
// }
let mut json = std::collections::BTreeMap::new();
json.insert("schema".to_string(), Json::String(SCHEMA_VERSION.to_string()));
let plugins_json = res.into_iter()
... | // { | random_line_split |
test.rs | /* | - [ ] Dimension
- [x] Data
- [x] Subspace<T>
- [x] Of<T>
- [ ] Pair
- [x] Data
- [x] Subspace<T>
- [x] Of<T>
- [ ] EqPair
- [x] Data
- [x] Subspace<T>
- [x] Of<T>
- [ ] NeqPair
- [x] Data
- [x] Subspace<T>
- ... |
Zero - implement unitialized element for all spaces.
First, implement all lacking combinations.
| random_line_split |
test.rs | /*
Zero - implement unitialized element for all spaces.
First, implement all lacking combinations.
- [ ] Dimension
- [x] Data
- [x] Subspace<T>
- [x] Of<T>
- [ ] Pair
- [x] Data
- [x] Subspace<T>
- [x] Of<T>
- [ ] EqPair
- [x] Data
-... | {
let dir: Context<Of<Context>> = Construct::new();
let ref dim = vec![vec![2, 2], vec![2, 2]];
let count = dir.count(dim);
let mut pos = dir.zero(dim);
for i in 0..count {
dir.to_pos(dim, i, &mut pos);
print!("{:?}", pos);
println!(" => {}", dir.to_index(dim, &pos));
}
... | identifier_body | |
test.rs | /*
Zero - implement unitialized element for all spaces.
First, implement all lacking combinations.
- [ ] Dimension
- [x] Data
- [x] Subspace<T>
- [x] Of<T>
- [ ] Pair
- [x] Data
- [x] Subspace<T>
- [x] Of<T>
- [ ] EqPair
- [x] Data
-... | () {
let dir: Context<Of<Context>> = Construct::new();
let ref dim = vec![vec![2, 2], vec![2, 2]];
let count = dir.count(dim);
let mut pos = dir.zero(dim);
for i in 0..count {
dir.to_pos(dim, i, &mut pos);
print!("{:?}", pos);
println!(" => {}", dir.to_index(dim, &pos));
... | main | identifier_name |
session.rs | /* Copyright (C) 2018 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARR... |
#[derive(Debug)]
pub struct SMBTransactionSessionSetup {
pub request_host: Option<SessionSetupRequest>,
pub response_host: Option<SessionSetupResponse>,
pub ntlmssp: Option<NtlmsspData>,
pub krb_ticket: Option<Kerberos5Ticket>,
}
impl SMBTransactionSessionSetup {
pub fn new() -> SMBTransactionSess... | use crate::smb::auth::*; | random_line_split |
session.rs | /* Copyright (C) 2018 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARR... | ,
};
if hit {
return Some(tx);
}
}
return None;
}
}
| { false } | conditional_block |
session.rs | /* Copyright (C) 2018 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARR... |
}
| {
for tx in &mut self.transactions {
let hit = tx.hdr.compare(&hdr) && match tx.type_data {
Some(SMBTransactionTypeData::SESSIONSETUP(_)) => { true },
_ => { false },
};
if hit {
return Some(tx);
}
}
... | identifier_body |
session.rs | /* Copyright (C) 2018 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARR... | {
pub request_host: Option<SessionSetupRequest>,
pub response_host: Option<SessionSetupResponse>,
pub ntlmssp: Option<NtlmsspData>,
pub krb_ticket: Option<Kerberos5Ticket>,
}
impl SMBTransactionSessionSetup {
pub fn new() -> SMBTransactionSessionSetup {
return SMBTransactionSessionSetup {
... | SMBTransactionSessionSetup | identifier_name |
node.rs | use common::dataset::DataSet;
use expr::Expr;
#[derive(Clone)]
pub struct PlanNode {
pub id: u32,
pub decl: NodeDecl,
}
#[derive(Clone)]
pub enum NodeDecl { | Join(Box<PlanNode>, Box<PlanNode>, JoinDecl),
Project(Box<PlanNode>, Vec<Expr>), // child and exprs
Filter(Box<PlanNode>, Vec<Expr>), // child and bool exprs
Aggregate(Box<PlanNode>, AggDecl), // child and decl
Head(Box<PlanNode>, usize), // child and row number
Tail(Box<PlanNode>, usize), // child and row ... | Relation(DataSet),
PartitionedRelation(PartitionedRelDecl),
DerivedRelation(DerivedRelDecl), | random_line_split |
node.rs | use common::dataset::DataSet;
use expr::Expr;
#[derive(Clone)]
pub struct PlanNode {
pub id: u32,
pub decl: NodeDecl,
}
#[derive(Clone)]
pub enum NodeDecl {
Relation(DataSet),
PartitionedRelation(PartitionedRelDecl),
DerivedRelation(DerivedRelDecl),
Join(Box<PlanNode>, Box<PlanNode>, JoinDecl),
Project(... | {
keys: Vec<Expr>,
aggrs: Vec<Expr>,
}
| AggDecl | identifier_name |
glb.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn tag(&self) -> String { "glb".to_string() }
fn a_is_expected(&self) -> bool { self.fields.a_is_expected }
fn trace(&self) -> TypeTrace { self.fields.trace.clone() }
fn equate<'a>(&'a self) -> Equate<'a, 'tcx> { Equate(self.fields.clone()) }
fn sub<'a>(&'a self) -> Sub<'a, 'tcx> { Sub(self.fields... | { self.fields.infcx } | identifier_body |
glb.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | <'f, 'tcx>(cf: CombineFields<'f, 'tcx>) -> Glb<'f, 'tcx> {
Glb { fields: cf }
}
impl<'f, 'tcx> Combine<'tcx> for Glb<'f, 'tcx> {
fn infcx<'a>(&'a self) -> &'a InferCtxt<'a, 'tcx> { self.fields.infcx }
fn tag(&self) -> String { "glb".to_string() }
fn a_is_expected(&self) -> bool { self.fields.a_is_expec... | Glb | identifier_name |
glb.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | }
}
} | this.fields.infcx.region_vars.new_bound(binder_id) | random_line_split |
str.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! String utils for attributes and similar stuff.
#![deny(missing_docs)]
use num_traits::ToPrimitive;
use std:... | <'a>(input: &'a str) -> Cow<'a, str> {
if input.bytes().any(|c| matches!(c, b'A'..=b'Z')) {
input.to_ascii_lowercase().into()
} else {
// Already ascii lowercase.
Cow::Borrowed(input)
}
}
/// To avoid accidentally instantiating multiple monomorphizations of large
/// serialization r... | string_as_ascii_lowercase | identifier_name |
str.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! String utils for attributes and similar stuff.
#![deny(missing_docs)]
use num_traits::ToPrimitive;
use std:... |
/// Read a decimal fraction.
pub fn read_fraction<I: Iterator<Item = char>>(
mut iter: Peekable<I>,
mut divisor: f64,
value: f64,
) -> (f64, usize) {
match iter.peek() {
Some(c) if is_decimal_point(*c) => (),
_ => return (value, 0),
}
iter.next();
iter.take_while(is_ascii_... | {
match iter.peek() {
Some(c) if is_ascii_digit(c) => (),
_ => return (None, 0),
}
iter.take_while(is_ascii_digit)
.map(|d| d as i64 - '0' as i64)
.fold((Some(0i64), 0), |accumulator, d| {
let digits = accumulator
.0
.and_then(|acc... | identifier_body |
str.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! String utils for attributes and similar stuff.
#![deny(missing_docs)]
use num_traits::ToPrimitive;
use std:... | ) -> Filter<Split<'a, StaticCharVec>, fn(&&str) -> bool> {
s.split(HTML_SPACE_CHARACTERS)
.filter(not_empty as fn(&&str) -> bool)
}
/// Split a string on commas.
#[inline]
pub fn split_commas<'a>(s: &'a str) -> Filter<Split<'a, char>, fn(&&str) -> bool> {
s.split(',').filter(not_empty as fn(&&str) -> bo... | random_line_split | |
lib.rs | #![feature(plugin)]
#![plugin(interpolate_idents)]
#[macro_use]
extern crate apache2;
use apache2::{Request, Status, server_banner, server_description, server_built, show_mpm,
apr_version_string, apu_version_string, Cookie, time_now};
apache2_module!(info_rs, b"mod_info_rs\0");
fn unwrap_str<'a>(wrapped: Option<... | for (key, val) in err_headers_out.iter() {
try!(r.write(format!("<p>{}: {}</p>", key, unwrap_str(val))));
}
try!(r.write("<h3>Notes</h3>"));
let notes = get!(r.notes());
for (key, val) in notes.iter() {
try!(r.write(format!("<p>{}: {}</p>", key, unwrap_str(val))));
}
try!(r.write("<... | try!(r.write("<h3>Err Headers Out</h3>"));
let err_headers_out = get!(r.err_headers_out());
| random_line_split |
lib.rs | #![feature(plugin)]
#![plugin(interpolate_idents)]
#[macro_use]
extern crate apache2;
use apache2::{Request, Status, server_banner, server_description, server_built, show_mpm,
apr_version_string, apu_version_string, Cookie, time_now};
apache2_module!(info_rs, b"mod_info_rs\0");
fn unwrap_str<'a>(wrapped: Option<... |
r.set_content_type("text/html");
r.set_last_modified(time_now());
try!(r.write("<!doctype html><html><head><meta charset=\"utf-8\"><title>Apache Info</title></head><body>"));
try!(r.write("<h1>Apache Server Information</h1>"));
let server_name = try!(
r.escape_html(
unwrap_str(r.serv... | {
return Ok(Status::DECLINED)
} | conditional_block |
lib.rs | #![feature(plugin)]
#![plugin(interpolate_idents)]
#[macro_use]
extern crate apache2;
use apache2::{Request, Status, server_banner, server_description, server_built, show_mpm,
apr_version_string, apu_version_string, Cookie, time_now};
apache2_module!(info_rs, b"mod_info_rs\0");
fn | <'a>(wrapped: Option<&'a str>) -> &'a str {
wrapped.unwrap_or("--")
}
fn info_rs_handler(r: &mut Request) -> Result<Status, ()> {
if get!(r.handler())!= "server-info-rs" {
return Ok(Status::DECLINED)
}
r.set_content_type("text/html");
r.set_last_modified(time_now());
try!(r.write("<!doctype ... | unwrap_str | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.