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 |
|---|---|---|---|---|
sha1.rs | // http://rosettacode.org/wiki/SHA-1
#![cfg_attr(feature = "clippy", allow(many_single_char_names))]
//! Straight port from golang crypto/sha1 library implementation
use std::num::Wrapping as wr;
use std::io::{Write, Result};
/// The size of a SHA1 checksum in bytes.
const SIZE: usize = 20;
/// The blocksize of SHA... |
let mut w: [u32; 16] = [0u32; 16];
let (mut h0, mut h1, mut h2, mut h3, mut h4) =
(self.h[0], self.h[1], self.h[2], self.h[3], self.h[4]);
let mut p = data;
while p.len() >= CHUNK {
for i in 0..16 {
let j = i * 4;
w[i] = (p[j] ... | {
((a << 5 | a >> (32 - 5)), (b << 30 | b >> (32 - 30)))
} | identifier_body |
sha1.rs | // http://rosettacode.org/wiki/SHA-1
#![cfg_attr(feature = "clippy", allow(many_single_char_names))]
//! Straight port from golang crypto/sha1 library implementation
use std::num::Wrapping as wr;
use std::io::{Write, Result};
/// The size of a SHA1 checksum in bytes.
const SIZE: usize = 20;
/// The blocksize of SHA... | () {
let mut d = Digest::new();
let _ = write!(&mut d, "The quick brown fox jumps over the lazy dog");
let sha1 = d.sha1();
for h in &sha1 {
print!("{:x} ", *h);
}
}
/// digest represents the partial evaluation of a checksum.
struct Digest {
h: [wr<u32>; 5],
x: [u8; CHUNK],
nx:... | main | identifier_name |
sha1.rs | // http://rosettacode.org/wiki/SHA-1
#![cfg_attr(feature = "clippy", allow(many_single_char_names))]
//! Straight port from golang crypto/sha1 library implementation
use std::num::Wrapping as wr;
use std::io::{Write, Result};
/// The size of a SHA1 checksum in bytes.
const SIZE: usize = 20;
/// The blocksize of SHA... |
let ln = buf_m.len();
if ln > 0 {
assert!(self.x.len() >= ln);
self.x.as_mut().write_all(buf_m).unwrap();
self.nx = ln;
}
Ok(())
}
fn flush(&mut self) -> Result<()> {
Ok(())
}
}
#[test]
fn known_sha1s() {
let input_output = [... | {
let n = buf_m.len() & !(CHUNK - 1);
let x = &(self.x[n..]);
self.h = self.process_block(x);
buf_m = &buf_m[n..];
} | conditional_block |
sha1.rs | // http://rosettacode.org/wiki/SHA-1
#![cfg_attr(feature = "clippy", allow(many_single_char_names))]
//! Straight port from golang crypto/sha1 library implementation
use std::num::Wrapping as wr;
use std::io::{Write, Result};
/// The size of a SHA1 checksum in bytes.
const SIZE: usize = 20;
/// The blocksize of SHA... | n = CHUNK - self.nx;
}
for i in 0..n {
self.x[self.nx + i] = *buf_m.get(i).unwrap();
}
self.nx += n;
if self.nx == CHUNK {
let x = &(self.x[..]);
self.h = self.process_block(x);
se... | let mut n = buf_m.len();
if n > CHUNK - self.nx { | random_line_split |
lib.rs | // DO NOT EDIT!
// This file was generated automatically from'src/mako/api/lib.rs.mako'
// DO NOT EDIT!
//! This documentation was generated from *datastore* crate version *0.1.8+20150402*, where *20150402* is the exact revision of the *datastore:v1beta2* schema built by the [mako](http://www.makotemplates.org/) code ... | //!
//! All structures provided by this library are made to be [enocodable](trait.RequestValue.html) and
//! [decodable](trait.ResponseResult.html) via *json*. Optionals are used to indicate that partial requests are responses
//! are valid.
//! Most optionals are are considered [Parts](trait.Part.html) which are id... | //! The [delegate trait](trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort.
//!
//! ## Optional Parts in Server-Requests | random_line_split |
glue.rs |
pub fn trans_exchange_free<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
v: ValueRef,
size: u64,
align: u32,
debug_loc: DebugLoc)
-> B... | {
let _icx = push_ctxt("trans_exchange_free");
let ccx = cx.ccx();
callee::trans_lang_call(cx,
langcall(cx, None, "", ExchangeFreeFnLangItem),
&[PointerCast(cx, v, Type::i8p(ccx)), size, align],
Some(expr::Ignore),
debug_loc).bcx
} | identifier_body | |
glue.rs | ptr: ValueRef,
content_ty: Ty<'tcx>,
debug_loc: DebugLoc)
-> Block<'blk, 'tcx> {
assert!(type_is_sized(bcx.ccx().tcx(), content_ty));
let sizing_type = sizing_type_of(bcx.ccx(), cont... |
match t.sty {
ty::TyStruct(id, substs) => {
let ccx = bcx.ccx();
// First get the size of all statically known fields.
// Don't use type_of::sizing_type_of because that expects t to be sized.
assert!(!t.is_simd(bcx.tcx()));
let repr = adt::represe... | {
let sizing_type = sizing_type_of(bcx.ccx(), t);
let size = C_uint(bcx.ccx(), llsize_of_alloc(bcx.ccx(), sizing_type));
let align = C_uint(bcx.ccx(), align_of(bcx.ccx(), t));
return (size, align);
} | conditional_block |
glue.rs | ptr: ValueRef,
content_ty: Ty<'tcx>,
debug_loc: DebugLoc)
-> Block<'blk, 'tcx> {
assert!(type_is_sized(bcx.ccx().tcx(), content_ty));
let sizing_type = sizing_type_of(bcx.ccx(), cont... | (&self) -> Ty<'tcx> {
match *self { DropGlueKind::Ty(t) | DropGlueKind::TyContents(t) => t }
}
fn map_ty<F>(&self, mut f: F) -> DropGlueKind<'tcx> where F: FnMut(Ty<'tcx>) -> Ty<'tcx>
{
match *self {
DropGlueKind::Ty(t) => DropGlueKind::Ty(f(t)),
DropGlueKind::TyCont... | ty | identifier_name |
glue.rs | trans_exchange_free(bcx, ptr, content_size, content_align, debug_loc)
} else {
bcx
}
}
pub fn get_drop_glue_type<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
t: Ty<'tcx>) -> Ty<'tcx> {
let tcx = ccx.tcx();
// Even if there is no dtor for t, there might be o... | // a safe-guard, assert TyBox not used with TyContents. | random_line_split | |
assoc.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 ... | {
debug!("normalize_associated_types_in(value={:?})", value);
let mut selcx = SelectionContext::new(infcx, typer);
let cause = ObligationCause::new(span, body_id, MiscObligation);
let Normalized { value: result, obligations } = traits::normalize(&mut selcx, cause, value);
debug!("normalize_associate... | identifier_body | |
assoc.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 ... | <'a,'tcx,T>(infcx: &InferCtxt<'a,'tcx>,
typer: &(ty::ClosureTyper<'tcx>+'a),
fulfillment_cx: &mut FulfillmentContext<'tcx>,
span: Span,
... | normalize_associated_types_in | identifier_name |
assoc.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 ... | where T : TypeFoldable<'tcx> + HasTypeFlags
{
debug!("normalize_associated_types_in(value={:?})", value);
let mut selcx = SelectionContext::new(infcx, typer);
let cause = ObligationCause::new(span, body_id, MiscObligation);
let Normalized { value: result, obligations } = traits::normalize(&mut selcx... | body_id: ast::NodeId,
value: &T)
-> T | random_line_split |
mod.rs | #[cfg(not(any(test, rustdoc)))]
#[allow(unused_imports)]
use alloc::prelude::v1::*;
#[cfg(any(test, rustdoc))]
#[allow(unused_imports)]
use std::prelude::v1::*;
use crate::event::EventHandler;
use crate::platform;
use crate::util::UnsafeContainer;
use crate::DRIVERS;
use crate::KERNEL_EVENTEMITTER;
pub mod driver_typ... |
pub fn setup_event_handlers() {
// register standard driver event handler
KERNEL_EVENTEMITTER.get().handlers.push(EventHandler::new(
|c, _, _| c == "driver",
driver_event_handler,
));
// register framework driver event handler
KERNEL_EVENTEMITTER.get().handlers.push(EventHandler::... | {
match DRIVERS.get().find_framework_by_name(name) {
Some(ref d) => Some(d.driver_id()),
None => DRIVER_FACTORIES.get().construct_framework_driver(name),
}
} | identifier_body |
mod.rs | #[cfg(not(any(test, rustdoc)))]
#[allow(unused_imports)]
use alloc::prelude::v1::*;
#[cfg(any(test, rustdoc))]
#[allow(unused_imports)]
use std::prelude::v1::*;
use crate::event::EventHandler;
use crate::platform;
use crate::util::UnsafeContainer;
use crate::DRIVERS;
use crate::KERNEL_EVENTEMITTER;
pub mod driver_typ... | "serial_16550",
Box::new(serial_16550::serial_16550_checker),
Box::new(serial_16550::serial_16550_factory),
);
UnsafeContainer::new(container)
};
}
pub fn require_framework(name: &str) -> Option<usize> {
match DRIVERS.get().find_framework_by_name(name) {
... | random_line_split | |
mod.rs | #[cfg(not(any(test, rustdoc)))]
#[allow(unused_imports)]
use alloc::prelude::v1::*;
#[cfg(any(test, rustdoc))]
#[allow(unused_imports)]
use std::prelude::v1::*;
use crate::event::EventHandler;
use crate::platform;
use crate::util::UnsafeContainer;
use crate::DRIVERS;
use crate::KERNEL_EVENTEMITTER;
pub mod driver_typ... | () {
// register standard driver event handler
KERNEL_EVENTEMITTER.get().handlers.push(EventHandler::new(
|c, _, _| c == "driver",
driver_event_handler,
));
// register framework driver event handler
KERNEL_EVENTEMITTER.get().handlers.push(EventHandler::new(
|c, _, _| c == "... | setup_event_handlers | identifier_name |
main.rs | // Copyright 2015 Markus Dittrich
// Licensed under BSD license, see LICENSE file for details
//
// st is a simple commandline helper script for calculating basic
// statistics on a data file consisting of column oriented
// floating point numbers.
// NOTE: Currently stats will read in all the data to compute the stati... | {
count: i64,
min: f64,
max: f64,
mean: f64,
median: f64,
sd: f64,
qk: f64,
mk: f64,
med: stats::Median,
}
impl Output {
fn new() -> Output {
Output { count: 0, min: f64::MAX, max: -f64::MAX, mean: 0.0,
median: 0.0, sd: 0.0, qk: 0.0, mk: 0.0, med: stats::Median::new()}
}
fn update(... | Output | identifier_name |
main.rs | // Copyright 2015 Markus Dittrich
// Licensed under BSD license, see LICENSE file for details
//
// st is a simple commandline helper script for calculating basic
// statistics on a data file consisting of column oriented
// floating point numbers.
// NOTE: Currently stats will read in all the data to compute the stati... | if file.is_err() {
usage();
return;
}
let buf = BufReader::new(file.unwrap());
let out = compute_statistics(buf);
let mut count = 0;
for o in out {
println!("Column {}: \n", count);
println!("#elems : {}", o.count);
println!("min : {}", o.min);
println!("max : {}", o.max);
... | let file_name = &args[1];
let file = File::open(file_name); | random_line_split |
main.rs | // Copyright 2015 Markus Dittrich
// Licensed under BSD license, see LICENSE file for details
//
// st is a simple commandline helper script for calculating basic
// statistics on a data file consisting of column oriented
// floating point numbers.
// NOTE: Currently stats will read in all the data to compute the stati... |
fn finalize(&mut self) {
let k: f64 = self.count as f64;
self.sd = (self.qk/(k-1.0)).sqrt();
self.mean /= k;
self.median = self.med.get();
}
}
| {
self.count += 1;
// update median
self.med.update(stats::FloatVal::new(v));
// update variance
let k: f64 = self.count as f64;
self.qk += (k - 1.0) * (v - self.mk) * (v - self.mk) / k;
self.mk += (v - self.mk) / k;
// update min, max, and mean
self.mean += v;
self.min = self... | identifier_body |
main.rs | // Copyright 2015 Markus Dittrich
// Licensed under BSD license, see LICENSE file for details
//
// st is a simple commandline helper script for calculating basic
// statistics on a data file consisting of column oriented
// floating point numbers.
// NOTE: Currently stats will read in all the data to compute the stati... |
let tokens : Vec<&str> = s.split(" ").collect();
for i in 0..tokens.len() {
out.push(Output::new());
let n_r = tokens[i].trim().parse::<f64>();
if n_r.is_err() {
println!("Warning {} in line {} is not a number. Skipping", s, out[i].count);
continue;
}
let n = n_r.unwrap();
out[... | {
return out;
} | conditional_block |
files.rs | ;
use formats::FormatSpec;
use schemars::{schema::Schema, JsonSchema};
use serde::Serialize;
use serde_with::skip_serializing_none;
use std::{
collections::{btree_map::Entry, BTreeMap, BTreeSet},
path::{Path, PathBuf},
time::UNIX_EPOCH,
};
use strum::Display;
/// A file or directory within a `Project`
#[sk... | ) {
if let Some(children) = &mut file.children {
let mut new_children = BTreeSet::new();
for child_old_path in children.iter() {
let child_new_path = new_path.join(
child_old_path
.strip_prefix(old... | old_path: &Path,
new_path: &Path, | random_line_split |
files.rs | use formats::FormatSpec;
use schemars::{schema::Schema, JsonSchema};
use serde::Serialize;
use serde_with::skip_serializing_none;
use std::{
collections::{btree_map::Entry, BTreeMap, BTreeSet},
path::{Path, PathBuf},
time::UNIX_EPOCH,
};
use strum::Display;
/// A file or directory within a `Project`
#[skip... | {
Refreshed,
Created,
Removed,
Renamed,
Modified,
}
/// An event associated with a `File` or a set of `File`s
///
/// These events published under the `projects:<project-path>:files` topic.
#[derive(JsonSchema, Serialize)]
#[schemars(deny_unknown_fields)]
pub struct FileEvent {
/// The path of... | FileEventType | identifier_name |
files.rs | use formats::FormatSpec;
use schemars::{schema::Schema, JsonSchema};
use serde::Serialize;
use serde_with::skip_serializing_none;
use std::{
collections::{btree_map::Entry, BTreeMap, BTreeSet},
path::{Path, PathBuf},
time::UNIX_EPOCH,
};
use strum::Display;
/// A file or directory within a `Project`
#[skip... | else {
false
}
}
/// Is the file a Git ignore file?
fn is_ignore_file(path: &Path) -> bool {
let name = File::name(path);
Files::GITIGNORE_NAMES.contains(&name.as_str())
}
/// Should a path be ignored?
///
/// Used by the following functions to decide w... | {
self.refresh();
true
} | conditional_block |
files.rs | use formats::FormatSpec;
use schemars::{schema::Schema, JsonSchema};
use serde::Serialize;
use serde_with::skip_serializing_none;
use std::{
collections::{btree_map::Entry, BTreeMap, BTreeSet},
path::{Path, PathBuf},
time::UNIX_EPOCH,
};
use strum::Display;
/// A file or directory within a `Project`
#[skip... |
/// Get a file's name from it's path
pub fn name(path: &Path) -> String {
path.file_name()
.map(|os_str| os_str.to_string_lossy())
.unwrap_or_default()
.into()
}
/// Get a file's parent from it's path
pub fn parent(path: &Path) -> Option<PathBuf> {
... | {
schemas::typescript("Format", true)
} | identifier_body |
mod.rs | //! Handler utilities for the various shell protocols
//!
//! Wayland, via its different protocol extensions, supports different kind of
//! shells. Here a shell represent the logic associated to displaying windows and
//! arranging them on the screen.
//!
//! The shell protocols thus define what kind of interactions a... | /// or `zxdg_toplevel`.
pub fn is_toplevel_equivalent(surface: &WlSurface) -> bool {
// (z)xdg_toplevel and wl_shell_surface are toplevel like, so verify if the roles match.
let role = compositor::get_role(surface);
matches!(
role,
Some(xdg::XDG_TOPLEVEL_ROLE) | Some(xdg::ZXDG_TOPLEVEL_ROLE... | /// This is method checks if the surface roles is one of `wl_shell_surface`, `xdg_toplevel` | random_line_split |
mod.rs | //! Handler utilities for the various shell protocols
//!
//! Wayland, via its different protocol extensions, supports different kind of
//! shells. Here a shell represent the logic associated to displaying windows and
//! arranging them on the screen.
//!
//! The shell protocols thus define what kind of interactions a... | {
/// The operation failed because the underlying surface has been destroyed
#[error("the ping failed cause the underlying surface has been destroyed")]
DeadSurface,
/// There is already a pending ping
#[error("there is already a ping pending `{0:?}`")]
PingAlreadyPending(Serial),
}
/// Return... | PingError | identifier_name |
mod.rs | use std::fs::File;
use std::io::Read;
use std::path::{Path, PathBuf};
use serde::Serialize;
mod dir;
mod markdown;
mod unknown;
pub trait FileType {
fn get_url(&self, context: &crate::AppContext<'_>) -> String;
fn convert(&self, context: &crate::AppContext<'_>);
fn get_type_str(&self) -> &'static str;
}
... | result.insert(
1,
Link {
name: file_name,
url: url,
},
);
temp.pop();
}
result
}
}
pub fn read_file<P: AsRef<Path>>(path: P) -> Result<String, &'static str> {
let path: &P... | }];
let mut temp = PathBuf::from(path.clone().parent().unwrap());
while temp.file_name().is_some() {
let file_name = String::from(temp.file_name().unwrap().to_str().unwrap());
let url = format!("{}{}", &base_url, temp.to_str().unwrap()); | random_line_split |
mod.rs | use std::fs::File;
use std::io::Read;
use std::path::{Path, PathBuf};
use serde::Serialize;
mod dir;
mod markdown;
mod unknown;
pub trait FileType {
fn get_url(&self, context: &crate::AppContext<'_>) -> String;
fn convert(&self, context: &crate::AppContext<'_>);
fn get_type_str(&self) -> &'static str;
}
... | }
result
}
}
pub fn read_file<P: AsRef<Path>>(path: P) -> Result<String, &'static str> {
let path: &Path = path.as_ref();
let mut file = match File::open(&path) {
Ok(ok_file) => ok_file,
Err(_) => return Err("Could not open path."),
};
let mut contents = String::new... | {
if is_dir && path.file_name().is_none() {
Vec::new()
} else {
let mut result: Vec<Link> = vec![Link {
name: String::from("root"),
url: format!("{}", base_url),
}];
let mut temp = PathBuf::from(path.clone().parent().unwrap());
while temp.file_name... | identifier_body |
mod.rs | use std::fs::File;
use std::io::Read;
use std::path::{Path, PathBuf};
use serde::Serialize;
mod dir;
mod markdown;
mod unknown;
pub trait FileType {
fn get_url(&self, context: &crate::AppContext<'_>) -> String;
fn convert(&self, context: &crate::AppContext<'_>);
fn get_type_str(&self) -> &'static str;
}
... | () -> FileTypeManager {
FileTypeManager {
factories: vec![
Box::new(markdown::MarkdownFactory),
Box::new(dir::DirFactory),
],
unknown_factory: unknown::UnknownFactory,
}
}
pub fn initialize_app_context(
&self,
a... | new | identifier_name |
dead-code-leading-underscore.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 _foo() {}
struct _Y {
_z: uint
}
enum _Z {}
impl _Y {
fn _bar() {}
}
type _A = int;
mod _bar {
fn _qux() {}
}
extern {
#[link_name = "abort"]
fn _abort() ->!;
}
pub fn main() {} | random_line_split | |
dead-code-leading-underscore.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 ... | () {}
| main | identifier_name |
error.rs | use std;
use std::fmt;
use std::fmt::Display;
use std::io;
use std::num;
use std::string;
use serde::{de, ser};
/// Alias for a `Result` with the error type [`serde_osc::error::Error`].
///
/// [`serde_osc::error::Error`]: enum.Error.html
pub type ResultE<T> = Result<T, Error>;
/// Unified error type used in both se... | <T: Display>(msg: T) -> Self {
Error::Message(msg.to_string())
}
}
| custom | identifier_name |
error.rs | use std;
use std::fmt;
use std::fmt::Display;
use std::io;
use std::num;
use std::string;
use serde::{de, ser};
/// Alias for a `Result` with the error type [`serde_osc::error::Error`].
///
/// [`serde_osc::error::Error`]: enum.Error.html
pub type ResultE<T> = Result<T, Error>;
/// Unified error type used in both se... | BadCast(num::TryFromIntError),
/// We store ascii strings as UTF-8.
/// Technically, this is safe, but if we received non-ascii data, we could have invalid UTF-8
StrParseError(string::FromUtf8Error),
}
/// Conversion from `io::Error` for use with the `?` operator
impl From<io::Error> for Error {
f... | /// e.g. OSC spec uses i32 for lengths, which we cast to u64, but that could underflow. | random_line_split |
error.rs | use std;
use std::fmt;
use std::fmt::Display;
use std::io;
use std::num;
use std::string;
use serde::{de, ser};
/// Alias for a `Result` with the error type [`serde_osc::error::Error`].
///
/// [`serde_osc::error::Error`]: enum.Error.html
pub type ResultE<T> = Result<T, Error>;
/// Unified error type used in both se... |
}
impl de::Error for Error {
fn custom<T: Display>(msg: T) -> Self {
Error::Message(msg.to_string())
}
}
impl ser::Error for Error {
fn custom<T: Display>(msg: T) -> Self {
Error::Message(msg.to_string())
}
}
| {
match *self {
Error::Io(ref io_error) => Some(io_error),
Error::BadCast(ref cast_error) => Some(cast_error),
Error::StrParseError(ref utf_error) => Some(utf_error),
_ => None,
}
} | identifier_body |
mod.rs | // +--------------------------------------------------------------------------+
// | Copyright 2016 Matthew D. Steele <mdsteele@alum.mit.edu> | | // | System Syzygy 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. |
... | // | |
// | This file is part of System Syzygy. |
// | | | random_line_split |
mod.rs | // +--------------------------------------------------------------------------+
// | Copyright 2016 Matthew D. Steele <mdsteele@alum.mit.edu> |
// | |
// | This file is part of System Syzygy. |
... |
// ========================================================================= //
| {
let view = {
let visible_rect = window.visible_rect();
View::new(
&mut window.resources(),
visible_rect,
&save_data.game_mut().plane_as_day,
)
};
run_puzzle(window, save_data, view)
} | identifier_body |
mod.rs | // +--------------------------------------------------------------------------+
// | Copyright 2016 Matthew D. Steele <mdsteele@alum.mit.edu> |
// | |
// | This file is part of System Syzygy. |
... | (
window: &mut Window,
save_data: &mut SaveData,
) -> Mode {
let view = {
let visible_rect = window.visible_rect();
View::new(
&mut window.resources(),
visible_rect,
&save_data.game_mut().plane_as_day,
)
};
run_puzzle(window, save_data, vie... | run_plane_as_day | identifier_name |
power_bank.rs | //! `StructurePowerBank` data description.
use crate::data::RoomName;
with_structure_fields_and_update_struct! {
/// A power bank object, which can be attacked by creeps, and when killed will yield a harvest of power.
#[derive(Clone, Debug, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Stru... | y: 40,
id: "59695d5c09c7343d8a4192fd".to_owned(),
decay_time: 20238724,
hits: 2000000,
hits_max: 2000000,
power: 3186,
}
);
}
}
| {
let json = json!({
"_id": "59695d5c09c7343d8a4192fd",
"decayTime": 20238724,
"hits": 2000000,
"hitsMax": 2000000,
"power": 3186,
"room": "W66N20",
"type": "powerBank",
"x": 24,
"y": 40
});
... | identifier_body |
power_bank.rs | //! `StructurePowerBank` data description.
use crate::data::RoomName;
with_structure_fields_and_update_struct! {
/// A power bank object, which can be attacked by creeps, and when killed will yield a harvest of power.
#[derive(Clone, Debug, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Stru... | () {
let json = json!({
"_id": "59695d5c09c7343d8a4192fd",
"decayTime": 20238724,
"hits": 2000000,
"hitsMax": 2000000,
"power": 3186,
"room": "W66N20",
"type": "powerBank",
"x": 24,
"y": 40
});
... | parse_power_bank | identifier_name |
power_bank.rs | //! `StructurePowerBank` data description.
use crate::data::RoomName;
with_structure_fields_and_update_struct! {
/// A power bank object, which can be attacked by creeps, and when killed will yield a harvest of power.
#[derive(Clone, Debug, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Stru... | "room": "W66N20",
"type": "powerBank",
"x": 24,
"y": 40
});
let obj = StructurePowerBank::deserialize(json).unwrap();
assert_eq!(
obj,
StructurePowerBank {
room: RoomName::new("W66N20").unwrap(),
... | random_line_split | |
db_session.rs | use rusqlite::Connection;
#[derive(Debug)]
pub struct Session {
pub id: i32,
pub uuid: String,
}
pub fn table_create_session(conn: &Connection) -> Result<(), &'static str> {
let load_table = conn.execute_batch(
"
BEGIN;
CREATE TABLE WHENENV_SESSION (
id ... |
dir_instance.unwrap();
return Ok(0);
}
pub fn list_session(conn: &Connection) -> Vec<Session> {
let mut stmt = conn
.prepare("SELECT id, uuid FROM WHENENV_SESSION")
.unwrap();
let wraped_fs_file_iter = stmt.query_map(&[], |row| Session {
id: row.get(0),
uuid: row.get(1),
... | {
return Err("ssss");
} | conditional_block |
db_session.rs | use rusqlite::Connection;
#[derive(Debug)]
pub struct Session {
pub id: i32,
pub uuid: String,
}
pub fn table_create_session(conn: &Connection) -> Result<(), &'static str> {
let load_table = conn.execute_batch(
"
BEGIN;
CREATE TABLE WHENENV_SESSION (
id ... |
pub fn list_session(conn: &Connection) -> Vec<Session> {
let mut stmt = conn
.prepare("SELECT id, uuid FROM WHENENV_SESSION")
.unwrap();
let wraped_fs_file_iter = stmt.query_map(&[], |row| Session {
id: row.get(0),
uuid: row.get(1),
});
let mut items = Vec::<Session>::new... | {
let session = Session {
id: 0,
uuid: uuid.to_string(),
};
let dir_instance = conn.execute(
"INSERT INTO WHENENV_SESSION (uuid)
VALUES (?1)",
&[&session.uuid],
);
if dir_instance.is_err() {
return Err("ssss");
}
dir_instance.unwrap();... | identifier_body |
db_session.rs | use rusqlite::Connection;
#[derive(Debug)]
pub struct Session {
pub id: i32,
pub uuid: String,
}
pub fn | (conn: &Connection) -> Result<(), &'static str> {
let load_table = conn.execute_batch(
"
BEGIN;
CREATE TABLE WHENENV_SESSION (
id INTEGER PRIMARY KEY ASC,
uuid TEXT NOT NULL UNIQUE
);
COMMIT;",
);
... | table_create_session | identifier_name |
db_session.rs | use rusqlite::Connection;
#[derive(Debug)]
pub struct Session {
pub id: i32,
pub uuid: String,
}
pub fn table_create_session(conn: &Connection) -> Result<(), &'static str> {
let load_table = conn.execute_batch(
"
BEGIN;
CREATE TABLE WHENENV_SESSION (
id ... | let session = Session {
id: 0,
uuid: uuid.to_string(),
};
let dir_instance = conn.execute(
"INSERT INTO WHENENV_SESSION (uuid)
VALUES (?1)",
&[&session.uuid],
);
if dir_instance.is_err() {
return Err("ssss");
}
dir_instance.unwrap();
... | pub fn insert_session(conn: &Connection, uuid: &str) -> Result<i32, &'static str> { | random_line_split |
transform_feedback.rs | use std::mem;
use version::Api;
use version::Version;
use context::CommandContext;
use backend::Facade;
use BufferViewExt;
use ContextExt;
use TransformFeedbackSessionExt;
use buffer::{BufferView, BufferViewAnySlice};
use index::PrimitiveType;
use program::OutputPrimitives;
use program::Program;
use vertex::Vertex;
u... |
if!program.transform_feedback_matches(&<V as Vertex>::build_bindings(),
mem::size_of::<V>())
{
return Err(TransformFeedbackSessionCreationError::WrongVertexFormat);
}
Ok(TransformFeedbackSession {
buffer: buffer.a... | return Err(TransformFeedbackSessionCreationError::NotSupported);
} | random_line_split |
transform_feedback.rs | use std::mem;
use version::Api;
use version::Version;
use context::CommandContext;
use backend::Facade;
use BufferViewExt;
use ContextExt;
use TransformFeedbackSessionExt;
use buffer::{BufferView, BufferViewAnySlice};
use index::PrimitiveType;
use program::OutputPrimitives;
use program::Program;
use vertex::Vertex;
u... | (mut ctxt: &mut CommandContext, buffer: gl::types::GLuint) {
if ctxt.state.transform_feedback_enabled.is_none() {
return;
}
let mut needs_unbind = false;
for elem in ctxt.state.indexed_transform_feedback_buffer_bindings.iter_mut() {
if elem.buffer == buffer {
... | ensure_buffer_out_of_transform_feedback | identifier_name |
transform_feedback.rs | use std::mem;
use version::Api;
use version::Version;
use context::CommandContext;
use backend::Facade;
use BufferViewExt;
use ContextExt;
use TransformFeedbackSessionExt;
use buffer::{BufferView, BufferViewAnySlice};
use index::PrimitiveType;
use program::OutputPrimitives;
use program::Program;
use vertex::Vertex;
u... |
fn ensure_buffer_out_of_transform_feedback(mut ctxt: &mut CommandContext, buffer: gl::types::GLuint) {
if ctxt.state.transform_feedback_enabled.is_none() {
return;
}
let mut needs_unbind = false;
for elem in ctxt.state.indexed_transform_feedback_buffer_bindings.iter_mu... | {
if ctxt.state.transform_feedback_enabled.is_none() {
return;
}
unsafe {
ctxt.gl.EndTransformFeedback();
ctxt.state.transform_feedback_enabled = None;
ctxt.state.transform_feedback_paused = false;
}
} | identifier_body |
tests.rs | use super::{parse_next_substitution as pns, Substitution as S};
macro_rules! assert_eq_pnsat {
($lhs:expr, $rhs:expr) => {
assert_eq!(
pns($lhs).and_then(|(f, _)| f.translate().ok()),
$rhs.map(<String as From<&str>>::from)
)
};
}
#[test]
fn test_escape() {
assert_eq... |
#[test]
fn test_translation() {
assert_eq_pnsat!("$0", Some("{0}"));
assert_eq_pnsat!("$9", Some("{9}"));
assert_eq_pnsat!("$1", Some("{1}"));
assert_eq_pnsat!("$10", Some("{1}"));
assert_eq_pnsat!("$stuff", Some("{stuff}"));
assert_eq_pnsat!("$NAME", Some("{NAME}"));
assert_eq_pnsat!("$PR... | {
use super::iter_subs;
let s = "The $0'th word $$ is: `$WORD` $!\n";
let subs: Vec<_> = iter_subs(s, 0).map(|sub| sub.translate().ok()).collect();
assert_eq!(
subs.iter().map(|ms| ms.as_ref().map(|s| &s[..])).collect::<Vec<_>>(),
vec![Some("{0}"), None, Some("{WORD}")]
);
} | identifier_body |
tests.rs | use super::{parse_next_substitution as pns, Substitution as S};
macro_rules! assert_eq_pnsat {
($lhs:expr, $rhs:expr) => {
assert_eq!(
pns($lhs).and_then(|(f, _)| f.translate().ok()),
$rhs.map(<String as From<&str>>::from)
)
};
}
#[test]
fn test_escape() {
assert_eq... | assert_eq_pnsat!("$PREFIX/bin", Some("{PREFIX}"));
} | assert_eq_pnsat!("$NAME", Some("{NAME}")); | random_line_split |
tests.rs | use super::{parse_next_substitution as pns, Substitution as S};
macro_rules! assert_eq_pnsat {
($lhs:expr, $rhs:expr) => {
assert_eq!(
pns($lhs).and_then(|(f, _)| f.translate().ok()),
$rhs.map(<String as From<&str>>::from)
)
};
}
#[test]
fn test_escape() {
assert_eq... | () {
assert_eq_pnsat!("$0", Some("{0}"));
assert_eq_pnsat!("$9", Some("{9}"));
assert_eq_pnsat!("$1", Some("{1}"));
assert_eq_pnsat!("$10", Some("{1}"));
assert_eq_pnsat!("$stuff", Some("{stuff}"));
assert_eq_pnsat!("$NAME", Some("{NAME}"));
assert_eq_pnsat!("$PREFIX/bin", Some("{PREFIX}"));... | test_translation | identifier_name |
maskmovdqu.rs | use ::Reg::*;
use ::RegScale::*;
fn maskmovdqu_1() {
run_test(&Instruction { mnemonic: Mnemonic::MASKMOVDQU, operand1: Some(Direct(XMM5)), operand2: Some(Direct(XMM2)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 247, 234... | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*; | random_line_split | |
maskmovdqu.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn maskmovdqu_1() {
run_test(&Instruction { mnemonic: Mnemonic::MASKMOVDQU, operand1: Some(Direct(XMM5)), operand2: Some(D... | {
run_test(&Instruction { mnemonic: Mnemonic::MASKMOVDQU, operand1: Some(Direct(XMM1)), operand2: Some(Direct(XMM7)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 247, 207], OperandSize::Qword)
} | identifier_body | |
maskmovdqu.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn | () {
run_test(&Instruction { mnemonic: Mnemonic::MASKMOVDQU, operand1: Some(Direct(XMM5)), operand2: Some(Direct(XMM2)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 247, 234], OperandSize::Dword)
}
fn maskmovdqu_2() {
... | maskmovdqu_1 | identifier_name |
lib.rs | extern crate ramp;
extern crate rpaillier;
use ramp::int::{ Int };
use rpaillier::KeyPairBuilder;
#[test]
fn test_encrypt_decrypt() {
let key_pair = KeyPairBuilder::new().bits(128).finalize();
let public_key = &key_pair.public_key;
let m = Int::from(37);
let c = public_key.encrypt(&m);
let a =... | {
let kp = KeyPairBuilder::new().bits(128).finalize();
let pk = &kp.public_key;
let m1 = Int::from(37);
let m2 = Int::from(132);
let c1 = pk.encrypt(&m1);
let c2 = pk.encrypt(&m2);
let add = (c1 * c2) % &pk.n_squared;
let e = m1 + m2;
let a = kp.decrypt(&add);
assert_eq!(a,... | identifier_body | |
lib.rs | extern crate ramp;
extern crate rpaillier;
use ramp::int::{ Int };
use rpaillier::KeyPairBuilder;
#[test]
fn test_encrypt_decrypt() {
let key_pair = KeyPairBuilder::new().bits(128).finalize();
let public_key = &key_pair.public_key;
let m = Int::from(37);
let c = public_key.encrypt(&m);
let a =... |
assert_eq!(a, e);
} | let add = (c1 * c2) % &pk.n_squared;
let e = m1 + m2;
let a = kp.decrypt(&add); | random_line_split |
lib.rs | extern crate ramp;
extern crate rpaillier;
use ramp::int::{ Int };
use rpaillier::KeyPairBuilder;
#[test]
fn | () {
let key_pair = KeyPairBuilder::new().bits(128).finalize();
let public_key = &key_pair.public_key;
let m = Int::from(37);
let c = public_key.encrypt(&m);
let a = key_pair.decrypt(&c);
assert_eq!(m, a);
}
#[test]
fn test_homomorphic_properties() {
let kp = KeyPairBuilder::new().bits(... | test_encrypt_decrypt | identifier_name |
documenttype.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/. */
use dom::bindings::codegen::Bindings::DocumentTypeBinding;
use dom::bindings::codegen::Bindings::DocumentTypeBindi... | (self) {
let node = NodeCast::from_ref(self);
node.remove_self();
}
}
| Remove | identifier_name |
documenttype.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/. */
use dom::bindings::codegen::Bindings::DocumentTypeBinding;
use dom::bindings::codegen::Bindings::DocumentTypeBindi... |
// https://dom.spec.whatwg.org/#dom-childnode-before
fn Before(self, nodes: Vec<NodeOrString>) -> ErrorResult {
NodeCast::from_ref(self).before(nodes)
}
// https://dom.spec.whatwg.org/#dom-childnode-after
fn After(self, nodes: Vec<NodeOrString>) -> ErrorResult {
NodeCast::from_ref... | {
self.system_id.clone()
} | identifier_body |
documenttype.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/. */
use dom::bindings::codegen::Bindings::DocumentTypeBinding;
use dom::bindings::codegen::Bindings::DocumentTypeBindi... |
impl DocumentTypeDerived for EventTarget {
fn is_documenttype(&self) -> bool {
*self.type_id() == EventTargetTypeId::Node(NodeTypeId::DocumentType)
}
}
impl DocumentType {
fn new_inherited(name: DOMString,
public_id: Option<DOMString>,
system_id: O... | public_id: DOMString,
system_id: DOMString,
} | random_line_split |
decoder.rs | extern crate jpeg_decoder;
use std::io::Read;
use color::{self, ColorType};
use image::{DecodingResult, ImageDecoder, ImageError, ImageResult};
/// JPEG decoder
pub struct JPEGDecoder<R> {
decoder: jpeg_decoder::Decoder<R>,
metadata: Option<jpeg_decoder::ImageInfo>,
}
impl<R: Read> JPEGDecoder<R> {
/// ... | (&mut self) -> ImageResult<(u32, u32)> {
let metadata = try!(self.metadata());
Ok((u32::from(metadata.width), u32::from(metadata.height)))
}
fn colortype(&mut self) -> ImageResult<ColorType> {
let metadata = try!(self.metadata());
Ok(metadata.pixel_format.into())
}
fn r... | dimensions | identifier_name |
decoder.rs | extern crate jpeg_decoder;
use std::io::Read;
use color::{self, ColorType};
use image::{DecodingResult, ImageDecoder, ImageError, ImageResult};
/// JPEG decoder
pub struct JPEGDecoder<R> {
decoder: jpeg_decoder::Decoder<R>,
metadata: Option<jpeg_decoder::ImageInfo>,
}
impl<R: Read> JPEGDecoder<R> {
/// ... |
}
fn cmyk_to_rgb(input: &[u8]) -> Vec<u8> {
let size = input.len() - input.len() / 4;
let mut output = Vec::with_capacity(size);
for pixel in input.chunks(4) {
let c = f32::from(pixel[0]) / 255.0;
let m = f32::from(pixel[1]) / 255.0;
let y = f32::from(pixel[2]) / 255.0;
le... | {
let mut data = try!(self.decoder.decode());
data = match self.decoder.info().unwrap().pixel_format {
jpeg_decoder::PixelFormat::CMYK32 => cmyk_to_rgb(&data),
_ => data,
};
Ok(DecodingResult::U8(data))
} | identifier_body |
decoder.rs | extern crate jpeg_decoder;
use std::io::Read;
use color::{self, ColorType};
use image::{DecodingResult, ImageDecoder, ImageError, ImageResult};
/// JPEG decoder
pub struct JPEGDecoder<R> {
decoder: jpeg_decoder::Decoder<R>,
metadata: Option<jpeg_decoder::ImageInfo>,
}
impl<R: Read> JPEGDecoder<R> {
/// ... |
output.push(r as u8);
output.push(g as u8);
output.push(b as u8);
}
output
}
impl From<jpeg_decoder::PixelFormat> for ColorType {
fn from(pixel_format: jpeg_decoder::PixelFormat) -> ColorType {
use self::jpeg_decoder::PixelFormat::*;
match pixel_format {
... | let g = (1.0 - m) * 255.0;
let b = (1.0 - y) * 255.0; | random_line_split |
serviceworkerglobalscope.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/. */
use devtools;
use devtools_traits::DevtoolScriptControlMsg;
use dom::abstractworker::WorkerScriptMsg;
use dom::bin... |
let ret = sel.wait();
if ret == worker_handle.id() {
Ok(MixedMessage::FromServiceWorker(worker_port.recv()?))
}else if ret == devtools_handle.id() {
Ok(MixedMessage::FromDevtools(devtools_port.recv()?))
} else if ret == timer_port_handle.id() {
Ok(Mix... | }
timer_port_handle.add();
} | random_line_split |
serviceworkerglobalscope.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/. */
use devtools;
use devtools_traits::DevtoolScriptControlMsg;
use dom::abstractworker::WorkerScriptMsg;
use dom::bin... | (&self) -> Box<ScriptChan + Send> {
Box::new(ServiceWorkerChan {
sender: self.sender.clone(),
})
}
}
#[dom_struct]
pub struct ServiceWorkerGlobalScope {
workerglobalscope: WorkerGlobalScope,
#[ignore_malloc_size_of = "Defined in std"]
receiver: Receiver<ServiceWorkerScriptMs... | clone | identifier_name |
serviceworkerglobalscope.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/. */
use devtools;
use devtools_traits::DevtoolScriptControlMsg;
use dom::abstractworker::WorkerScriptMsg;
use dom::bin... |
impl ServiceWorkerGlobalScopeMethods for ServiceWorkerGlobalScope {
// https://w3c.github.io/ServiceWorker/#service-worker-global-scope-onmessage-attribute
event_handler!(message, GetOnmessage, SetOnmessage);
}
| {
let worker =
DomRoot::downcast::<WorkerGlobalScope>(GlobalScope::from_context(cx))
.expect("global is not a worker scope");
assert!(worker.is::<ServiceWorkerGlobalScope>());
// A false response causes the script to terminate
!worker.is_closing()
} | identifier_body |
connect_ack_flags.rs | use std::io::{Read, Write};
use std::convert::From;
use byteorder::{ReadBytesExt, WriteBytesExt};
use control::variable_header::VariableHeaderError;
use {Encodable, Decodable};
#[derive(Debug, Eq, PartialEq, Copy, Clone)]
pub struct | {
pub session_present: bool,
}
impl ConnackFlags {
pub fn empty() -> ConnackFlags {
ConnackFlags {
session_present: false,
}
}
}
impl<'a> Encodable<'a> for ConnackFlags {
type Err = VariableHeaderError;
fn encode<W: Write>(&self, writer: &mut W) -> Result<(), Variable... | ConnackFlags | identifier_name |
connect_ack_flags.rs | use std::io::{Read, Write};
use std::convert::From;
use byteorder::{ReadBytesExt, WriteBytesExt};
use control::variable_header::VariableHeaderError;
use {Encodable, Decodable};
#[derive(Debug, Eq, PartialEq, Copy, Clone)] | }
impl ConnackFlags {
pub fn empty() -> ConnackFlags {
ConnackFlags {
session_present: false,
}
}
}
impl<'a> Encodable<'a> for ConnackFlags {
type Err = VariableHeaderError;
fn encode<W: Write>(&self, writer: &mut W) -> Result<(), VariableHeaderError> {
let code = ... | pub struct ConnackFlags {
pub session_present: bool, | random_line_split |
connect_ack_flags.rs | use std::io::{Read, Write};
use std::convert::From;
use byteorder::{ReadBytesExt, WriteBytesExt};
use control::variable_header::VariableHeaderError;
use {Encodable, Decodable};
#[derive(Debug, Eq, PartialEq, Copy, Clone)]
pub struct ConnackFlags {
pub session_present: bool,
}
impl ConnackFlags {
pub fn empt... |
}
impl<'a> Decodable<'a> for ConnackFlags {
type Err = VariableHeaderError;
type Cond = ();
fn decode_with<R: Read>(reader: &mut R, _rest: Option<()>) -> Result<ConnackFlags, VariableHeaderError> {
let code = try!(reader.read_u8());
if code &!1!= 0 {
return Err(VariableHeaderE... | {
1
} | identifier_body |
connect_ack_flags.rs | use std::io::{Read, Write};
use std::convert::From;
use byteorder::{ReadBytesExt, WriteBytesExt};
use control::variable_header::VariableHeaderError;
use {Encodable, Decodable};
#[derive(Debug, Eq, PartialEq, Copy, Clone)]
pub struct ConnackFlags {
pub session_present: bool,
}
impl ConnackFlags {
pub fn empt... |
Ok(ConnackFlags {
session_present: code == 1,
})
}
}
| {
return Err(VariableHeaderError::InvalidReservedFlag);
} | conditional_block |
union_in_nested_ns_generated.rs | // automatically generated by the FlatBuffers compiler, do not modify
extern crate flatbuffers;
use std::mem;
use std::cmp::Ordering;
use self::flatbuffers::{EndianScalar, Follow};
use super::*;
#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
pub cons... |
}
impl flatbuffers::SimpleToVerifyInSlice for UnionInNestedNS {}
pub struct UnionInNestedNSUnionTableOffset {}
#[allow(clippy::upper_case_acronyms)]
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq)]
pub enum UnionInNestedNST {
NONE,
TableInNestedNS(Box<TableInNestedNST>),
}
impl Default for UnionInNestedNST {... | {
use self::flatbuffers::Verifiable;
u8::run_verifier(v, pos)
} | identifier_body |
union_in_nested_ns_generated.rs | // automatically generated by the FlatBuffers compiler, do not modify
extern crate flatbuffers;
use std::mem;
use std::cmp::Ordering;
use self::flatbuffers::{EndianScalar, Follow};
use super::*;
#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
pub cons... | (self) -> Option<&'static str> {
match self {
Self::NONE => Some("NONE"),
Self::TableInNestedNS => Some("TableInNestedNS"),
_ => None,
}
}
}
impl std::fmt::Debug for UnionInNestedNS {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
if let Some(name) = self.variant_name... | variant_name | identifier_name |
union_in_nested_ns_generated.rs | // automatically generated by the FlatBuffers compiler, do not modify
extern crate flatbuffers;
use std::mem;
use std::cmp::Ordering;
use self::flatbuffers::{EndianScalar, Follow};
use super::*;
#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
pub cons... | let b = u8::from_le(self.0);
Self(b)
}
}
impl<'a> flatbuffers::Verifiable for UnionInNestedNS {
#[inline]
fn run_verifier(
v: &mut flatbuffers::Verifier, pos: usize
) -> Result<(), flatbuffers::InvalidFlatbuffer> {
use self::flatbuffers::Verifiable;
u8::run_verifier(v, pos)
}
}
impl flat... | }
#[inline]
#[allow(clippy::wrong_self_convention)]
fn from_little_endian(self) -> Self { | random_line_split |
cci_class_6.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 ... | <U> {
priv info : Vec<U>,
priv meows : uint,
how_hungry : int,
}
impl<U> cat<U> {
pub fn speak<T>(&mut self, stuff: Vec<T> ) {
self.meows += stuff.len();
}
pub fn meow_count(&mut self) -> uint { self.meows }
}
pub fn cat<U>(in_x : uint, in_... | cat | identifier_name |
cci_class_6.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 ... |
pub fn meow_count(&mut self) -> uint { self.meows }
}
pub fn cat<U>(in_x : uint, in_y : int, in_info: Vec<U> ) -> cat<U> {
cat {
meows: in_x,
how_hungry: in_y,
info: in_info
}
}
}
| {
self.meows += stuff.len();
} | identifier_body |
cci_class_6.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 ... | how_hungry : int,
}
impl<U> cat<U> {
pub fn speak<T>(&mut self, stuff: Vec<T> ) {
self.meows += stuff.len();
}
pub fn meow_count(&mut self) -> uint { self.meows }
}
pub fn cat<U>(in_x : uint, in_y : int, in_info: Vec<U> ) -> cat<U> {
cat {
... | priv info : Vec<U> ,
priv meows : uint,
| random_line_split |
mod.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file | // "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS,... | // 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 | random_line_split |
macro-meta-items.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | {
// statement
compiles_fine!(baz);
emit!(baz);
println!("{}", MISTYPED);
} | identifier_body | |
macro-meta-items.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT. | // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-pretty - ... | // | random_line_split |
macro-meta-items.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | () {
println!("{}", MISTYPED);
}
pub fn main() {
// statement
compiles_fine!(baz);
emit!(baz);
println!("{}", MISTYPED);
}
| foo | identifier_name |
negative_numbers.rs | /*
* Tests for negative numbers.
*/
extern crate rustyard;
#[test]
fn can_add_two_negative_numbers() {
let mut yard = rustyard::ShuntingYard::new();
assert_eq!(-4f64, yard.calculate("-2 + -2").unwrap());
assert_eq!("-2 + -2 ", yard.to_string_ast());
assert_eq!("-2 -2 + ", yard.to_string()); | fn can_subtract_two_negative_numbers() {
let mut yard = rustyard::ShuntingYard::new();
assert_eq!(0f64, yard.calculate("-2 - -2").unwrap());
assert_eq!("-2 - -2 ", yard.to_string_ast());
assert_eq!("-2 -2 - ", yard.to_string());
}
#[test]
fn can_multiply_two_negative_numbers() {
let mut yard = rus... | }
#[test] | random_line_split |
negative_numbers.rs | /*
* Tests for negative numbers.
*/
extern crate rustyard;
#[test]
fn can_add_two_negative_numbers() {
let mut yard = rustyard::ShuntingYard::new();
assert_eq!(-4f64, yard.calculate("-2 + -2").unwrap());
assert_eq!("-2 + -2 ", yard.to_string_ast());
assert_eq!("-2 -2 + ", yard.to_string());
}
#[te... | () {
let mut yard = rustyard::ShuntingYard::new();
assert_eq!(0f64, yard.calculate("-2 - -2").unwrap());
assert_eq!("-2 - -2 ", yard.to_string_ast());
assert_eq!("-2 -2 - ", yard.to_string());
}
#[test]
fn can_multiply_two_negative_numbers() {
let mut yard = rustyard::ShuntingYard::new();
ass... | can_subtract_two_negative_numbers | identifier_name |
negative_numbers.rs | /*
* Tests for negative numbers.
*/
extern crate rustyard;
#[test]
fn can_add_two_negative_numbers() {
let mut yard = rustyard::ShuntingYard::new();
assert_eq!(-4f64, yard.calculate("-2 + -2").unwrap());
assert_eq!("-2 + -2 ", yard.to_string_ast());
assert_eq!("-2 -2 + ", yard.to_string());
}
#[te... | {
let mut yard = rustyard::ShuntingYard::new();
assert_eq!(10f64, yard.calculate("-20 / -2").unwrap());
assert_eq!("-20 / -2 ", yard.to_string_ast());
assert_eq!("-20 -2 / ", yard.to_string());
} | identifier_body | |
uidmap.rs | use std::cmp::min;
use std::env;
use std::fs::{File};
use std::io::{BufReader, BufRead};
use std::str::FromStr;
use std::str::from_utf8;
use std::path::{Path, PathBuf};
use unshare::{Command, Stdio};
use libc::funcs::posix88::unistd::{geteuid, getegid};
use libc::{uid_t, gid_t};
use config::Range;
use config::Setting... | reqval = match reqiter.next() {
Some(val) => *val,
None => break,
};
}
if allowval.len() == 0 {
allowval = match allowiter.next() {
Some(val) => *val,
None => return Err(()),
};
}
... | {
let mut res = vec!((0, own_id, 1));
let mut reqiter = req.iter();
let mut reqval = *reqiter.next().unwrap();
let mut allowiter = allowed.iter();
let mut allowval = *allowiter.next().unwrap();
loop {
if reqval.start() == 0 {
reqval = reqval.shift(1);
}
if all... | identifier_body |
uidmap.rs | use std::cmp::min;
use std::env;
use std::fs::{File};
use std::io::{BufReader, BufRead};
use std::str::FromStr;
use std::str::from_utf8;
use std::path::{Path, PathBuf};
use unshare::{Command, Stdio};
use libc::funcs::posix88::unistd::{geteuid, getegid};
use libc::{uid_t, gid_t};
use config::Range;
use config::Setting... | {
Singleton(uid_t, gid_t),
Ranges(Vec<(uid_t, uid_t, uid_t)>, Vec<(gid_t, gid_t, gid_t)>),
}
fn read_uid_map(username: &str) -> Result<Vec<Range>,String> {
let file = try_msg!(File::open(&Path::new("/etc/subuid")),
"Can't open /etc/subuid: {err}");
let mut res = Vec::new();
let reader = B... | Uidmap | identifier_name |
uidmap.rs | use std::cmp::min;
use std::env;
use std::fs::{File};
use std::io::{BufReader, BufRead};
use std::str::FromStr;
use std::str::from_utf8;
use std::path::{Path, PathBuf};
use unshare::{Command, Stdio};
use libc::funcs::posix88::unistd::{geteuid, getegid};
use libc::{uid_t, gid_t};
use config::Range;
use config::Setting... | else {
result.push(Range::new(outside, outside+count-1));
}
}
return Ok(result);
}
pub fn map_users(settings: &Settings, uids: &Vec<Range>, gids: &Vec<Range>)
-> Result<Uidmap, String>
{
let default_uids = vec!(Range::new(0, 0));
let default_gids = vec!(Range::new(0, 0));
l... | {
result.push(Range::new(inside, inside+count-1));
} | conditional_block |
uidmap.rs | use std::cmp::min;
use std::env;
use std::fs::{File};
use std::io::{BufReader, BufRead};
use std::str::FromStr;
use std::str::from_utf8;
use std::path::{Path, PathBuf};
use unshare::{Command, Stdio};
use libc::funcs::posix88::unistd::{geteuid, getegid};
use libc::{uid_t, gid_t};
use config::Range;
use config::Setting... | let mut reqval = *reqiter.next().unwrap();
let mut allowiter = allowed.iter();
let mut allowval = *allowiter.next().unwrap();
loop {
if reqval.start() == 0 {
reqval = reqval.shift(1);
}
if allowval.start() == 0 {
allowval = allowval.shift(1);
}
... | random_line_split | |
handle.rs | use std::sync::Arc;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering::SeqCst;
use std::thread::{self, Thread, ThreadId};
use std::time::Instant;
use select::CaseId;
use util::Backoff;
struct Inner {
case_id: AtomicUsize,
thread: Thread,
}
#[derive(Clone)]
pub struct Handle {
inner: Arc... | (&self) -> CaseId {
CaseId::new(self.inner.case_id.load(SeqCst))
}
pub fn wait_until(&self, deadline: Option<Instant>) -> bool {
let mut backoff = Backoff::new();
loop {
if self.selected()!= CaseId::none() {
return true;
}
if!backoff.s... | selected | identifier_name |
handle.rs | use std::sync::Arc;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering::SeqCst;
use std::thread::{self, Thread, ThreadId};
use std::time::Instant;
use select::CaseId;
use util::Backoff;
struct Inner {
case_id: AtomicUsize,
thread: Thread,
}
#[derive(Clone)]
pub struct Handle {
inner: Arc... | self.inner
.case_id
.compare_and_swap(CaseId::none().id, case_id.id, SeqCst) == CaseId::none().id
}
pub fn unpark(&self) {
self.inner.thread.unpark();
}
pub fn thread_id(&self) -> ThreadId {
self.inner.thread.id()
}
pub fn reset(&self) {
s... | pub fn try_select(&self, case_id: CaseId) -> bool { | random_line_split |
handle.rs | use std::sync::Arc;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering::SeqCst;
use std::thread::{self, Thread, ThreadId};
use std::time::Instant;
use select::CaseId;
use util::Backoff;
struct Inner {
case_id: AtomicUsize,
thread: Thread,
}
#[derive(Clone)]
pub struct Handle {
inner: Arc... |
pub fn reset(&self) {
self.inner.case_id.store(0, SeqCst);
}
pub fn selected(&self) -> CaseId {
CaseId::new(self.inner.case_id.load(SeqCst))
}
pub fn wait_until(&self, deadline: Option<Instant>) -> bool {
let mut backoff = Backoff::new();
loop {
if sel... | {
self.inner.thread.id()
} | identifier_body |
path_finding.rs | use cgmath::Point2;
use pathfinding::{directed::astar::astar, utils::absdiff};
use crate::game::constants::{TILES_PCS_H, TILES_PCS_W, TERRAIN_OBJECTS};
use crate::game::get_rand_from_range;
use crate::graphics::coords_to_tile;
use crate::shaders::Position;
fn neighbours<'c>(curr_pos: Point2<i32>, impassable_tiles: &[... | (-1, -1) => 90,
(0, -1) => 45,
(1, -1) => 0,
_ => get_rand_from_range(0, 359),
}
}
| {
let next_step: Point2<i32> = calc_route(start_point, end_point, &TERRAIN_OBJECTS.to_vec())
.map_or_else(|| Point2::new(0, 0),
|(route, ..)| {
if route.len() > 1 {
route[1]
} else {
route[0]
}
... | identifier_body |
path_finding.rs | use cgmath::Point2;
use pathfinding::{directed::astar::astar, utils::absdiff};
use crate::game::constants::{TILES_PCS_H, TILES_PCS_W, TERRAIN_OBJECTS};
use crate::game::get_rand_from_range;
use crate::graphics::coords_to_tile;
use crate::shaders::Position;
fn neighbours<'c>(curr_pos: Point2<i32>, impassable_tiles: &[... |
match diff {
(1, 0) => 315,
(1, 1) => 270,
(0, 1) => 225,
(-1, 1) => 180,
(-1, 0) => 135,
(-1, -1) => 90,
(0, -1) => 45,
(1, -1) => 0,
_ => get_rand_from_range(0, 359),
}
} | random_line_split | |
path_finding.rs | use cgmath::Point2;
use pathfinding::{directed::astar::astar, utils::absdiff};
use crate::game::constants::{TILES_PCS_H, TILES_PCS_W, TERRAIN_OBJECTS};
use crate::game::get_rand_from_range;
use crate::graphics::coords_to_tile;
use crate::shaders::Position;
fn neighbours<'c>(curr_pos: Point2<i32>, impassable_tiles: &[... | (p: Point2<i32>, impassable_tiles: &[[i32; 2]]) -> Vec<(Point2<i32>, i32)> {
neighbours(p, &impassable_tiles, &mut vec![])
.iter()
.map(|p| (**p, 1))
.collect()
}
fn find_next_best_endpoint<'c>(end_point: &'c Point2<i32>, impassable_tiles: &[[i32; 2]], neighbour_tiles: &'c mut Vec<Point2<i32>>) -> &'c Point... | tiles | identifier_name |
world.rs | // state/world.rs -- top level state object
// Copyright (C) 2015 Alex Iadicicco <http://ajitek.net>
//
// This file is part of ircd-oxide and is protected under the terms contained in
// the COPYING file in the project root.
//! The top level state object
use std::borrow::Borrow;
use std::collections::HashMap;
use ... |
}
fn nickname_owner(&self, nick: &String) -> Option<&Id<Identity>> {
self.world.nicknames.owner(nick)
}
fn nickname(&self, owner: &Id<Identity>) -> Option<&String> {
self.world.nicknames.active(owner).map(|n| &n.0)
}
fn channel_name_owner(&self, name: &String) -> Option<&Id<C... | {
let cu = self.world.chanusers.join(chan, user);
self.changes.added(&*cu);
} | conditional_block |
world.rs | // state/world.rs -- top level state object
// Copyright (C) 2015 Alex Iadicicco <http://ajitek.net>
//
// This file is part of ircd-oxide and is protected under the terms contained in
// the COPYING file in the project root.
//! The top level state object
use std::borrow::Borrow;
use std::collections::HashMap;
use ... | /// Claims a name for a channel. Returns whether the claim was successful.
fn channel_claim(&mut self, owner: Id<Channel>, name: String) -> bool {
self.world.channames.claim(owner, Channame(name))
}
/// Changes a channel's active name. Returns whether the operation was successful.
fn channe... | self.world.channels.insert(id.clone(), channel);
id
}
| random_line_split |
world.rs | // state/world.rs -- top level state object
// Copyright (C) 2015 Alex Iadicicco <http://ajitek.net>
//
// This file is part of ircd-oxide and is protected under the terms contained in
// the COPYING file in the project root.
//! The top level state object
use std::borrow::Borrow;
use std::collections::HashMap;
use ... | (&mut self, chan: Id<Channel>, user: Id<Identity>) {
if self.world.chanusers.get(&chan, &user).is_none() {
let cu = self.world.chanusers.join(chan, user);
self.changes.added(&*cu);
}
}
fn nickname_owner(&self, nick: &String) -> Option<&Id<Identity>> {
self.world.... | channel_user_add | identifier_name |
world.rs | // state/world.rs -- top level state object
// Copyright (C) 2015 Alex Iadicicco <http://ajitek.net>
//
// This file is part of ircd-oxide and is protected under the terms contained in
// the COPYING file in the project root.
//! The top level state object
use std::borrow::Borrow;
use std::collections::HashMap;
use ... |
/// Claims a name for a channel. Returns whether the claim was successful.
fn channel_claim(&mut self, owner: Id<Channel>, name: String) -> bool {
self.world.channames.claim(owner, Channame(name))
}
/// Changes a channel's active name. Returns whether the operation was successful.
fn chan... | {
let id = self.world.idgen_channel.next();
let channel = Channel::new(id.clone());
self.changes.added(&channel);
self.world.channels.insert(id.clone(), channel);
id
} | identifier_body |
tree.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/. */
//! Traits that nodes must implement. Breaks the otherwise-cyclic dependency
//! between layout and style.
use c... | /// Converts self into an opaque representation.
fn opaque(&self) -> OpaqueElement;
fn parent_element(&self) -> Option<Self>;
/// Whether the parent node of this element is a shadow root.
fn parent_node_is_shadow_root(&self) -> bool;
/// The host of the containing shadow root, if any.
fn ... |
pub trait Element: Sized + Clone + Debug {
type Impl: SelectorImpl;
| random_line_split |
tree.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/. */
//! Traits that nodes must implement. Breaks the otherwise-cyclic dependency
//! between layout and style.
use c... |
/// Whether we're matching on a pseudo-element.
fn is_pseudo_element(&self) -> bool;
/// Skips non-element nodes
fn prev_sibling_element(&self) -> Option<Self>;
/// Skips non-element nodes
fn next_sibling_element(&self) -> Option<Self>;
fn is_html_element_in_html_document(&self) -> bool... | {
debug_assert!(self.is_pseudo_element());
self.parent_element()
} | identifier_body |
tree.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/. */
//! Traits that nodes must implement. Breaks the otherwise-cyclic dependency
//! between layout and style.
use c... | (&self) -> Option<Self> {
None
}
fn has_id(
&self,
id: &<Self::Impl as SelectorImpl>::Identifier,
case_sensitivity: CaseSensitivity,
) -> bool;
fn has_class(
&self,
name: &<Self::Impl as SelectorImpl>::ClassName,
case_sensitivity: CaseSensitivity... | assigned_slot | identifier_name |
pixel_ops.rs | use criterion::{black_box, criterion_group, criterion_main, Criterion};
use librsvg::surface_utils::{Pixel, PixelOps};
const OTHER: Pixel = Pixel {
r: 0x10,
g: 0x20,
b: 0x30,
a: 0x40,
};
const N: usize = 1024;
fn make_pixels(n: usize) -> Vec<Pixel> {
(0..n)
.map(|i| Pixel {
r: ... | (c: &mut Criterion) {
c.bench_function("pixel_diff", |b| {
let pixels = black_box(make_pixels(N));
let other = black_box(OTHER);
b.iter(|| bench_op(&pixels, |pixel| pixel.diff(&other)))
});
c.bench_function("pixel_to_luminance_mask", |b| {
let pixels = black_box(make_pixels(... | bench_pixel_ops | identifier_name |
pixel_ops.rs | use criterion::{black_box, criterion_group, criterion_main, Criterion};
use librsvg::surface_utils::{Pixel, PixelOps};
const OTHER: Pixel = Pixel {
r: 0x10,
g: 0x20,
b: 0x30,
a: 0x40,
};
const N: usize = 1024;
fn make_pixels(n: usize) -> Vec<Pixel> |
fn bench_op<F>(pixels: &[Pixel], op: F)
where
F: Fn(&Pixel) -> Pixel,
{
let result: Vec<Pixel> = pixels.iter().map(op).collect();
black_box(result);
}
fn bench_pixel_ops(c: &mut Criterion) {
c.bench_function("pixel_diff", |b| {
let pixels = black_box(make_pixels(N));
let other = black... | {
(0..n)
.map(|i| Pixel {
r: (i / 2) as u8,
g: (i / 3) as u8,
b: (i / 4) as u8,
a: i as u8,
})
.collect()
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.