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 |
|---|---|---|---|---|
v6Data.rs | pub fn | () -> [f64; 81] {
let mut v6List: [f64; 81] = [0.0; 81];
// index is wavelengths of light, stepped by 5, from 380 to 780
v6List[0] = -0.0809279;
v6List[1] = -0.0830999;
v6List[2] = -0.0746431;
v6List[3] = -0.0487062;
v6List[4] = -0.0232402;
v6List[5] = 0.000270005;
v6List[6] = 0.015... | v6Data | identifier_name |
v6Data.rs | pub fn v6Data() -> [f64; 81] | v6List[16] = -0.128604;
v6List[17] = -0.114038;
v6List[18] = -0.103359;
v6List[19] = -0.0675493;
v6List[20] = -0.0231118;
v6List[21] = 0.0393885;
v6List[22] = 0.0926205;
v6List[23] = 0.177201;
v6List[24] = 0.153455;
v6List[25] = 0.0860555;
v6List[26] = 0.219497;
v6List[27... | {
let mut v6List: [f64; 81] = [0.0; 81];
// index is wavelengths of light, stepped by 5, from 380 to 780
v6List[0] = -0.0809279;
v6List[1] = -0.0830999;
v6List[2] = -0.0746431;
v6List[3] = -0.0487062;
v6List[4] = -0.0232402;
v6List[5] = 0.000270005;
v6List[6] = 0.0151724;
v6List... | identifier_body |
v6Data.rs | pub fn v6Data() -> [f64; 81] {
let mut v6List: [f64; 81] = [0.0; 81];
// index is wavelengths of light, stepped by 5, from 380 to 780
v6List[0] = -0.0809279;
v6List[1] = -0.0830999;
v6List[2] = -0.0746431;
v6List[3] = -0.0487062;
v6List[4] = -0.0232402;
v6List[5] = 0.000270005;
v6Li... | v6List[40] = 0.0477786;
v6List[41] = 0.116347;
v6List[42] = 0.196124;
v6List[43] = 0.204762;
v6List[44] = 0.235425;
v6List[45] = 0.202082;
v6List[46] = 0.160728;
v6List[47] = 0.0858789;
v6List[48] = 0.115125;
v6List[49] = 0.0809753;
v6List[50] = -0.0104571;
v6List[51] = -... | v6List[36] = -0.223687;
v6List[37] = -0.107916;
v6List[38] = -0.126467;
v6List[39] = -0.0135333; | random_line_split |
main.rs | use std::io::BufReader;
use std::fs::File;
use std::str::FromStr;
use std::io;
use std::io::prelude::*;
use std::collections::BinaryHeap;
use std::cmp::Reverse;
#[derive(Debug)]
struct MaxHeap{
heap:BinaryHeap<u64>,
count: usize
}
impl MaxHeap {
fn | () -> MaxHeap{
let heap = BinaryHeap::new();
let count = 0;
MaxHeap {
heap,
count
}
}
fn push(&mut self, new_value: u64) {
self.count = self.count + 1;
self.heap.push(new_value);
}
fn top(&self) -> u64 {
let v = self.heap.... | new | identifier_name |
main.rs | use std::io::BufReader;
use std::fs::File;
use std::str::FromStr;
use std::io;
use std::io::prelude::*;
use std::collections::BinaryHeap;
use std::cmp::Reverse;
#[derive(Debug)]
struct MaxHeap{
heap:BinaryHeap<u64>,
count: usize
}
impl MaxHeap {
fn new() -> MaxHeap |
fn push(&mut self, new_value: u64) {
self.count = self.count + 1;
self.heap.push(new_value);
}
fn top(&self) -> u64 {
let v = self.heap.peek().expect("max heap underflow");
v.clone()
}
fn pop(&mut self) -> u64 {
let v = self.heap.pop().expect("max heap... | {
let heap = BinaryHeap::new();
let count = 0;
MaxHeap {
heap,
count
}
} | identifier_body |
main.rs | use std::io::BufReader;
use std::fs::File;
use std::str::FromStr;
use std::io;
use std::io::prelude::*;
use std::collections::BinaryHeap;
use std::cmp::Reverse;
#[derive(Debug)]
struct MaxHeap{
heap:BinaryHeap<u64>,
count: usize
}
impl MaxHeap {
fn new() -> MaxHeap{
let heap = BinaryHeap::new();
... |
else {
if max_heap.count > min_heap.count {
let mut diff = max_heap.count - min_heap.count;
while diff > 1 {
let v = max_heap.pop();
min_heap.push(v);
diff = max_heap.count - min_heap.count;
}
}
}
}
/*
#[test]
... | {
let mut diff = min_heap.count - max_heap.count;
while diff > 1 {
let v = min_heap.pop();
max_heap.push(v);
diff = min_heap.count - max_heap.count;
}
} | conditional_block |
main.rs | use std::io::BufReader;
use std::fs::File;
use std::str::FromStr;
use std::io;
use std::io::prelude::*;
use std::collections::BinaryHeap;
use std::cmp::Reverse;
#[derive(Debug)]
struct MaxHeap{
heap:BinaryHeap<u64>,
count: usize
}
impl MaxHeap {
fn new() -> MaxHeap{
let heap = BinaryHeap::new();
... | let mut v = Vec::new();
for line in reader.lines() {
let line = line.unwrap();
let value = u64::from_str(&line).expect("error parsing value");
v.push(value);
}
Ok(median_sum(&v))
}
fn main() {
for arg in std::env::args().skip(1) {
let value = print_medians(&arg)... | let f = File::open(file_name)?;
let reader = BufReader::new(f); | random_line_split |
mod.rs | use ffmpeg::frame;
use openal::{Error, Listener};
use openal::source::{self, Stream};
use game::State;
use settings;
pub struct Sound<'a> {
settings: settings::Audio,
music: Option<Stream<'a>>,
timestamp: i64,
listener: Listener<'a>,
}
impl<'a> Sound<'a> {
pub fn new(settings: &settings::Audio) -> Result<... |
}
| {
} | identifier_body |
mod.rs | use ffmpeg::frame;
use openal::{Error, Listener};
use openal::source::{self, Stream};
use game::State;
use settings;
pub struct Sound<'a> {
settings: settings::Audio,
music: Option<Stream<'a>>,
timestamp: i64,
listener: Listener<'a>,
}
impl<'a> Sound<'a> {
pub fn new(settings: &settings::Audio) -> Result<... | (&mut self, state: &State) {
}
}
| render | identifier_name |
mod.rs | use ffmpeg::frame;
use openal::{Error, Listener};
use openal::source::{self, Stream};
use game::State;
use settings;
pub struct Sound<'a> {
settings: settings::Audio,
music: Option<Stream<'a>>,
timestamp: i64,
listener: Listener<'a>,
}
impl<'a> Sound<'a> {
pub fn new(settings: &settings::Audio) -> Result<... |
if self.timestamp >= frame.timestamp().unwrap() {
return;
}
self.timestamp = frame.timestamp().unwrap();
if let Some(source) = self.music.as_mut() {
source.push(frame.channels(), frame.plane::<i16>(0), frame.rate()).unwrap();
if source.state()!= source::State::Playing {
source.play();
}
}... | {
self.music = Some(self.listener.source().unwrap().stream());
} | conditional_block |
mod.rs | use ffmpeg::frame;
use openal::{Error, Listener};
use openal::source::{self, Stream};
use game::State;
use settings;
pub struct Sound<'a> {
settings: settings::Audio,
music: Option<Stream<'a>>,
timestamp: i64,
listener: Listener<'a>,
}
impl<'a> Sound<'a> {
pub fn new(settings: &settings::Audio) -> Result<... |
pub fn render(&mut self, state: &State) {
}
} | random_line_split | |
parser.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.
*/
// Nom parser for Mercurial revlogs
use std::fmt::Debug;
use std::io::Read;
use bitflags::bitflags;
use flate2::read::ZlibDecoder;
use no... | named!(remains_owned<Vec<u8>>, map!(remains, |x: &[u8]| x.into()));
// Parse some literal data, possibly compressed
named!(pub literal<Vec<u8> >,
alt!(
do_parse!(peek!(tag!(b"\0")) >> d: remains >> (d.into())) |
do_parse!(peek!(tag!(b"x")) >> d: apply!(zlib_decompress, remains_owned) >> (d)) |
... | random_line_split | |
parser.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.
*/
// Nom parser for Mercurial revlogs
use std::fmt::Debug;
use std::io::Read;
use bitflags::bitflags;
use flate2::read::ZlibDecoder;
use no... | () -> usize {
6 + 2 + 4 + 4 + 4 + 4 + 4 + 4 + 32
}
// Parse an "NG" revlog entry
named!(pub indexng<Entry>,
do_parse!(
offset: return_error!(ErrorKind::Custom(Badness::IO), be_u48) >> // XXX if first, then only 2 bytes, implied 0 in top 4
flags: return_error!(ErrorKind::Custom(Badness::IO), ... | indexng_size | identifier_name |
parser.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.
*/
// Nom parser for Mercurial revlogs
use std::fmt::Debug;
use std::io::Read;
use bitflags::bitflags;
use flate2::read::ZlibDecoder;
use no... |
// Parse an "NG" revlog entry
named!(pub indexng<Entry>,
do_parse!(
offset: return_error!(ErrorKind::Custom(Badness::IO), be_u48) >> // XXX if first, then only 2 bytes, implied 0 in top 4
flags: return_error!(ErrorKind::Custom(Badness::IO), be_u16) >> //?
compressed_length: return_e... | {
6 + 2 + 4 + 4 + 4 + 4 + 4 + 4 + 32
} | identifier_body |
coverageinfo.rs | use crate::traits::*;
use rustc_middle::mir::coverage::*;
use rustc_middle::mir::Coverage;
use rustc_middle::mir::SourceScope;
use super::FunctionCx;
impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
pub fn codegen_coverage(&self, bx: &mut Bx, coverage: Coverage, scope: SourceScope) {
... | );
}
}
}
} | }
CoverageKind::Unreachable => {
bx.add_coverage_unreachable(
instance,
code_region.expect("unreachable regions always have code regions"), | random_line_split |
coverageinfo.rs | use crate::traits::*;
use rustc_middle::mir::coverage::*;
use rustc_middle::mir::Coverage;
use rustc_middle::mir::SourceScope;
use super::FunctionCx;
impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
pub fn codegen_coverage(&self, bx: &mut Bx, coverage: Coverage, scope: SourceScope) | // but do inject the counter intrinsic.
bx.add_coverage_counter(instance, id, code_region);
}
let coverageinfo = bx.tcx().coverageinfo(instance.def);
let fn_name = bx.get_pgo_func_name_var(instance);
... | {
// Determine the instance that coverage data was originally generated for.
let scope_data = &self.mir.source_scopes[scope];
let instance = if let Some((inlined_instance, _)) = scope_data.inlined {
self.monomorphize(inlined_instance)
} else if let Some(inlined_scope) = scope... | identifier_body |
coverageinfo.rs | use crate::traits::*;
use rustc_middle::mir::coverage::*;
use rustc_middle::mir::Coverage;
use rustc_middle::mir::SourceScope;
use super::FunctionCx;
impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
pub fn | (&self, bx: &mut Bx, coverage: Coverage, scope: SourceScope) {
// Determine the instance that coverage data was originally generated for.
let scope_data = &self.mir.source_scopes[scope];
let instance = if let Some((inlined_instance, _)) = scope_data.inlined {
self.monomorphize(inline... | codegen_coverage | identifier_name |
coverageinfo.rs | use crate::traits::*;
use rustc_middle::mir::coverage::*;
use rustc_middle::mir::Coverage;
use rustc_middle::mir::SourceScope;
use super::FunctionCx;
impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
pub fn codegen_coverage(&self, bx: &mut Bx, coverage: Coverage, scope: SourceScope) {
... | bx.instrprof_increment(fn_name, hash, num_counters, index);
}
}
CoverageKind::Expression { id, lhs, op, rhs } => {
bx.add_coverage_counter_expression(instance, id, lhs, op, rhs, code_region);
}
CoverageKind::Unreachable... | {
// If `set_function_source_hash()` returned true, the coverage map is enabled,
// so continue adding the counter.
if let Some(code_region) = code_region {
// Note: Some counters do not have code regions, but may still be referenced
... | conditional_block |
eth.rs | // Copyright 2015-2017 Parity Technologies (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 lat... | (&self, _: String) -> Result<Bytes> {
Err(errors::deprecated("Compilation of LLL via RPC is deprecated".to_string()))
}
fn compile_serpent(&self, _: String) -> Result<Bytes> {
Err(errors::deprecated("Compilation of Serpent via RPC is deprecated".to_string()))
}
fn compile_solidity(&self, _: String) -> Result<... | compile_lll | identifier_name |
eth.rs | // Copyright 2015-2017 Parity Technologies (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 lat... |
fn transaction_by_block_number_and_index(&self, num: BlockNumber, idx: Index) -> BoxFuture<Option<Transaction>> {
let eip86 = self.client.eip86_transition();
Box::new(self.fetcher().block(num.into()).map(move |block| {
light_fetch::extract_transaction_at_index(block, idx.value(), eip86)
}))
}
fn transact... | {
let eip86 = self.client.eip86_transition();
Box::new(self.fetcher().block(BlockId::Hash(hash.into())).map(move |block| {
light_fetch::extract_transaction_at_index(block, idx.value(), eip86)
}))
} | identifier_body |
eth.rs | // Copyright 2015-2017 Parity Technologies (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 lat... | let hash = hash.into();
let eip86 = self.client.eip86_transition();
{
let tx_queue = self.transaction_queue.read();
if let Some(tx) = tx_queue.get(&hash) {
return Box::new(future::ok(Some(Transaction::from_pending(
tx.clone(),
self.client.chain_info().best_block_number,
eip86,
))));
... | }
}))
}
fn transaction_by_hash(&self, hash: RpcH256) -> BoxFuture<Option<Transaction>> { | random_line_split |
cache_generate_metadata.rs | use anyhow::Result;
use clap::{App, Arg};
use std::path::Path;
use std::process;
use std::sync::Arc;
use crate::cache::metadata_generator::*;
use crate::io_engine::{AsyncIoEngine, IoEngine, SyncIoEngine};
//------------------------------------------
const MAX_CONCURRENT_IO: u32 = 1024;
//---------------------------... | else {
commit_new_transaction()?;
}
Ok(())
}
//------------------------------------------
pub fn run(args: &[std::ffi::OsString]) {
let parser = App::new("cache_generate_metadata")
.color(clap::ColorChoice::Never)
.version(crate::version::tools_version())
.about("A tool for ... | {
set_needs_check(engine)?;
} | conditional_block |
cache_generate_metadata.rs | use anyhow::Result;
use clap::{App, Arg};
use std::path::Path;
use std::process;
use std::sync::Arc;
use crate::cache::metadata_generator::*;
use crate::io_engine::{AsyncIoEngine, IoEngine, SyncIoEngine};
//------------------------------------------
const MAX_CONCURRENT_IO: u32 = 1024;
//---------------------------... | (opts: &CacheGenerateOpts) -> Result<()> {
let engine: Arc<dyn IoEngine + Send + Sync> = if opts.async_io {
Arc::new(AsyncIoEngine::new(opts.output, MAX_CONCURRENT_IO, true)?)
} else {
let nr_threads = std::cmp::max(8, num_cpus::get() * 2);
Arc::new(SyncIoEngine::new(opts.output, nr_thre... | generate_metadata | identifier_name |
cache_generate_metadata.rs | use anyhow::Result;
use clap::{App, Arg};
use std::path::Path;
use std::process;
use std::sync::Arc;
use crate::cache::metadata_generator::*;
use crate::io_engine::{AsyncIoEngine, IoEngine, SyncIoEngine};
//------------------------------------------
const MAX_CONCURRENT_IO: u32 = 1024;
//---------------------------... | let parser = App::new("cache_generate_metadata")
.color(clap::ColorChoice::Never)
.version(crate::version::tools_version())
.about("A tool for creating synthetic cache metadata.")
// flags
.arg(
Arg::new("ASYNC_IO")
.help("Force use of io_uring for sync... | pub fn run(args: &[std::ffi::OsString]) { | random_line_split |
client.rs | use std::env;
use std::time::Duration;
use once_cell::sync::OnceCell;
use reqwest::{
self,
header::{HeaderValue, CONTENT_TYPE},
};
use thiserror::Error;
use crate::feed::Rss;
static RESP_SIZE_LIMIT: OnceCell<u64> = OnceCell::new();
static CLIENT: OnceCell<reqwest::Client> = OnceCell::new();
#[derive(Error, ... |
if env::var("RSSBOT_DONT_PROXY_FEEDS")
.or_else(|_| env::var("rssbot_dont_proxy_feeds"))
.is_ok()
{
client_builder = client_builder.no_proxy();
}
let client = client_builder.build().unwrap();
CLIENT.set(client).expect("CLIENT already initialized");
RESP_SIZE_LIMIT
... | {
let mut headers = reqwest::header::HeaderMap::new();
let ua = format!(
concat!(
env!("CARGO_PKG_NAME"),
"/",
env!("CARGO_PKG_VERSION"),
" (+https://t.me/{})"
),
bot_name
);
headers.insert(
reqwest::header::USER_AGENT,
... | identifier_body |
client.rs | use std::env;
use std::time::Duration;
use once_cell::sync::OnceCell;
use reqwest::{
self,
header::{HeaderValue, CONTENT_TYPE},
};
use thiserror::Error;
use crate::feed::Rss;
static RESP_SIZE_LIMIT: OnceCell<u64> = OnceCell::new();
static CLIENT: OnceCell<reqwest::Client> = OnceCell::new();
#[derive(Error, ... | (value: &HeaderValue) -> bool {
value
.to_str()
.map(|value| {
value
.split(';')
.map(|v| v.trim())
.any(|v| v == "application/json")
})
.unwrap_or(false)
}
/// About the "kiB" not "KiB": https://en.wikipedia.org/wiki/Metric_pref... | content_type_is_json | identifier_name |
client.rs | use std::env;
use std::time::Duration;
use once_cell::sync::OnceCell;
use reqwest::{
self,
header::{HeaderValue, CONTENT_TYPE}, | use thiserror::Error;
use crate::feed::Rss;
static RESP_SIZE_LIMIT: OnceCell<u64> = OnceCell::new();
static CLIENT: OnceCell<reqwest::Client> = OnceCell::new();
#[derive(Error, Debug)]
pub enum FeedError {
#[error("network error")]
Network(#[from] reqwest::Error),
#[error("feed parsing failed")]
Pars... | }; | random_line_split |
bthsdpdef.rs | // 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.
// All files in the project carrying such notice may not be copied, modified, or distributed
// except according ... | SDP_TYPE_INT = 0x02,
SDP_TYPE_UUID = 0x03,
SDP_TYPE_STRING = 0x04,
SDP_TYPE_BOOLEAN = 0x05,
SDP_TYPE_SEQUENCE = 0x06,
SDP_TYPE_ALTERNATIVE = 0x07,
SDP_TYPE_URL = 0x08,
SDP_TYPE_CONTAINER = 0x20,
}}
ENUM!{enum SDP_SPECIFICTYPE {
SDP_ST_NONE = 0x0000,
SDP_ST_UINT8 = 0x0010,
SDP... | pub type PSDP_ERROR = *mut USHORT;
ENUM!{enum SDP_TYPE {
SDP_TYPE_NIL = 0x00,
SDP_TYPE_UINT = 0x01, | random_line_split |
prepare.rs | use std::env;
use std::ffi::OsStr;
use std::ffi::OsString;
use std::fs;
use std::path::Path;
use std::process::Command;
use crate::rustc_info::{get_file_name, get_rustc_path, get_rustc_version};
use crate::utils::{copy_dir_recursively, spawn_and_wait};
pub(crate) fn prepare() {
prepare_sysroot();
eprintln!("... | {
for patch in get_patches(crate_name) {
eprintln!("[PATCH] {:?} <- {:?}", target_dir.file_name().unwrap(), patch);
let patch_arg = env::current_dir().unwrap().join("patches").join(patch);
let mut apply_patch_cmd = Command::new("git");
apply_patch_cmd.arg("am").arg(patch_arg).arg("-q... | identifier_body | |
prepare.rs | use std::env;
use std::ffi::OsStr;
use std::ffi::OsString;
use std::fs;
use std::path::Path;
use std::process::Command;
use crate::rustc_info::{get_file_name, get_rustc_path, get_rustc_version};
use crate::utils::{copy_dir_recursively, spawn_and_wait};
pub(crate) fn prepare() {
prepare_sysroot();
eprintln!("... | () {
let rustc_path = get_rustc_path();
let sysroot_src_orig = rustc_path.parent().unwrap().join("../lib/rustlib/src/rust");
let sysroot_src = env::current_dir().unwrap().join("build_sysroot").join("sysroot_src");
assert!(sysroot_src_orig.exists());
if sysroot_src.exists() {
fs::remove_dir... | prepare_sysroot | identifier_name |
prepare.rs | use std::env;
use std::ffi::OsStr;
use std::ffi::OsString;
use std::fs;
use std::path::Path;
use std::process::Command;
use crate::rustc_info::{get_file_name, get_rustc_path, get_rustc_version};
use crate::utils::{copy_dir_recursively, spawn_and_wait};
pub(crate) fn prepare() {
prepare_sysroot();
eprintln!("... |
clone_repo(
"simple-raytracer",
"https://github.com/ebobby/simple-raytracer",
"804a7a21b9e673a482797aa289a18ed480e4d813",
);
eprintln!("[LLVM BUILD] simple-raytracer");
let mut build_cmd = Command::new("cargo");
build_cmd.arg("build").env_remove("CARGO_TARGET_DIR").current_... | "8cf7a62e5d2552961df51e5200aaa5b7c890a4bf",
);
apply_patches("portable-simd", Path::new("portable-simd")); | random_line_split |
prepare.rs | use std::env;
use std::ffi::OsStr;
use std::ffi::OsString;
use std::fs;
use std::path::Path;
use std::process::Command;
use crate::rustc_info::{get_file_name, get_rustc_path, get_rustc_version};
use crate::utils::{copy_dir_recursively, spawn_and_wait};
pub(crate) fn prepare() {
prepare_sysroot();
eprintln!("... |
fs::create_dir_all(sysroot_src.join("library")).unwrap();
eprintln!("[COPY] sysroot src");
copy_dir_recursively(&sysroot_src_orig.join("library"), &sysroot_src.join("library"));
let rustc_version = get_rustc_version();
fs::write(Path::new("build_sysroot").join("rustc_version"), &rustc_version).unw... | {
fs::remove_dir_all(&sysroot_src).unwrap();
} | conditional_block |
hough_transform.rs | // Implements http://rosettacode.org/wiki/Hough_transform
//
// Contributed by Gavin Baker <gavinb@antonym.org>
// Adapted from the Go version
use std::io::{BufReader, BufRead, BufWriter, Write, Read};
use std::fs::File;
use std::iter::repeat;
// Simple 8-bit grayscale image
struct ImageGray8 {
width: usize,
... |
// Transform extents
let rmax = (in_width as f64).hypot(in_height as f64);
let dr = rmax / (out_height/2) as f64;
let dth = std::f64::consts::PI / out_width as f64;
// Process input image in raster order
for y in (0..in_height) {
for x in (0..in_width) {
let in_idx = y*in... | data: repeat(255).take(out_width*out_height).collect(),
}; | random_line_split |
hough_transform.rs | // Implements http://rosettacode.org/wiki/Hough_transform
//
// Contributed by Gavin Baker <gavinb@antonym.org>
// Adapted from the Go version
use std::io::{BufReader, BufRead, BufWriter, Write, Read};
use std::fs::File;
use std::iter::repeat;
// Simple 8-bit grayscale image
struct ImageGray8 {
width: usize,
... | () {
let image = load_pgm("../src/resources/Pentagon.pgm");
let accum = hough(&image, 460, 360);
save_pgm(&accum, "hough.pgm");
}
| main | identifier_name |
hough_transform.rs | // Implements http://rosettacode.org/wiki/Hough_transform
//
// Contributed by Gavin Baker <gavinb@antonym.org>
// Adapted from the Go version
use std::io::{BufReader, BufRead, BufWriter, Write, Read};
use std::fs::File;
use std::iter::repeat;
// Simple 8-bit grayscale image
struct ImageGray8 {
width: usize,
... | let width = width_in.trim().parse::<usize>().unwrap();
let height: usize = height_in.trim().parse::<usize>().unwrap();
println!("Reading pgm file {}: {} x {}", filename, width, height);
// Create image and allocate buffer
let mut img = ImageGray8 {
width: width,
height: height,
... | {
// Open file
let mut file = BufReader::new(File::open(filename).unwrap());
// Read header
let mut magic_in = String::new();
let _ = file.read_line(&mut magic_in).unwrap();
let mut width_in = String::new();
let _ = file.read_line(&mut width_in).unwrap();
let mut height_in = String::ne... | identifier_body |
vrstageparameters.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 core::nonzero::NonZero;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::VRStagePara... | (parameters: WebVRStageParameters, global: &GlobalScope) -> Root<VRStageParameters> {
reflect_dom_object(box VRStageParameters::new_inherited(parameters, global),
global,
VRStageParametersBinding::Wrap)
}
#[allow(unsafe_code)]
pub fn update(&sel... | new | identifier_name |
vrstageparameters.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 core::nonzero::NonZero;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::VRStagePara... |
// https://w3c.github.io/webvr/#dom-vrstageparameters-sizez
fn SizeZ(&self) -> Finite<f32> {
Finite::wrap(self.parameters.borrow().size_z)
}
}
| {
Finite::wrap(self.parameters.borrow().size_x)
} | identifier_body |
vrstageparameters.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 core::nonzero::NonZero;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::VRStagePara... | }
impl VRStageParametersMethods for VRStageParameters {
#[allow(unsafe_code)]
// https://w3c.github.io/webvr/#dom-vrstageparameters-sittingtostandingtransform
unsafe fn SittingToStandingTransform(&self, _cx: *mut JSContext) -> NonZero<*mut JSObject> {
NonZero::new(self.transform.get())
}
/... | }
*self.parameters.borrow_mut() = parameters.clone();
} | random_line_split |
deque.rs | on `swap_buffer`
// FIXME: all atomic operations in this module use a SeqCst ordering. That is
// probably overkill
use core::prelude::*;
use alloc::arc::Arc;
use alloc::heap::{allocate, deallocate};
use alloc::boxed::Box;
use collections::{Vec, MutableSeq};
use core::kinds::marker;
use core::mem::{forget, min... | else {
self.bottom.store(t + 1, SeqCst);
forget(data); // someone else stole this value
return None;
}
}
unsafe fn steal(&self) -> Stolen<T> {
let t = self.top.load(SeqCst);
let old = self.array.load(SeqCst);
let b = self.bottom.load(SeqCst);... | {
self.bottom.store(t + 1, SeqCst);
return Some(data);
} | conditional_block |
deque.rs | on `swap_buffer`
// FIXME: all atomic operations in this module use a SeqCst ordering. That is
// probably overkill
use core::prelude::*;
use alloc::arc::Arc;
use alloc::heap::{allocate, deallocate};
use alloc::boxed::Box;
use collections::{Vec, MutableSeq};
use core::kinds::marker;
use core::mem::{forget, min... | () -> BufferPool<T> {
BufferPool { pool: Arc::new(Exclusive::new(Vec::new())) }
}
/// Allocates a new work-stealing deque which will send/receiving memory to
/// and from this buffer pool.
pub fn deque(&self) -> (Worker<T>, Stealer<T>) {
let a = Arc::new(Deque::new(self.clone()));
... | new | identifier_name |
deque.rs | on `swap_buffer`
// FIXME: all atomic operations in this module use a SeqCst ordering. That is
// probably overkill
use core::prelude::*;
use alloc::arc::Arc;
use alloc::heap::{allocate, deallocate};
use alloc::boxed::Box;
use collections::{Vec, MutableSeq};
use core::kinds::marker;
use core::mem::{forget, min... |
#[test]
fn stealpush() {
static AMT: int = 100000;
let pool = BufferPool::<int>::new();
let (w, s) = pool.deque();
let t = Thread::start(proc() {
let mut left = AMT;
while left > 0 {
match s.steal() {
Data(i) => {
... | {
let pool = BufferPool::new();
let (w, s) = pool.deque();
assert_eq!(w.pop(), None);
assert_eq!(s.steal(), Empty);
w.push(1i);
assert_eq!(w.pop(), Some(1));
w.push(1);
assert_eq!(s.steal(), Data(1));
w.push(1);
assert_eq!(s.clone().steal()... | identifier_body |
deque.rs | comment on `swap_buffer`
// FIXME: all atomic operations in this module use a SeqCst ordering. That is
// probably overkill
use core::prelude::*;
use alloc::arc::Arc;
use alloc::heap::{allocate, deallocate};
use alloc::boxed::Box;
use collections::{Vec, MutableSeq};
use core::kinds::marker;
use core::mem::{for... | unsafe fn elem(&self, i: int) -> *const T {
self.storage.offset(i & self.mask())
}
// This does not protect against loading duplicate values of the same cell,
// nor does this clear out the contents contained within. Hence, this is a
// very unsafe method which the caller needs to treat spe... |
// Apparently LLVM cannot optimize (foo % (1 << bar)) into this implicitly
fn mask(&self) -> int { (1 << self.log_size) - 1 }
| random_line_split |
safety_assertion_mode.rs | use crate::{analysis::function_parameters::Parameters, env::Env, library};
use std::str::FromStr;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SafetyAssertionMode {
None,
Skip,
InMainThread,
}
impl FromStr for SafetyAssertionMode {
type Err = String;
fn from_str(name: &str) -> Result<Safe... | }
} | match self {
SafetyAssertionMode::None => true,
_ => false,
} | random_line_split |
safety_assertion_mode.rs | use crate::{analysis::function_parameters::Parameters, env::Env, library};
use std::str::FromStr;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum | {
None,
Skip,
InMainThread,
}
impl FromStr for SafetyAssertionMode {
type Err = String;
fn from_str(name: &str) -> Result<SafetyAssertionMode, String> {
use self::SafetyAssertionMode::*;
match name {
"none" => Ok(None),
"skip" => Ok(Skip),
"in-ma... | SafetyAssertionMode | identifier_name |
safety_assertion_mode.rs | use crate::{analysis::function_parameters::Parameters, env::Env, library};
use std::str::FromStr;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SafetyAssertionMode {
None,
Skip,
InMainThread,
}
impl FromStr for SafetyAssertionMode {
type Err = String;
fn from_str(name: &str) -> Result<Safe... |
for par in ¶ms.rust_parameters {
let c_par = ¶ms.c_parameters[par.ind_c];
match *env.library.type_(c_par.typ) {
Class(..) | Interface(..)
if!*c_par.nullable && c_par.typ.ns_id == library::MAIN_NAMESPACE =>
{
... | {
return None;
} | conditional_block |
safety_assertion_mode.rs | use crate::{analysis::function_parameters::Parameters, env::Env, library};
use std::str::FromStr;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SafetyAssertionMode {
None,
Skip,
InMainThread,
}
impl FromStr for SafetyAssertionMode {
type Err = String;
fn from_str(name: &str) -> Result<Safe... |
InMainThread
}
pub fn is_none(self) -> bool {
match self {
SafetyAssertionMode::None => true,
_ => false,
}
}
}
| {
use self::SafetyAssertionMode::*;
use crate::library::Type::*;
if !env.config.generate_safety_asserts {
return None;
}
if is_method {
return None;
}
for par in ¶ms.rust_parameters {
let c_par = ¶ms.c_parameters[par.ind... | identifier_body |
mod.rs | // Each closure instance has its own unique anonymous type: that is, even if two closures have
// the same signature, their types are still considered to be different.
//
// Closures can capture values from environment by (1) moving, (2) borrow immutably, and (3) borrow
// mutably
// (1) Encoded as FnOnce trait. FnOnce... | assert!(equal_to_x(y));
let y = vec![1, 2, 3];
assert!(equal_to_x(y));
} | // let equal_to_x: (FnOnce(Vec<i32>) -> bool) = move |z| z == x;
let equal_to_x = move |z| z == x;
// This is no longer allowed.
// println!("can't use x here: {:?}", x);
let y = vec![1, 2, 3]; | random_line_split |
mod.rs | // Each closure instance has its own unique anonymous type: that is, even if two closures have
// the same signature, their types are still considered to be different.
//
// Closures can capture values from environment by (1) moving, (2) borrow immutably, and (3) borrow
// mutably
// (1) Encoded as FnOnce trait. FnOnce... | ensity: i32, random_number: i32) {
// Type annotations are not neccessary for closures, but can be added for clarity.
let mut expensive_result = Cacher::new(|nums: i32| -> i32 {
println!("calculating slowly...");
thread::sleep(Duration::from_secs(2));
nums
});
if intensity < 25 {... | rate_workout(int | identifier_name |
mod.rs | // Each closure instance has its own unique anonymous type: that is, even if two closures have
// the same signature, their types are still considered to be different.
//
// Closures can capture values from environment by (1) moving, (2) borrow immutably, and (3) borrow
// mutably
// (1) Encoded as FnOnce trait. FnOnce... | e {
println!("Today, run for {} minutes!", expensive_result.value(intensity));
}
}
}
fn capture() {
let x = 4;
// Closures can capture their dynamic environment, but at a cost -> memory
let equal_to_x = |z| z == x;
// Functions cannot do so. Following is illegal.
// fn equal... | println!("Take a break today! Remember to stay hydrated!");
} els | conditional_block |
cssrulelist.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::cell::DomRefCell;
use dom::bindings::codegen::Bindings::CSSRuleListBinding;
use dom::bindings::... | (&self) {
for rule in self.dom_rules.borrow().iter() {
rule.get().map(|r| DomRoot::upcast(r).deparent());
}
}
pub fn item(&self, idx: u32) -> Option<DomRoot<CSSRule>> {
self.dom_rules.borrow().get(idx as usize).map(|rule| {
rule.or_init(|| {
let p... | deparent_all | identifier_name |
cssrulelist.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::cell::DomRefCell;
use dom::bindings::codegen::Bindings::CSSRuleListBinding;
use dom::bindings::... |
}
}
// Remove parent stylesheets from all children
pub fn deparent_all(&self) {
for rule in self.dom_rules.borrow().iter() {
rule.get().map(|r| DomRoot::upcast(r).deparent());
}
}
pub fn item(&self, idx: u32) -> Option<DomRoot<CSSRule>> {
self.dom_rules... | {
// https://drafts.csswg.org/css-animations/#dom-csskeyframesrule-deleterule
let mut dom_rules = self.dom_rules.borrow_mut();
dom_rules[index].get().map(|r| r.detach());
dom_rules.remove(index);
kf.write_with(&mut guard).keyframes.remove(i... | conditional_block |
cssrulelist.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::cell::DomRefCell;
use dom::bindings::codegen::Bindings::CSSRuleListBinding;
use dom::bindings::... | unsafe_no_jsmanaged_fields!(RulesSource);
unsafe_no_jsmanaged_fields!(CssRules);
impl From<RulesMutateError> for Error {
fn from(other: RulesMutateError) -> Self {
match other {
RulesMutateError::Syntax => Error::Syntax,
RulesMutateError::IndexSize => Error::IndexSize,
... |
#[allow(unsafe_code)] | random_line_split |
cssrulelist.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::cell::DomRefCell;
use dom::bindings::codegen::Bindings::CSSRuleListBinding;
use dom::bindings::... |
}
impl CSSRuleListMethods for CSSRuleList {
// https://drafts.csswg.org/cssom/#ref-for-dom-cssrulelist-item-1
fn Item(&self, idx: u32) -> Option<DomRoot<CSSRule>> {
self.item(idx)
}
// https://drafts.csswg.org/cssom/#dom-cssrulelist-length
fn Length(&self) -> u32 {
self.dom_rules.... | {
if let RulesSource::Rules(..) = self.rules {
panic!("Can only call append_lazy_rule with keyframes-backed CSSRules");
}
self.dom_rules.borrow_mut().push(MutNullableDom::new(None));
} | identifier_body |
advent1.rs | // advent1.rs
// Manhattan lengths and segment intersection
use std::io;
use std::collections::HashSet;
type Vec2 = [i32; 2];
// unit vectors for the 4 cardinal directions
const NORTH: Vec2 = [0, 1];
#[allow(dead_code)]
const SOUTH: Vec2 = [0, -1];
#[allow(dead_code)]
const EAST: Vec2 = [1, 0];
#[allow(dead_code)]
c... | () {
assert_eq!(5, calc_manhattan_length("R2, L3"));
assert_eq!(2, calc_manhattan_length("R2, R2, R2"));
assert_eq!(12, calc_manhattan_length("R5, L5, R5, R3"));
}
// part 2
#[test]
fn test_find_first_revisited_distance() {
assert_eq!(4, find_first_revisited_distance("R8, R4, R4, R8"));
}
| test_calc_manhattan_length | identifier_name |
advent1.rs | // advent1.rs
// Manhattan lengths and segment intersection
use std::io;
use std::collections::HashSet;
type Vec2 = [i32; 2];
// unit vectors for the 4 cardinal directions
const NORTH: Vec2 = [0, 1];
#[allow(dead_code)]
const SOUTH: Vec2 = [0, -1];
#[allow(dead_code)]
const EAST: Vec2 = [1, 0];
#[allow(dead_code)]
c... | assert_eq!(12, calc_manhattan_length("R5, L5, R5, R3"));
}
// part 2
#[test]
fn test_find_first_revisited_distance() {
assert_eq!(4, find_first_revisited_distance("R8, R4, R4, R8"));
} |
#[test]
fn test_calc_manhattan_length() {
assert_eq!(5, calc_manhattan_length("R2, L3"));
assert_eq!(2, calc_manhattan_length("R2, R2, R2")); | random_line_split |
advent1.rs | // advent1.rs
// Manhattan lengths and segment intersection
use std::io;
use std::collections::HashSet;
type Vec2 = [i32; 2];
// unit vectors for the 4 cardinal directions
const NORTH: Vec2 = [0, 1];
#[allow(dead_code)]
const SOUTH: Vec2 = [0, -1];
#[allow(dead_code)]
const EAST: Vec2 = [1, 0];
#[allow(dead_code)]
c... | {
assert_eq!(4, find_first_revisited_distance("R8, R4, R4, R8"));
} | identifier_body | |
lib.rs | //! A database access library for leveldb
//!
//! Usage:
//!
//! ```rust,ignore
//! extern crate tempdir;
//! extern crate leveldb;
//!
//! use tempdir::TempDir;
//! use leveldb::database::Database;
//! use leveldb::kv::KV;
//! use leveldb::options::{Options,WriteOptions,ReadOptions};
//!
//! let tempdir = TempDir::new... |
/// The minor version
fn minor() -> isize {
unsafe { leveldb_minor_version() as isize }
}
}
| {
unsafe { leveldb_major_version() as isize }
} | identifier_body |
lib.rs | //! A database access library for leveldb
//!
//! Usage:
//!
//! ```rust,ignore
//! extern crate tempdir;
//! extern crate leveldb;
//!
//! use tempdir::TempDir;
//! use leveldb::database::Database;
//! use leveldb::kv::KV;
//! use leveldb::options::{Options,WriteOptions,ReadOptions};
//!
//! let tempdir = TempDir::new... | pub use database::batch;
pub use database::management;
pub use database::compaction;
#[allow(missing_docs)]
pub mod database;
/// Library version information
///
/// Need a recent version of leveldb to be used.
pub trait Version {
/// The major version.
fn major() -> isize {
unsafe { leveldb_major_ve... | pub use database::snapshots;
pub use database::comparator;
pub use database::kv; | random_line_split |
lib.rs | //! A database access library for leveldb
//!
//! Usage:
//!
//! ```rust,ignore
//! extern crate tempdir;
//! extern crate leveldb;
//!
//! use tempdir::TempDir;
//! use leveldb::database::Database;
//! use leveldb::kv::KV;
//! use leveldb::options::{Options,WriteOptions,ReadOptions};
//!
//! let tempdir = TempDir::new... | () -> isize {
unsafe { leveldb_minor_version() as isize }
}
}
| minor | identifier_name |
extern-fail.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 ... | do task::spawn {
let result = count(5u);
debug!("result = %?", result);
fail!();
};
}
} | fn main() {
for old_iter::repeat(10u) { | random_line_split |
extern-fail.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 main() {
for old_iter::repeat(10u) {
do task::spawn {
let result = count(5u);
debug!("result = %?", result);
fail!();
};
}
}
| {
unsafe {
task::yield();
rustrt::rust_dbg_call(cb, n)
}
} | identifier_body |
extern-fail.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 ... | else {
count(data - 1u) + count(data - 1u)
}
}
fn count(n: uint) -> uint {
unsafe {
task::yield();
rustrt::rust_dbg_call(cb, n)
}
}
fn main() {
for old_iter::repeat(10u) {
do task::spawn {
let result = count(5u);
debug!("result = %?", result);
... | {
data
} | conditional_block |
extern-fail.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 ... | (data: libc::uintptr_t) -> libc::uintptr_t {
if data == 1u {
data
} else {
count(data - 1u) + count(data - 1u)
}
}
fn count(n: uint) -> uint {
unsafe {
task::yield();
rustrt::rust_dbg_call(cb, n)
}
}
fn main() {
for old_iter::repeat(10u) {
do task::spawn... | cb | identifier_name |
generic-derived-type.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 f<T:Clone>(t: T) -> Pair<T> {
let x: Pair<T> = Pair {a: t.clone(), b: t};
return g::<Pair<T>>(x);
}
pub fn main() {
let b = f::<isize>(10);
println!("{}",b.a);
println!("{}", b.b);
assert_eq!(b.a, 10);
assert_eq!(b.b, 10);
} | a: T,
b: T
} | random_line_split |
generic-derived-type.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 ... |
#[derive(Clone)]
struct Pair<T> {
a: T,
b: T
}
fn f<T:Clone>(t: T) -> Pair<T> {
let x: Pair<T> = Pair {a: t.clone(), b: t};
return g::<Pair<T>>(x);
}
pub fn main() {
let b = f::<isize>(10);
println!("{}",b.a);
println!("{}", b.b);
assert_eq!(b.a, 10);
assert_eq!(b.b, 10);
}
| { return x; } | identifier_body |
generic-derived-type.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 ... | <X>(x: X) -> X { return x; }
#[derive(Clone)]
struct Pair<T> {
a: T,
b: T
}
fn f<T:Clone>(t: T) -> Pair<T> {
let x: Pair<T> = Pair {a: t.clone(), b: t};
return g::<Pair<T>>(x);
}
pub fn main() {
let b = f::<isize>(10);
println!("{}",b.a);
println!("{}", b.b);
assert_eq!(b.a, 10);
... | g | identifier_name |
increase_in_window.rs | use crate::client::types::ClientTypes;
use crate::common::increase_in_window_common::IncreaseInWindowCommon;
use crate::server::types::ServerTypes;
enum Impl {
Client(IncreaseInWindowCommon<ClientTypes>),
Server(IncreaseInWindowCommon<ServerTypes>),
}
/// Utility to tell the peer that it can send more data.
p... |
}
| {
match &mut self.0 {
Impl::Client(c) => c.increase_window_auto_above(above),
Impl::Server(c) => c.increase_window_auto_above(above),
}
} | identifier_body |
increase_in_window.rs | use crate::client::types::ClientTypes;
use crate::common::increase_in_window_common::IncreaseInWindowCommon;
use crate::server::types::ServerTypes;
enum Impl {
Client(IncreaseInWindowCommon<ClientTypes>),
Server(IncreaseInWindowCommon<ServerTypes>),
}
/// Utility to tell the peer that it can send more data.
p... | (c: IncreaseInWindowCommon<ClientTypes>) -> Self {
IncreaseInWindow(Impl::Client(c))
}
}
impl From<IncreaseInWindowCommon<ServerTypes>> for IncreaseInWindow {
fn from(c: IncreaseInWindowCommon<ServerTypes>) -> Self {
IncreaseInWindow(Impl::Server(c))
}
}
impl IncreaseInWindow {
/// Cur... | from | identifier_name |
increase_in_window.rs | use crate::client::types::ClientTypes;
use crate::common::increase_in_window_common::IncreaseInWindowCommon;
use crate::server::types::ServerTypes;
enum Impl {
Client(IncreaseInWindowCommon<ClientTypes>),
Server(IncreaseInWindowCommon<ServerTypes>),
}
/// Utility to tell the peer that it can send more data.
p... | // TODO: drop this operation.
pub fn increase_window_auto(&mut self) -> crate::Result<()> {
match &mut self.0 {
Impl::Client(c) => c.increase_window_auto(),
Impl::Server(c) => c.increase_window_auto(),
}
}
/// Auto-increase in window above specified limit.
//... | /// Auto-increase in window. | random_line_split |
iv.rs | use Error;
use header::tlv::Tlv;
use std::io::Read;
const IV_LENGTH: usize = 16;
pub fn read_tlv(reader: &mut Read, length: u16) -> Result<Tlv, Error> |
#[cfg(test)]
mod test {
use super::*;
use Error;
use header::tlv::Tlv;
#[test]
fn should_read_tlv() {
let bytes = [1; 16];
let result = read_tlv(&mut &bytes[..], 16);
match result {
Ok(Tlv::EncryptionIv(iv)) => assert_eq!(iv, bytes),
_ => panic!("... | {
try!(super::check_tlv_length(length, IV_LENGTH as u16));
let iv = try!(read_array!(reader, IV_LENGTH));
Ok(Tlv::EncryptionIv(iv))
} | identifier_body |
iv.rs | use Error;
use header::tlv::Tlv;
use std::io::Read;
const IV_LENGTH: usize = 16;
pub fn read_tlv(reader: &mut Read, length: u16) -> Result<Tlv, Error> {
try!(super::check_tlv_length(length, IV_LENGTH as u16));
let iv = try!(read_array!(reader, IV_LENGTH));
Ok(Tlv::EncryptionIv(iv))
}
#[cfg(test)]
mod ... | _ => panic!("Invalid result: {:#?}", result),
}
}
#[test]
fn should_return_error_if_wrong_length() {
let bytes = vec![];
let result = read_tlv(&mut &bytes[..], 15);
match result {
Err(Error::InvalidTlvSize) => (),
_ => panic!("Invalid res... |
match result {
Ok(Tlv::EncryptionIv(iv)) => assert_eq!(iv, bytes), | random_line_split |
iv.rs | use Error;
use header::tlv::Tlv;
use std::io::Read;
const IV_LENGTH: usize = 16;
pub fn read_tlv(reader: &mut Read, length: u16) -> Result<Tlv, Error> {
try!(super::check_tlv_length(length, IV_LENGTH as u16));
let iv = try!(read_array!(reader, IV_LENGTH));
Ok(Tlv::EncryptionIv(iv))
}
#[cfg(test)]
mod ... | () {
let bytes = [1; 16];
let result = read_tlv(&mut &bytes[..], 16);
match result {
Ok(Tlv::EncryptionIv(iv)) => assert_eq!(iv, bytes),
_ => panic!("Invalid result: {:#?}", result),
}
}
#[test]
fn should_return_error_if_wrong_length() {
let ... | should_read_tlv | identifier_name |
inline-trait-and-foreign-items.rs | #![feature(extern_types)]
#![feature(type_alias_impl_trait)]
#![warn(unused_attributes)]
trait Trait {
#[inline] //~ WARN `#[inline]` is ignored on constants
//~^ WARN this was previously accepted
const X: u32;
|
type U;
}
impl Trait for () {
#[inline] //~ WARN `#[inline]` is ignored on constants
//~^ WARN this was previously accepted
const X: u32 = 0;
#[inline] //~ ERROR attribute should be applied to function or closure
type T = Self;
#[inline] //~ ERROR attribute should be applied to function ... | #[inline] //~ ERROR attribute should be applied to function or closure
type T; | random_line_split |
inline-trait-and-foreign-items.rs | #![feature(extern_types)]
#![feature(type_alias_impl_trait)]
#![warn(unused_attributes)]
trait Trait {
#[inline] //~ WARN `#[inline]` is ignored on constants
//~^ WARN this was previously accepted
const X: u32;
#[inline] //~ ERROR attribute should be applied to function or closure
type T;
ty... | () {}
| main | identifier_name |
inline-trait-and-foreign-items.rs | #![feature(extern_types)]
#![feature(type_alias_impl_trait)]
#![warn(unused_attributes)]
trait Trait {
#[inline] //~ WARN `#[inline]` is ignored on constants
//~^ WARN this was previously accepted
const X: u32;
#[inline] //~ ERROR attribute should be applied to function or closure
type T;
ty... | {} | identifier_body | |
data.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/. */
//! Data needed to style a Gecko document.
use animation::Animation;
use atomic_refcell::{AtomicRef, AtomicRefCel... |
/// Get the default computed values for this document.
pub fn default_computed_values(&self) -> &Arc<ComputedValues> {
self.stylist.device.default_computed_values_arc()
}
}
unsafe impl HasFFI for PerDocumentStyleData {
type FFIType = RawServoStyleSet;
}
unsafe impl HasSimpleFFI for PerDocumen... | {
if self.stylesheets_changed {
let mut stylist = Arc::get_mut(&mut self.stylist).unwrap();
stylist.update(&self.stylesheets, &StylesheetGuards::same(guard), None, true);
self.stylesheets_changed = false;
}
} | identifier_body |
data.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/. */
//! Data needed to style a Gecko document.
use animation::Animation;
use atomic_refcell::{AtomicRef, AtomicRefCel... | (&mut self, guard: &SharedRwLockReadGuard) {
{
let mut stylist = Arc::get_mut(&mut self.stylist).unwrap();
Arc::get_mut(&mut stylist.device).unwrap().reset();
}
self.stylesheets_changed = true;
self.flush_stylesheets(guard);
}
/// Recreate the style data ... | reset_device | identifier_name |
data.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/. */
//! Data needed to style a Gecko document.
use animation::Animation;
use atomic_refcell::{AtomicRef, AtomicRefCel... |
}
/// Get the default computed values for this document.
pub fn default_computed_values(&self) -> &Arc<ComputedValues> {
self.stylist.device.default_computed_values_arc()
}
}
unsafe impl HasFFI for PerDocumentStyleData {
type FFIType = RawServoStyleSet;
}
unsafe impl HasSimpleFFI for PerD... | {
let mut stylist = Arc::get_mut(&mut self.stylist).unwrap();
stylist.update(&self.stylesheets, &StylesheetGuards::same(guard), None, true);
self.stylesheets_changed = false;
} | conditional_block |
data.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/. */
//! Data needed to style a Gecko document.
use animation::Animation;
use atomic_refcell::{AtomicRef, AtomicRefCel... | }))
}
/// Get an immutable reference to this style data.
pub fn borrow(&self) -> AtomicRef<PerDocumentStyleDataImpl> {
self.0.borrow()
}
/// Get an mutable reference to this style data.
pub fn borrow_mut(&self) -> AtomicRefMut<PerDocumentStyleDataImpl> {
self.0.borrow_m... | stylesheets_changed: true,
new_animations_sender: new_anims_sender,
new_animations_receiver: new_anims_receiver,
running_animations: Arc::new(RwLock::new(HashMap::new())),
expired_animations: Arc::new(RwLock::new(HashMap::new())), | random_line_split |
pokemon.rs | extern crate rand;
use self::rand::{random, Closed01};
use pokedex::{MoveDesc,PokeDesc,DamageClass,StatMod};
use std::cmp;
use std::fmt;
#[derive(Clone)]
pub enum Status
{
Paralyzed,
Poisoned,
Asleep,
Healthy
}
#[derive(Clone)]
pub struct Move<'a>
{
id: i32,
pub desc: &'a MoveDesc,
pub pp: i32
}
impl<'a> Mov... | (&mut self, mv: &MoveDesc, _foe: &mut Pokemon) -> ()
{
// match mv.damage_class
// {
// DamageClass::Status => println!("status moves are not implemented yet for the user. sorry."),
// _ => println!("physical and special moves are not implemented yet for the user. waiting on move data...")
// }
self.modi... | use_move | identifier_name |
pokemon.rs | extern crate rand;
use self::rand::{random, Closed01};
use pokedex::{MoveDesc,PokeDesc,DamageClass,StatMod};
use std::cmp;
use std::fmt;
#[derive(Clone)]
pub enum Status
{
Paralyzed,
Poisoned,
Asleep,
Healthy
}
#[derive(Clone)]
pub struct Move<'a>
{
id: i32,
pub desc: &'a MoveDesc,
pub pp: i32
}
impl<'a> Mov... | {
write!(f, "{} lvl: {}\n\thp: {}/{} atk: {} def: {}\n\tsp_atk: {} sp_def: {} speed: {}\n\t",
self.desc.name, self.level, self.hp, self.calc_hp(), self.calc_attack(), self.calc_defense(),
self.calc_sp_atk(), self.calc_sp_def(), self.calc_speed())
}
}
impl<'a> Pokemon<'a>
{
pub fn new<'b>(desc: &... | fn fmt(&self, f: &mut fmt::Formatter) -> (fmt::Result) | random_line_split |
pokemon.rs | extern crate rand;
use self::rand::{random, Closed01};
use pokedex::{MoveDesc,PokeDesc,DamageClass,StatMod};
use std::cmp;
use std::fmt;
#[derive(Clone)]
pub enum Status
{
Paralyzed,
Poisoned,
Asleep,
Healthy
}
#[derive(Clone)]
pub struct Move<'a>
{
id: i32,
pub desc: &'a MoveDesc,
pub pp: i32
}
impl<'a> Mov... |
pub fn modify_stats(&mut self, stat_effects: Vec<StatMod>) -> ()
{
for stat_mod in stat_effects.iter()
{
match *stat_mod
{
StatMod::Hp(_) => (),
StatMod::Attack(change) =>
{
Pokemon::mod_stat(&mut self.attack_stage, change);
println!("mod attack by {}", change)
}
StatMod... | {
*stat += change;
if *stat > 6
{
*stat = 6;
}
else if *stat < -6
{
*stat = -6;
}
} | identifier_body |
mesh.rs | use iced_wgpu::{wgpu, wgpu::util::DeviceExt};
#[repr(C)]
#[derive(Copy, Clone, Debug, Default)]
pub struct Vertex {
pub position: glam::Vec3,
pub normal: glam::Vec3,
pub texcoord: glam::Vec2,
}
pub struct Mesh {
pub bind_group: Option<wgpu::BindGroup>,
vertex_buffer: wgpu::Buffer,
index_buffer... |
/*pub fn new_test_triangle(device: &wgpu::Device) -> Self {
let vertices: &[Vertex] = &[
Vertex { position: glam::Vec3::new(0.0, 0.5, 0.0), normal: glam::Vec3::new(0.0, 0.0, 1.0), texcoord: glam::Vec2::new(0.5, 1.0) },
Vertex { position: glam::Vec3::new(-0.5, -0.5, 0.0), normal: gl... | {
let vertex_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: None,
contents: vertices,
usage: wgpu::BufferUsage::VERTEX,
});
let index_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: None,... | identifier_body |
mesh.rs | use iced_wgpu::{wgpu, wgpu::util::DeviceExt};
#[repr(C)]
#[derive(Copy, Clone, Debug, Default)]
pub struct Vertex {
pub position: glam::Vec3,
pub normal: glam::Vec3,
pub texcoord: glam::Vec2,
}
pub struct Mesh {
pub bind_group: Option<wgpu::BindGroup>,
vertex_buffer: wgpu::Buffer,
index_buffer... |
);
}
let indices: [u16; 36] = [
0, 4, 2, 2, 4, 6,
3, 5, 1, 7, 5, 3,
0, 1, 4, 1, 5, 4,
6, 3, 2, 6, 7, 3,
2, 1, 0, 1, 2, 3,
4, 5, 6, 7, 6, 5,
];
let bounding_volume = crate::bounding_volume::BoundingVolume... | { max_z } | conditional_block |
mesh.rs | use iced_wgpu::{wgpu, wgpu::util::DeviceExt};
#[repr(C)]
#[derive(Copy, Clone, Debug, Default)]
pub struct Vertex {
pub position: glam::Vec3,
pub normal: glam::Vec3,
pub texcoord: glam::Vec2,
}
pub struct Mesh {
pub bind_group: Option<wgpu::BindGroup>,
vertex_buffer: wgpu::Buffer,
index_buffer... | (device: &wgpu::Device, circle_resolution: usize) -> Self {
let mut vertices: Vec<glam::Vec3> = Vec::with_capacity(1+circle_resolution);
vertices.push(glam::Vec3::default());
for i in 0..circle_resolution {
let angle = i as f32/circle_resolution as f32*std::f32::consts::PI*2.0;
... | new_light_cone | identifier_name |
mesh.rs | use iced_wgpu::{wgpu, wgpu::util::DeviceExt};
#[repr(C)]
#[derive(Copy, Clone, Debug, Default)]
pub struct Vertex {
pub position: glam::Vec3,
pub normal: glam::Vec3,
pub texcoord: glam::Vec2,
}
pub struct Mesh {
pub bind_group: Option<wgpu::BindGroup>,
vertex_buffer: wgpu::Buffer,
index_buffer... | indices.push(1);
indices.push(1+((i+1)%circle_resolution) as u16);
indices.push(1+i as u16);
}
let bounding_volume = crate::bounding_volume::BoundingVolume::Cone(crate::bounding_volume::BoundingCone {
near: 0.0,
far: 1.0,
radius_at_... | for i in 1..circle_resolution-1 { | random_line_split |
cache.rs | use std::rc::Rc;
use std::cell::RefCell;
use super::types;
/// Evaluation cache. Know how to store reference for a particular execution context: environment of table.
/// Called to speedup execution of block cycles
#[derive(Debug, Clone, Default)]
pub struct Cache {
/// Context environment or table id
env_id:... |
}
None
}
pub fn set(&mut self, env_id: u64, value: &Rc<RefCell<types::Type>>) {
self.env_id = env_id;
self.cached_value = Some(value.clone());
}
} | {
return Some(types::Type::Reference(value.clone()))
} | conditional_block |
cache.rs | use std::rc::Rc;
use std::cell::RefCell;
use super::types;
/// Evaluation cache. Know how to store reference for a particular execution context: environment of table.
/// Called to speedup execution of block cycles
#[derive(Debug, Clone, Default)]
pub struct Cache {
/// Context environment or table id
env_id:... | (&mut self, env_id: u64, value: &Rc<RefCell<types::Type>>) {
self.env_id = env_id;
self.cached_value = Some(value.clone());
}
} | set | identifier_name |
cache.rs | use std::rc::Rc;
use std::cell::RefCell;
use super::types;
/// Evaluation cache. Know how to store reference for a particular execution context: environment of table.
/// Called to speedup execution of block cycles
#[derive(Debug, Clone, Default)]
pub struct Cache { | env_id: u64,
/// Cached value if set
cached_value: Option<Rc<RefCell<types::Type>>>
}
impl Cache {
pub fn get(&self, env_id: u64) -> Option<types::Type> {
if env_id == self.env_id {
if let Some(value) = &self.cached_value {
return Some(types::Type::Reference(value.cl... | /// Context environment or table id | random_line_split |
cache.rs | use std::rc::Rc;
use std::cell::RefCell;
use super::types;
/// Evaluation cache. Know how to store reference for a particular execution context: environment of table.
/// Called to speedup execution of block cycles
#[derive(Debug, Clone, Default)]
pub struct Cache {
/// Context environment or table id
env_id:... |
pub fn set(&mut self, env_id: u64, value: &Rc<RefCell<types::Type>>) {
self.env_id = env_id;
self.cached_value = Some(value.clone());
}
} | {
if env_id == self.env_id {
if let Some(value) = &self.cached_value {
return Some(types::Type::Reference(value.clone()))
}
}
None
} | identifier_body |
lib.rs | #[derive (Debug, PartialEq, Eq)]
pub enum Fix<A> {
Pro(A),
Fix(A)
}
impl<A> Fix<A> {
pub fn map<B, F: FnOnce(A) -> B>(self, f: F) -> Fix<B> {
match self {
Fix::Pro(a) => Fix::Pro(f(a)),
Fix::Fix(a) => Fix::Fix(f(a))
}
}
}
pub fn compose<A, F, G>(a: A, mut f: F, ... | <A, F: FnMut(A) -> Fix<A>>(mut a: A, mut f: F) -> A {
loop {
match f(a) {
Fix::Fix(b) => return b,
Fix::Pro(b) => a = b
}
}
}
pub fn fix_result<A, E, F: FnMut(A) -> Result<Fix<A>, E>>(mut a: A, mut f: F) -> Result<A, E> {
loop {
match f(a) {
Resul... | fix | identifier_name |
lib.rs | #[derive (Debug, PartialEq, Eq)]
pub enum Fix<A> {
Pro(A),
Fix(A)
}
impl<A> Fix<A> {
pub fn map<B, F: FnOnce(A) -> B>(self, f: F) -> Fix<B> {
match self {
Fix::Pro(a) => Fix::Pro(f(a)),
Fix::Fix(a) => Fix::Fix(f(a))
}
}
}
pub fn compose<A, F, G>(a: A, mut f: F, ... | } | random_line_split | |
lib.rs | #[derive (Debug, PartialEq, Eq)]
pub enum Fix<A> {
Pro(A),
Fix(A)
}
impl<A> Fix<A> {
pub fn map<B, F: FnOnce(A) -> B>(self, f: F) -> Fix<B> {
match self {
Fix::Pro(a) => Fix::Pro(f(a)),
Fix::Fix(a) => Fix::Fix(f(a))
}
}
}
pub fn compose<A, F, G>(a: A, mut f: F, ... |
pub fn fix_result<A, E, F: FnMut(A) -> Result<Fix<A>, E>>(mut a: A, mut f: F) -> Result<A, E> {
loop {
match f(a) {
Result::Err(err) => return Result::Err(err),
Result::Ok(Fix::Fix(b)) => return Result::Ok(b),
Result::Ok(Fix::Pro(b)) => a = b
}
}
}
| {
loop {
match f(a) {
Fix::Fix(b) => return b,
Fix::Pro(b) => a = b
}
}
} | identifier_body |
libunwind.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 ... |
#[cfg(target_arch = "arm")]
#[repr(C)]
pub enum _Unwind_State {
_US_VIRTUAL_UNWIND_FRAME = 0,
_US_UNWIND_FRAME_STARTING = 1,
_US_UNWIND_FRAME_RESUME = 2,
_US_ACTION_MASK = 3,
_US_FORCE_UNWIND = 8,
_US_END_OF_STACK = 16
}
#[repr(C)]
pub enum _Unwind_Reason_Code {
_URC_NO_REASON = 0,
_UR... | _UA_CLEANUP_PHASE = 2,
_UA_HANDLER_FRAME = 4,
_UA_FORCE_UNWIND = 8,
_UA_END_OF_STACK = 16,
} | random_line_split |
libunwind.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 ... | {
pub exception_class: _Unwind_Exception_Class,
pub exception_cleanup: _Unwind_Exception_Cleanup_Fn,
pub private: [_Unwind_Word,..unwinder_private_data_size],
}
pub enum _Unwind_Context {}
pub type _Unwind_Exception_Cleanup_Fn =
extern "C" fn(unwind_code: _Unwind_Reason_Code,
... | _Unwind_Exception | identifier_name |
net.rs | // Copyright 2015, 2016 Parity Technologies (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 la... | } | fn is_listening(&self) -> Result<bool, Error>;
} | random_line_split |
mtmap.rs | #[deriving(Clone)]
#[deriving(ToStr)]
type LinkedList = Option<~Node>;
#[deriving(Clone)]
struct Node {
val: int,
tail: LinkedList
}
trait Length {
fn length(&self) -> int;
}
#[allow(dead_code)]
fn length(p: LinkedList) -> int |
impl Length for LinkedList {
fn length(&self) -> int {
match self {
&Some(ref node) => { 1 + node.tail.length() }
&None => 0
}
}
}
fn construct_list(n: int, x: int) -> LinkedList {
match n {
0 => { None }
_ => { Some(~Node{val: x, tail: construct_list(n - 1, x + ... | {
match p {
None => { 0 }
Some(node) => { 1 + length(node.tail) }
}
} | identifier_body |
mtmap.rs | #[deriving(Clone)]
#[deriving(ToStr)]
type LinkedList = Option<~Node>;
#[deriving(Clone)]
struct Node {
val: int,
tail: LinkedList
}
trait Length {
fn length(&self) -> int;
}
#[allow(dead_code)]
fn length(p: LinkedList) -> int {
match p {
None => { 0 }
Some(node) => { 1 + length(node.tail) }... | (&mut self, f: fn(int) -> int) {
match(*self) {
None => { }
Some(ref mut current) => {
let (port, chan) : (Port<int>, Chan<int>) = Chan::new();
let val = current.val; // Can't use current inside task!
spawn(proc() { chan.send(f(val)); });
... | mapr | identifier_name |
mtmap.rs | #[deriving(Clone)]
#[deriving(ToStr)]
type LinkedList = Option<~Node>;
#[deriving(Clone)]
struct Node {
val: int,
tail: LinkedList
}
trait Length {
fn length(&self) -> int;
}
#[allow(dead_code)]
fn length(p: LinkedList) -> int {
match p {
None => { 0 }
Some(node) => { 1 + length(node.tail) }... |
}
}
}
fn expensive_inc(n: int) -> int {
let mut a = 1;
println!("starting inc: {:d}", n);
for _ in range(0, 10000) {
for _ in range(0, 1000000) {
a = a + 1;
}
}
println!("finished inc: {:d} ({:d})", n, a);
n + 1
}
fn main() {
let mut l10 : LinkedLi... | {
let (port, chan) : (Port<int>, Chan<int>) = Chan::new();
let val = current.val; // Can't use current inside task!
spawn(proc() { chan.send(f(val)); });
current.tail.mapr(f); // Make sure to do this first, so we're not waiting for recv!
curren... | conditional_block |
mtmap.rs | #[deriving(Clone)]
#[deriving(ToStr)]
type LinkedList = Option<~Node>;
#[deriving(Clone)]
struct Node {
val: int,
tail: LinkedList
} |
trait Length {
fn length(&self) -> int;
}
#[allow(dead_code)]
fn length(p: LinkedList) -> int {
match p {
None => { 0 }
Some(node) => { 1 + length(node.tail) }
}
}
impl Length for LinkedList {
fn length(&self) -> int {
match self {
&Some(ref node) => { 1 + node.tail.length() }
... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.