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 |
|---|---|---|---|---|
treebuilder.rs | //! A convenience struct to create symbolic trees.
use ketos::{
Error,
Interpreter,
ModuleLoader,
FromValue,
};
use std::collections::HashSet;
use std::fmt::Debug;
use std::rc::Rc;
use std::cell::RefCell;
use std::mem;
use tree::{
Tree,
Expression,
};
use treeerror::{
TreeError,
TreeErr... | (&mut self, s: &'a str) {
self.kcode = s;
}
/// Sets the prologue to be executed.
pub fn set_prologue(&mut self, s: &'a str) {
self.prologue = s;
}
/// Sets the epilogue to be executed.
pub fn set_epilogue(&mut self, s: &'a str) {
self.epilogue = s;
}
/// Consu... | set_body | identifier_name |
treebuilder.rs | //! A convenience struct to create symbolic trees.
use ketos::{
Error,
Interpreter,
ModuleLoader,
FromValue,
};
use std::collections::HashSet;
use std::fmt::Debug;
use std::rc::Rc;
use std::cell::RefCell;
use std::mem;
use tree::{
Tree,
Expression,
};
use treeerror::{
TreeError,
TreeErr... | };
let varcont = Rc::new(RefCell::new(vs));
let varcontc = varcont.clone();
let var_fn = move |s: &str| -> Result<Tree<T>, Error> {
varcontc.borrow_mut().insert(s.to_string());
Ok(Tree::<T>::new(Expression::Variable(s.to_string())))
... | random_line_split | |
kindck-copy.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 test<'a,T,U:Copy>(_: &'a isize) {
// lifetime pointers are ok...
assert_copy::<&'static isize>();
assert_copy::<&'a isize>();
assert_copy::<&'a str>();
assert_copy::<&'a [isize]>();
//...unless they are mutable
assert_copy::<&'static mut isize>(); //~ ERROR : std::marker::Copy` is not sa... | x: Box<char>,
}
| random_line_split |
kindck-copy.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 ... |
trait Dummy { }
#[derive(Copy, Clone)]
struct MyStruct {
x: isize,
y: isize,
}
struct MyNoncopyStruct {
x: Box<char>,
}
fn test<'a,T,U:Copy>(_: &'a isize) {
// lifetime pointers are ok...
assert_copy::<&'static isize>();
assert_copy::<&'a isize>();
assert_copy::<&'a str>();
assert_c... | { } | identifier_body |
kindck-copy.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 ... | () {
}
| main | identifier_name |
build.rs | extern crate gcc;
use std::env;
pub fn main() | }
/*
use std::env;
use std::process::Command;
pub fn main() {
let root = env::var("CARGO_MANIFEST_DIR").unwrap();
let make = root.clone() + "/Makefile";
let src = root.clone() + "/src";
let out = env::var("OUT_DIR").unwrap();
let target = env::var("TARGET").unwrap();
let os = if ta... | {
let target = env::var("TARGET").unwrap();
let os = if target.contains("linux") {
"LINUX"
} else if target.contains("darwin") {
"DARWIN"
} else {
"UNKNOWN"
};
let mut config = gcc::Config::new();
for file in &["src/const.c", "src/sizes.c"] {
config.file(fi... | identifier_body |
build.rs | extern crate gcc;
use std::env;
pub fn | () {
let target = env::var("TARGET").unwrap();
let os = if target.contains("linux") {
"LINUX"
} else if target.contains("darwin") {
"DARWIN"
} else {
"UNKNOWN"
};
let mut config = gcc::Config::new();
for file in &["src/const.c", "src/sizes.c"] {
config.file... | main | identifier_name |
build.rs | extern crate gcc;
use std::env;
pub fn main() {
let target = env::var("TARGET").unwrap();
let os = if target.contains("linux") {
"LINUX"
} else if target.contains("darwin") {
"DARWIN"
} else {
"UNKNOWN"
};
let mut config = gcc::Config::new();
for file in &["src/c... | "DARWIN"
} else {
"UNKNOWN"
};
let res = Command::new("make")
.arg("-f").arg(&make)
.current_dir(&out)
.env("VPATH", &src)
.env("OS", os)
.spawn().unwrap()
.wait().unwrap();
assert!(res.success());
println!("cargo:rustc-flags=-L {}/", out)... | } else if target.contains("darwin") { | random_line_split |
build.rs | extern crate gcc;
use std::env;
pub fn main() {
let target = env::var("TARGET").unwrap();
let os = if target.contains("linux") | else if target.contains("darwin") {
"DARWIN"
} else {
"UNKNOWN"
};
let mut config = gcc::Config::new();
for file in &["src/const.c", "src/sizes.c"] {
config.file(file);
}
config.define(os, None);
config.compile("libnixtest.a");
}
/*
use std::env;
use std::proces... | {
"LINUX"
} | conditional_block |
(8 kyu) Count of positives - sum of negatives.rs | // #1
// fn count_positives_sum_negatives(input: Vec<i32>) -> Vec<i32> {
// if input.len() == 0 {
// return vec![];
// }
// let mut res = vec![0, 0];
// for x in &input {
// if x > &0 {
// res[0] += 1;
// } else {
// res[1] += x;
// }
// }
// ... | {
if input.is_empty() {
return vec![];
}
input.iter().fold(vec![0, 0], |mut res, &x| {
if x.is_positive() {
res[0] += 1;
} else {
res[1] += x;
}
res
})
} | identifier_body | |
(8 kyu) Count of positives - sum of negatives.rs | // #1
// fn count_positives_sum_negatives(input: Vec<i32>) -> Vec<i32> {
// if input.len() == 0 {
// return vec![];
// }
// let mut res = vec![0, 0];
// for x in &input {
// if x > &0 {
// res[0] += 1;
// } else {
// res[1] += x;
// }
// }
// ... | (input: Vec<i32>) -> Vec<i32> {
if input.is_empty() {
return vec![];
}
input.iter().fold(vec![0, 0], |mut res, &x| {
if x.is_positive() {
res[0] += 1;
} else {
res[1] += x;
}
res
})
}
| count_positives_sum_negatives | identifier_name |
(8 kyu) Count of positives - sum of negatives.rs | // #1
// fn count_positives_sum_negatives(input: Vec<i32>) -> Vec<i32> {
// if input.len() == 0 {
// return vec![];
// }
// let mut res = vec![0, 0];
// for x in &input {
// if x > &0 {
// res[0] += 1;
// } else {
// res[1] += x;
// }
// }
// ... | else {
res[1] += x;
}
res
})
}
| {
res[0] += 1;
} | conditional_block |
(8 kyu) Count of positives - sum of negatives.rs | // }
// let mut res = vec![0, 0];
// for x in &input {
// if x > &0 {
// res[0] += 1;
// } else {
// res[1] += x;
// }
// }
// res
// }
// #2
fn count_positives_sum_negatives(input: Vec<i32>) -> Vec<i32> {
if input.is_empty() {
return vec![... | // #1
// fn count_positives_sum_negatives(input: Vec<i32>) -> Vec<i32> {
// if input.len() == 0 {
// return vec![]; | random_line_split | |
server.rs | //! Shadowsocks Server instance
use std::{
collections::HashMap,
io::{self, ErrorKind},
sync::Arc,
time::Duration,
};
use futures::{stream::FuturesUnordered, FutureExt, StreamExt};
use log::{error, trace};
use shadowsocks::{
config::{ManagerAddr, ServerConfig},
dns_resolver::DnsResolver,
n... |
}
}
// Report every 10 seconds
time::sleep(Duration::from_secs(10)).await;
}
}
}
| {
trace!("report to manager {}, {:?}", manager_addr, req);
} | conditional_block |
server.rs | //! Shadowsocks Server instance
use std::{
collections::HashMap,
io::{self, ErrorKind},
sync::Arc,
time::Duration,
};
use futures::{stream::FuturesUnordered, FutureExt, StreamExt};
use log::{error, trace};
use shadowsocks::{
config::{ManagerAddr, ServerConfig},
dns_resolver::DnsResolver,
n... |
/// Get server's configuration
pub fn config(&self) -> &ServerConfig {
&self.svr_cfg
}
/// Set customized DNS resolver
pub fn set_dns_resolver(&mut self, resolver: Arc<DnsResolver>) {
let context = Arc::get_mut(&mut self.context).expect("cannot set DNS resolver on a shared context... | {
self.manager_addr = Some(manager_addr);
} | identifier_body |
server.rs | //! Shadowsocks Server instance
use std::{
collections::HashMap,
io::{self, ErrorKind},
sync::Arc,
time::Duration,
};
use futures::{stream::FuturesUnordered, FutureExt, StreamExt};
use log::{error, trace};
use shadowsocks::{
config::{ManagerAddr, ServerConfig},
dns_resolver::DnsResolver,
n... | );
server.run(&self.svr_cfg).await
}
async fn run_manager_report(&self) -> io::Result<()> {
let manager_addr = self.manager_addr.as_ref().unwrap();
loop {
match ManagerClient::connect(
self.context.context_ref(),
manager_addr,
... | random_line_split | |
server.rs | //! Shadowsocks Server instance
use std::{
collections::HashMap,
io::{self, ErrorKind},
sync::Arc,
time::Duration,
};
use futures::{stream::FuturesUnordered, FutureExt, StreamExt};
use log::{error, trace};
use shadowsocks::{
config::{ManagerAddr, ServerConfig},
dns_resolver::DnsResolver,
n... | (&mut self, manager_addr: ManagerAddr) {
self.manager_addr = Some(manager_addr);
}
/// Get server's configuration
pub fn config(&self) -> &ServerConfig {
&self.svr_cfg
}
/// Set customized DNS resolver
pub fn set_dns_resolver(&mut self, resolver: Arc<DnsResolver>) {
let... | set_manager_addr | identifier_name |
d3dcompiler.rs | // Copyright © 2016, Peter Atashian
// Licensed under the MIT License <LICENSE.md>
use shared::basetsd::{SIZE_T};
use shared::minwindef::{DWORD, LPCVOID};
use um::d3dcommon::{ID3DInclude};
pub const D3DCOMPILER_DLL: &'static str = "d3dcompiler_47.dll";
pub const D3D_COMPILER_VERSION: DWORD = 47;
pub const D3DCOMPILE_D... | pub const D3D_DISASM_ENABLE_INSTRUCTION_OFFSET: DWORD = 0x00000020;
pub const D3D_DISASM_INSTRUCTION_ONLY: DWORD = 0x00000040;
pub const D3D_DISASM_PRINT_HEX_LITERALS: DWORD = 0x00000080;
pub const D3D_GET_INST_OFFSETS_INCLUDE_NON_EXECUTABLE: DWORD = 0x00000001;
ENUM!{enum D3DCOMPILER_STRIP_FLAGS {
D3DCOMPILER_STRI... | pub const D3D_DISASM_ENABLE_DEFAULT_VALUE_PRINTS: DWORD = 0x00000002;
pub const D3D_DISASM_ENABLE_INSTRUCTION_NUMBERING: DWORD = 0x00000004;
pub const D3D_DISASM_ENABLE_INSTRUCTION_CYCLE: DWORD = 0x00000008;
pub const D3D_DISASM_DISABLE_DEBUG_INFO: DWORD = 0x00000010; | random_line_split |
asn.rs | /*
copyright: (c) 2013-2019 by Blockstack PBC, a public benefit corporation.
This file is part of Blockstack.
Blockstack is free software. You may redistribute 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... | text: "\n\n1.2.3.4/24 100\n \n2.3.4.5/23 \t\t\t200\n # this is a comment\n# so is this\n".to_string(),
result: Ok(vec![
ASEntry4 {
prefix: 0x01020304,
mask: 24,
asn: 100,
... | {
let tests = vec![
asn_fixture {
text: "1.0.0.0/8 1\n2.1.0.0/16 2\n".to_string(),
result: Ok(vec![
ASEntry4 {
prefix: 0x01000000,
mask: 8,
asn: 1,
org:... | identifier_body |
asn.rs | /*
copyright: (c) 2013-2019 by Blockstack PBC, a public benefit corporation.
This file is part of Blockstack.
Blockstack is free software. You may redistribute 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... | mask: mask,
asn: asn,
org: 0 // TODO
}))
}
}
#[cfg(test)]
mod test {
use super::*;
use std::io;
use std::io::BufRead;
use util::log;
struct asn_fixture {
text: String,
result: Result<Vec<ASEntry4>, net_error>
}
#[test]
... | prefix: prefix, | random_line_split |
asn.rs | /*
copyright: (c) 2013-2019 by Blockstack PBC, a public benefit corporation.
This file is part of Blockstack.
Blockstack is free software. You may redistribute 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... |
let caps = asn4_regex.captures(&buf)
.ok_or(net_error::DeserializeError("Line does not match ANS4 regex".to_string()))
.map_err(|e| {
debug!("Failed to read line \"{}\"", &buf);
e
})?;
let prefix_octets_str = caps.get(1)
.ok... | {
return Ok(None);
} | conditional_block |
asn.rs | /*
copyright: (c) 2013-2019 by Blockstack PBC, a public benefit corporation.
This file is part of Blockstack.
Blockstack is free software. You may redistribute 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... | (asn_file: &String) -> Result<Vec<ASEntry4>, net_error> {
// each row in asn_file must be one of the following:
// ^[:whitespace:]*([0-9]+.[0-9]+.[0-9]+.[0-9]+)/([0-9]+)[:whitespace:]+([0-9]+)[:whitespace:]*$
// group 1 is the IP prefix
// group 2 is the prefix length
// group 3 ... | from_file | identifier_name |
codec.rs | // Copyright 2017 click2stream, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed... |
}
impl Encoder<ArrowMessage> for ArrowCodec {
type Error = ArrowError;
fn encode(&mut self, item: ArrowMessage, dst: &mut BytesMut) -> Result<(), Self::Error> {
item.encode(dst);
Ok(())
}
}
| {
ArrowMessage::decode(src).map_err(ArrowError::from)
} | identifier_body |
codec.rs | // Copyright 2017 click2stream, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed... | impl<T: AsRef<[u8]>> Encode for T {
fn encode(&self, buf: &mut BytesMut) {
buf.extend_from_slice(self.as_ref())
}
}
/// Common trait for types that can be decoded from a sequence of bytes.
pub trait FromBytes: Sized {
/// Deserialize an object from a given buffer if possible.
fn from_bytes(byte... | random_line_split | |
codec.rs | // Copyright 2017 click2stream, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed... | ;
impl Decoder for ArrowCodec {
type Item = ArrowMessage;
type Error = ArrowError;
fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
ArrowMessage::decode(src).map_err(ArrowError::from)
}
}
impl Encoder<ArrowMessage> for ArrowCodec {
type Error = ArrowEr... | ArrowCodec | identifier_name |
lib.rs | use chromiumoxide::{cdp::browser_protocol::page::PrintToPdfParamsBuilder, Browser, BrowserConfig};
use codec::{
async_trait::async_trait, eyre::Result, stencila_schema::Node, utils::vec_string, Codec,
CodecTrait, EncodeOptions,
};
use codec_html::HtmlCodec;
use futures::StreamExt;
use std::path::Path;
/// A co... | () -> Codec {
Codec {
status: "alpha".to_string(),
formats: vec_string!["pdf"],
root_types: vec_string!["Article"],
from_string: false,
from_path: false,
to_string: false,
..Default::default()
}
}
/// Encode a do... | spec | identifier_name |
lib.rs | use chromiumoxide::{cdp::browser_protocol::page::PrintToPdfParamsBuilder, Browser, BrowserConfig};
use codec::{
async_trait::async_trait, eyre::Result, stencila_schema::Node, utils::vec_string, Codec,
CodecTrait, EncodeOptions,
};
use codec_html::HtmlCodec;
use futures::StreamExt;
use std::path::Path;
/// A co... | .set_content(html)
.await?
.save_pdf(params, path)
.await?;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use codec::stencila_schema::Article;
use test_utils::tempfile;
#[tokio::test]
async fn encode() -> super::Result<()> {
let ... | .new_page("about:blank")
.await? | random_line_split |
lib.rs | use chromiumoxide::{cdp::browser_protocol::page::PrintToPdfParamsBuilder, Browser, BrowserConfig};
use codec::{
async_trait::async_trait, eyre::Result, stencila_schema::Node, utils::vec_string, Codec,
CodecTrait, EncodeOptions,
};
use codec_html::HtmlCodec;
use futures::StreamExt;
use std::path::Path;
/// A co... | let (browser, mut handler) = Browser::launch(config).await?;
tokio::task::spawn(async move {
loop {
let _ = handler.next().await.unwrap();
}
});
let params = PrintToPdfParamsBuilder::default().build();
browser
.new_page("about:b... | {
let EncodeOptions { theme, .. } = options.unwrap_or_default();
let html = HtmlCodec::to_string(
node,
Some(EncodeOptions {
standalone: true,
bundle: true,
theme,
..Default::default()
}),
)?;
... | identifier_body |
issue-49595.rs | // revisions:cfail1 cfail2 cfail3
// compile-flags: -Z query-dep-graph --test
// build-pass
#![feature(rustc_attrs)]
#![crate_type = "rlib"]
#![rustc_partition_codegened(module="issue_49595-tests", cfg="cfail2")]
#![rustc_partition_codegened(module="issue_49595-lit_test", cfg="cfail3")]
mod tests {
#[cfg_attr(no... | () {
println!("{}", ::lit::A);
}
}
| lit_test | identifier_name |
issue-49595.rs | // revisions:cfail1 cfail2 cfail3
// compile-flags: -Z query-dep-graph --test
// build-pass
#![feature(rustc_attrs)]
#![crate_type = "rlib"]
#![rustc_partition_codegened(module="issue_49595-tests", cfg="cfail2")]
#![rustc_partition_codegened(module="issue_49595-lit_test", cfg="cfail3")]
mod tests {
#[cfg_attr(no... |
// Checks that changing a string literal without changing its span
// takes effect.
// replacing a module to have a stable span
#[cfg_attr(not(cfail3), path = "auxiliary/lit_a.rs")]
#[cfg_attr(cfail3, path = "auxiliary/lit_b.rs")]
mod lit;
pub mod lit_test {
#[test]
fn lit_test() {
println!("{}", ::... | fn test() {
}
} | random_line_split |
issue-49595.rs | // revisions:cfail1 cfail2 cfail3
// compile-flags: -Z query-dep-graph --test
// build-pass
#![feature(rustc_attrs)]
#![crate_type = "rlib"]
#![rustc_partition_codegened(module="issue_49595-tests", cfg="cfail2")]
#![rustc_partition_codegened(module="issue_49595-lit_test", cfg="cfail3")]
mod tests {
#[cfg_attr(no... |
}
| {
println!("{}", ::lit::A);
} | identifier_body |
clipboard.rs | extern crate clipboard_win;
use clipboard_win::*;
use clipboard_win::wrapper::{open_clipboard, close_clipboard, set_clipboard_raw, register_format, count_formats, is_format_avail, get_clipboard_seq_num};
//NOTE: parallel running may cause fail.
#[test]
fn win_error_test() {
let result = WindowsError::ne... |
}
}
#[test]
fn get_clipboard_seq_num_test() {
assert!(get_clipboard_seq_num().is_some());
}
#[test]
fn set_clipboard_test() {
let test_array = vec!["ololo", "1234", "1234567891234567891234567891234567891", "12345678912345678912345678912345678912"];
for expected_string in test_array {
... | {
println!("{}={}", format, format_name);
} | conditional_block |
clipboard.rs | extern crate clipboard_win;
use clipboard_win::*;
use clipboard_win::wrapper::{open_clipboard, close_clipboard, set_clipboard_raw, register_format, count_formats, is_format_avail, get_clipboard_seq_num};
//NOTE: parallel running may cause fail.
#[test]
fn win_error_test() {
let result = WindowsError::ne... |
#[test]
fn get_clipboard_seq_num_test() {
assert!(get_clipboard_seq_num().is_some());
}
#[test]
fn set_clipboard_test() {
let test_array = vec!["ololo", "1234", "1234567891234567891234567891234567891", "12345678912345678912345678912345678912"];
for expected_string in test_array {
asser... | {
let clipboard_formats = get_clipboard_formats();
assert!(clipboard_formats.is_ok());
let clipboard_formats = clipboard_formats.unwrap();
println!("get_clipboard_formats_test: clipboard formats: {:?}", clipboard_formats);
for format in clipboard_formats {
if let Some(format_name) ... | identifier_body |
clipboard.rs | extern crate clipboard_win;
use clipboard_win::*;
use clipboard_win::wrapper::{open_clipboard, close_clipboard, set_clipboard_raw, register_format, count_formats, is_format_avail, get_clipboard_seq_num};
//NOTE: parallel running may cause fail.
#[test]
fn win_error_test() {
let result = WindowsError::ne... | }
}
#[test]
fn get_clipboard_test() {
let result = get_clipboard_string();
assert!(result.is_ok());
println!("get_clipboard_test: Clipboard: {}", result.unwrap());
}
#[test]
fn is_format_avail_test() {
assert!(is_format_avail(13)); //default unicode format
assert!(!is_format_ava... | println!("set_clipboard_test: Expected: {}", expected_string);
assert!(result == expected_string);
| random_line_split |
clipboard.rs | extern crate clipboard_win;
use clipboard_win::*;
use clipboard_win::wrapper::{open_clipboard, close_clipboard, set_clipboard_raw, register_format, count_formats, is_format_avail, get_clipboard_seq_num};
//NOTE: parallel running may cause fail.
#[test]
fn win_error_test() {
let result = WindowsError::ne... | () {
let new_format = register_format("text");
assert!(new_format.is_ok());
let new_format = new_format.unwrap();
println!("register_format_test: new_format={}", new_format);
assert!(open_clipboard().is_ok());
let expect_buf = [13, 12, 122, 1];
println!("register_format_test: set ... | register_format_test | identifier_name |
cube.rs | pub const VERTEX: &'static str = r#"
#version 150
in uint face;
in uvec3 pos;
in vec3 corner;
void main() {
gl_Position = vec4(corner + pos, 1.0);
}
"#;
pub const GEOMETRY: &'static str = r#"
#version 150
layout(lines) in;
la... | EndPrimitive();
}
"#;
pub const FRAGMENT: &'static str = r#"
#version 150
in vec2 g_texcoord;
out vec4 color;
uniform sampler2D tex;
void main() {
color = texture(tex, g_texcoord);
}
"#; | random_line_split | |
method-normalize-bounds-issue-20604.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | <K>(&self, k: K) where K: Hash< <S as HashState>::Wut> {}
}
fn foo<K: Hash<SipHasher>>(map: &Map<SipState>) {
map.foo(22);
}
fn main() {}
| foo | identifier_name |
method-normalize-bounds-issue-20604.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | #![feature(associated_types)]
trait Hasher {
type Output;
fn finish(&self) -> Self::Output;
}
trait Hash<H: Hasher> {
fn hash(&self, h: &mut H);
}
trait HashState {
type Wut: Hasher;
fn hasher(&self) -> Self::Wut;
}
struct SipHasher;
impl Hasher for SipHasher {
type Output = u64;
fn fini... | random_line_split | |
method-normalize-bounds-issue-20604.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
impl Hash<SipHasher> for int {
fn hash(&self, h: &mut SipHasher) {}
}
struct SipState;
impl HashState for SipState {
type Wut = SipHasher;
fn hasher(&self) -> SipHasher { SipHasher }
}
struct Map<S> {
s: S,
}
impl<S> Map<S>
where S: HashState,
<S as HashState>::Wut: Hasher<Output=u6... | { 4 } | identifier_body |
trait-matching-lifetimes.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 ... | <'a,'b> {
x: &'a isize,
y: &'b isize,
}
trait Tr : Sized {
fn foo(x: Self) {}
}
impl<'a,'b> Tr for Foo<'a,'b> {
fn foo(x: Foo<'b,'a>) {
//~^ ERROR method not compatible with trait
//~^^ ERROR method not compatible with trait
}
}
fn main(){}
| Foo | identifier_name |
trait-matching-lifetimes.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(){} | //~^^ ERROR method not compatible with trait
} | random_line_split |
buf_writer.rs | use super::DEFAULT_BUF_SIZE;
use futures_core::ready;
use futures_core::task::{Context, Poll};
use futures_io::{AsyncBufRead, AsyncRead, AsyncSeek, AsyncWrite, IoSlice, SeekFrom};
use pin_project_lite::pin_project;
use std::fmt;
use std::io::{self, Write};
use std::pin::Pin;
pin_project! {
/// Wraps a writer and b... |
}
| {
ready!(self.as_mut().flush_buf(cx))?;
self.project().inner.poll_seek(cx, pos)
} | identifier_body |
buf_writer.rs | use super::DEFAULT_BUF_SIZE;
use futures_core::ready;
use futures_core::task::{Context, Poll};
use futures_io::{AsyncBufRead, AsyncRead, AsyncSeek, AsyncWrite, IoSlice, SeekFrom};
use pin_project_lite::pin_project;
use std::fmt;
use std::io::{self, Write};
use std::pin::Pin;
pin_project! {
/// Wraps a writer and b... |
impl<W: AsyncWrite + AsyncSeek> AsyncSeek for BufWriter<W> {
/// Seek to the offset, in bytes, in the underlying writer.
///
/// Seeking always writes out the internal buffer before seeking.
fn poll_seek(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
pos: SeekFrom,
) -> Po... | .field("written", &self.written)
.finish()
}
} | random_line_split |
buf_writer.rs | use super::DEFAULT_BUF_SIZE;
use futures_core::ready;
use futures_core::task::{Context, Poll};
use futures_io::{AsyncBufRead, AsyncRead, AsyncSeek, AsyncWrite, IoSlice, SeekFrom};
use pin_project_lite::pin_project;
use std::fmt;
use std::io::{self, Write};
use std::pin::Pin;
pin_project! {
/// Wraps a writer and b... | (mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
ready!(self.as_mut().flush_buf(cx))?;
self.project().inner.poll_close(cx)
}
}
impl<W: AsyncRead> AsyncRead for BufWriter<W> {
delegate_async_read!(inner);
}
impl<W: AsyncBufRead> AsyncBufRead for BufWriter<W> {
dele... | poll_close | identifier_name |
buf_writer.rs | use super::DEFAULT_BUF_SIZE;
use futures_core::ready;
use futures_core::task::{Context, Poll};
use futures_io::{AsyncBufRead, AsyncRead, AsyncSeek, AsyncWrite, IoSlice, SeekFrom};
use pin_project_lite::pin_project;
use std::fmt;
use std::io::{self, Write};
use std::pin::Pin;
pin_project! {
/// Wraps a writer and b... |
}
}
if *this.written > 0 {
this.buf.drain(..*this.written);
}
*this.written = 0;
Poll::Ready(ret)
}
delegate_access_inner!(inner, W, ());
/// Returns a reference to the internally buffered data.
pub fn buffer(&self) -> &[u8] {
&s... | {
ret = Err(e);
break;
} | conditional_block |
file_info.rs | use std::fs;
use std::io::BufReader;
fn main() {
std::process::exit(real_main());
}
fn real_main() -> i32 {
let args: Vec<_> = std::env::args().collect();
if args.len() < 2 {
println!("Usage: {} ", args[0]);
return 1;
}
let fname = std::path::Path::new(&*args[1]);
let file = fs... | continue;
}
};
{
let comment = file.comment();
if!comment.is_empty() {
println!("Entry {} comment: {}", i, comment);
}
}
if (*file.name()).ends_with('/') {
println!(
"Entry {} is... | let file = archive.by_index(i).unwrap();
let outpath = match file.enclosed_name() {
Some(path) => path,
None => {
println!("Entry {} has a suspicious path", file.name()); | random_line_split |
file_info.rs | use std::fs;
use std::io::BufReader;
fn main() {
std::process::exit(real_main());
}
fn real_main() -> i32 {
let args: Vec<_> = std::env::args().collect();
if args.len() < 2 {
println!("Usage: {} ", args[0]);
return 1;
}
let fname = std::path::Path::new(&*args[1]);
let file = fs... |
}
0
}
| {
println!(
"Entry {} is a file with name \"{}\" ({} bytes)",
i,
outpath.display(),
file.size()
);
} | conditional_block |
file_info.rs | use std::fs;
use std::io::BufReader;
fn main() |
fn real_main() -> i32 {
let args: Vec<_> = std::env::args().collect();
if args.len() < 2 {
println!("Usage: {} ", args[0]);
return 1;
}
let fname = std::path::Path::new(&*args[1]);
let file = fs::File::open(&fname).unwrap();
let reader = BufReader::new(file);
let mut archi... | {
std::process::exit(real_main());
} | identifier_body |
file_info.rs | use std::fs;
use std::io::BufReader;
fn | () {
std::process::exit(real_main());
}
fn real_main() -> i32 {
let args: Vec<_> = std::env::args().collect();
if args.len() < 2 {
println!("Usage: {} ", args[0]);
return 1;
}
let fname = std::path::Path::new(&*args[1]);
let file = fs::File::open(&fname).unwrap();
let reader... | main | identifier_name |
build.rs | // Copyright (C) 2016, Alberto Corona <ac@albertocorona.com>
// All rights reserved. This file is part of libpm, distributed under the
// BSD 3-clause license. For full terms please see the LICENSE file.
extern crate serde;
extern crate toml;
extern crate tar;
extern crate time;
extern crate walkdir;
extern crate cryp... | i686,
#[serde(rename = "arm")]
arm,
#[serde(rename = "aarch64")]
aarch64,
#[serde(rename = "powerpc")]
powerpc,
#[serde(rename = "any")]
any,
}
impl Default for Arch {
fn default() -> Arch {
match env::consts::ARCH {
"x86_64" => Arch::x86_64,
"i68... | random_line_split | |
build.rs | // Copyright (C) 2016, Alberto Corona <ac@albertocorona.com>
// All rights reserved. This file is part of libpm, distributed under the
// BSD 3-clause license. For full terms please see the LICENSE file.
extern crate serde;
extern crate toml;
extern crate tar;
extern crate time;
extern crate walkdir;
extern crate cryp... |
fn set_checksum(&mut self, path: &Path) -> Result<(), PkgError> {
let mut hasher = sha2::Sha256::new();
let mut buffer = Vec::new();
File::open(path)?.read_to_end(&mut buffer)?;
hasher.input(&buffer);
Ok(self.checksum = hasher.result_str())
}
fn prepend_path(&self,... | {
match fs::metadata(path) {
Ok(s) => self.size = s.len(),
Err(e) => return Err(PkgError::Io(e)),
};
Ok(())
} | identifier_body |
build.rs | // Copyright (C) 2016, Alberto Corona <ac@albertocorona.com>
// All rights reserved. This file is part of libpm, distributed under the
// BSD 3-clause license. For full terms please see the LICENSE file.
extern crate serde;
extern crate toml;
extern crate tar;
extern crate time;
extern crate walkdir;
extern crate cryp... | (&mut self) -> Result<(), PkgError> {
match time::strftime("%m%d%Y%H%M%S", &time::now_utc()) {
Ok(s) => self.time = s,
Err(e) => return Err(PkgError::Time(e)),
};
Ok(())
}
fn set_mode(&mut self, path: &Path) -> Result<(), PkgError> {
let metadata = fs::me... | set_time | identifier_name |
drop.rs | struct Droppable {
name: &'static str,
}
// This trivial implementation of `drop` adds a print to console.
impl Drop for Droppable {
fn drop(&mut self) |
}
fn main() {
let _a = Droppable { name: "a" };
// block A
{
let _b = Droppable { name: "b" };
// block B
{
let _c = Droppable { name: "c" };
let _d = Droppable { name: "d" };
println!("Exiting block B");
}
println!("Just exite... | {
println!("> Dropping {}", self.name);
} | identifier_body |
drop.rs | struct | {
name: &'static str,
}
// This trivial implementation of `drop` adds a print to console.
impl Drop for Droppable {
fn drop(&mut self) {
println!("> Dropping {}", self.name);
}
}
fn main() {
let _a = Droppable { name: "a" };
// block A
{
let _b = Droppable { name: "b" };
... | Droppable | identifier_name |
drop.rs | struct Droppable {
name: &'static str,
}
// This trivial implementation of `drop` adds a print to console.
impl Drop for Droppable {
fn drop(&mut self) {
println!("> Dropping {}", self.name); | }
}
fn main() {
let _a = Droppable { name: "a" };
// block A
{
let _b = Droppable { name: "b" };
// block B
{
let _c = Droppable { name: "c" };
let _d = Droppable { name: "d" };
println!("Exiting block B");
}
println!("Just ... | random_line_split | |
fence.rs | // Copyright 2017 Dasein Phaos aka. Luxko
//
// 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 a... | (&mut self) -> u64 {
unsafe {self.ptr.GetCompletedValue() }
}
/// set the `event` if fence value reachs `value`
// TODO: event lifetime safety?
#[inline]
pub fn set_event_on<'a>(
&mut self, value: u64, event: &'a Event
) -> Result<(), WinError> {unsafe {
WinError::from_h... | get_completed_value | identifier_name |
fence.rs | // Copyright 2017 Dasein Phaos aka. Luxko
//
// 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 a... | const SHARED = 0x1;
const SHARED_CROSS_ADAPTER = 0x2;
}
}
impl Default for FenceFlags {
#[inline]
fn default() -> FenceFlags {
FenceFlags::NONE
}
} | const NONE = 0; | random_line_split |
pipe.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 ... | (&mut self, timeout: Option<u64>) {
self.read_deadline = timeout.map(|a| timer::now() + a).unwrap_or(0);
}
pub fn set_write_timeout(&mut self, timeout: Option<u64>) {
self.write_deadline = timeout.map(|a| timer::now() + a).unwrap_or(0);
}
}
impl Clone for UnixStream {
fn clone(&self) -... | set_read_timeout | identifier_name |
pipe.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 ... | } | random_line_split | |
pipe.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 fn set_read_timeout(&mut self, timeout: Option<u64>) {
self.read_deadline = timeout.map(|a| timer::now() + a).unwrap_or(0);
}
pub fn set_write_timeout(&mut self, timeout: Option<u64>) {
self.write_deadline = timeout.map(|a| timer::now() + a).unwrap_or(0);
}
}
impl Clone for UnixS... | {
let deadline = timeout.map(|a| timer::now() + a).unwrap_or(0);
self.read_deadline = deadline;
self.write_deadline = deadline;
} | identifier_body |
mod.rs | use super::{Block, ListItem, Span};
trait JoinHelper<I>
where
I: Iterator,
{
fn j(self, sep: &'static str) -> String;
}
impl<I> JoinHelper<I> for I
where
I: Iterator<Item = String>,
{
fn j(self, sep: &'static str) -> String {
self.collect::<Vec<String>>().join(sep)
}
}
fn gen_block(b: Blo... |
fn generate_from_li(data: Vec<ListItem>) -> String {
use ListItem::*;
data.into_iter()
.map(|x| {
format!(
"* {}",
match x {
Simple(x) => generate_from_spans(x),
Paragraph(x) => format!(
"{}\n",... | {
use Span::*;
match s {
Break => " \n".to_string(),
Text(x) => x,
Literal(x) => format!("\\{}", x),
Code(x) => format!("`{}`", x),
Link(a, b, None) => format!("[{}]({})", generate_from_spans(a), b),
Link(a, b, Some(c)) => format!("[{}]({} \"{}\")", generate_from... | identifier_body |
mod.rs | use super::{Block, ListItem, Span};
trait JoinHelper<I>
where
I: Iterator,
{
fn j(self, sep: &'static str) -> String;
}
impl<I> JoinHelper<I> for I
where
I: Iterator<Item = String>,
{
fn j(self, sep: &'static str) -> String {
self.collect::<Vec<String>>().join(sep)
}
}
fn gen_block(b: Blo... | Paragraph(x) => format!(
"{}\n",
generate(x)
.lines()
.enumerate()
.map(|(i, x)| if i == 0 {
x.to_string()
} el... | Simple(x) => generate_from_spans(x), | random_line_split |
mod.rs | use super::{Block, ListItem, Span};
trait JoinHelper<I>
where
I: Iterator,
{
fn j(self, sep: &'static str) -> String;
}
impl<I> JoinHelper<I> for I
where
I: Iterator<Item = String>,
{
fn j(self, sep: &'static str) -> String {
self.collect::<Vec<String>>().join(sep)
}
}
fn | (b: Block) -> String {
use Block::*;
match b {
Header(s, level) => format!(
"{} {}",
::std::iter::repeat("#".to_string()).take(level).j(""),
generate_from_spans(s)
),
Paragraph(s) => generate_from_spans(s),
Blockquote(bb) => generate(bb).lines(... | gen_block | identifier_name |
lib.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/. */
//! An implementation of re-entrant mutexes.
//!
//! Re-entrant mutexes are like mutexes, but where it is expected... |
}
#[allow(unsafe_code)]
unsafe impl Send for HandOverHandMutex {}
/// A type for re-entrant mutexes.
///
/// It provides the same interface as https://github.com/rust-lang/rust/blob/master/src/libstd/sys/common/remutex.rs
pub struct ReentrantMutex<T> {
mutex: HandOverHandMutex,
count: Cell<usize>,
data:... | {
self.owner.load(Ordering::Relaxed)
} | identifier_body |
lib.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/. */
//! An implementation of re-entrant mutexes.
//!
//! Re-entrant mutexes are like mutexes, but where it is expected... | (&self) -> ReentrantMutexGuard<T> {
let count = self.count.get().checked_add(1).expect("Overflowed lock count.");
trace!("{:?} Incrementing count to {}.", ThreadId::current(), count);
self.count.set(count);
ReentrantMutexGuard { mutex: self }
}
}
#[must_use]
pub struct ReentrantMute... | mk_guard | identifier_name |
lib.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/. */
//! An implementation of re-entrant mutexes.
//!
//! Re-entrant mutexes are like mutexes, but where it is expected... |
trace!("{:?} Became owner.", ThreadId::current());
}
Ok(self.mk_guard())
}
pub fn try_lock(&self) -> TryLockResult<ReentrantMutexGuard<T>> {
trace!("{:?} Try locking.", ThreadId::current());
if self.mutex.owner()!= Some(ThreadId::current()) {
trace!("{:?... | {
trace!("{:?} Poison!", ThreadId::current());
return Err(PoisonError::new(self.mk_guard()));
} | conditional_block |
lib.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/. */
//! An implementation of re-entrant mutexes.
//!
//! Re-entrant mutexes are like mutexes, but where it is expected... | data: T,
}
#[allow(unsafe_code)]
unsafe impl<T> Sync for ReentrantMutex<T> where T: Send {}
impl<T> ReentrantMutex<T> {
pub fn new(data: T) -> ReentrantMutex<T> {
trace!("{:?} Creating new lock.", ThreadId::current());
ReentrantMutex {
mutex: HandOverHandMutex::new(),
c... | /// It provides the same interface as https://github.com/rust-lang/rust/blob/master/src/libstd/sys/common/remutex.rs
pub struct ReentrantMutex<T> {
mutex: HandOverHandMutex,
count: Cell<usize>, | random_line_split |
cell_range.rs | // Copyright 2015 The Noise-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ... |
fn scaled_cell2_range(seed: &Seed, point: &Point2<f64>) -> f64 {
cell2_range(seed, &[point[0] / 16.0, point[1] / 16.0]) * 2.0 - 1.0
}
fn scaled_cell3_range(seed: &Seed, point: &Point2<f64>) -> f64 {
cell3_range(seed, &[point[0] / 16.0, point[1] / 16.0, point[0] / 32.0]) * 2.0 - 1.0
}
fn scaled_cell4_range(s... | {
debug::render_png("cell2_range.png", &Seed::new(0), 1024, 1024, scaled_cell2_range);
debug::render_png("cell3_range.png", &Seed::new(0), 1024, 1024, scaled_cell3_range);
debug::render_png("cell4_range.png", &Seed::new(0), 1024, 1024, scaled_cell4_range);
println!("\nGenerated cell2_range.png, cell3_ra... | identifier_body |
cell_range.rs | // Copyright 2015 The Noise-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ... | cell3_range(seed, &[point[0] / 16.0, point[1] / 16.0, point[0] / 32.0]) * 2.0 - 1.0
}
fn scaled_cell4_range(seed: &Seed, point: &Point2<f64>) -> f64 {
cell4_range(seed, &[point[0] / 16.0, point[1] / 16.0, point[0] / 32.0, point[1] / 32.0]) * 2.0 - 1.0
} | fn scaled_cell3_range(seed: &Seed, point: &Point2<f64>) -> f64 { | random_line_split |
cell_range.rs | // Copyright 2015 The Noise-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ... | () {
debug::render_png("cell2_range.png", &Seed::new(0), 1024, 1024, scaled_cell2_range);
debug::render_png("cell3_range.png", &Seed::new(0), 1024, 1024, scaled_cell3_range);
debug::render_png("cell4_range.png", &Seed::new(0), 1024, 1024, scaled_cell4_range);
println!("\nGenerated cell2_range.png, cell3... | main | identifier_name |
issue-45107-unnecessary-unsafe-in-closure.rs | // Copyright 2017 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 ... | |y: &mut Vec<u32>| { unsafe {
y.set_len(48);
} };
}
| {
let mut v = Vec::<i32>::with_capacity(24);
unsafe {
let f = |v: &mut Vec<_>| {
unsafe { //~ ERROR unnecessary `unsafe`
v.set_len(24);
|w: &mut Vec<u32>| { unsafe { //~ ERROR unnecessary `unsafe`
w.set_len(32);
} };
... | identifier_body |
issue-45107-unnecessary-unsafe-in-closure.rs | // Copyright 2017 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 ... |
|y: &mut Vec<u32>| { unsafe {
y.set_len(48);
} };
} | random_line_split | |
issue-45107-unnecessary-unsafe-in-closure.rs | // Copyright 2017 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 ... | () {
let mut v = Vec::<i32>::with_capacity(24);
unsafe {
let f = |v: &mut Vec<_>| {
unsafe { //~ ERROR unnecessary `unsafe`
v.set_len(24);
|w: &mut Vec<u32>| { unsafe { //~ ERROR unnecessary `unsafe`
w.set_len(32);
} };
... | main | identifier_name |
node.rs | use crate::{Frame, Sample};
/// Types to be used as a **Node** within the DSP **Graph**.
pub trait Node<F>
where
F: Frame,
{
/// Request audio from the **Node** given some `sample_hz` (aka sample rate in hertz).
/// If the **Node** has no inputs, the `buffer` will be zeroed.
/// If the **Node** has som... | <F::Sample as Sample>::IDENTITY
}
}
impl<F> Node<F> for Box<dyn Node<F>>
where
F: Frame,
{
#[inline]
fn audio_requested(&mut self, buffer: &mut [F], sample_hz: f64) {
(**self).audio_requested(buffer, sample_hz);
}
#[inline]
fn dry(&self) -> <F::Sample as Sample>::Float {
... | random_line_split | |
node.rs | use crate::{Frame, Sample};
/// Types to be used as a **Node** within the DSP **Graph**.
pub trait Node<F>
where
F: Frame,
{
/// Request audio from the **Node** given some `sample_hz` (aka sample rate in hertz).
/// If the **Node** has no inputs, the `buffer` will be zeroed.
/// If the **Node** has som... | (&self) -> <F::Sample as Sample>::Float {
(**self).dry()
}
#[inline]
fn wet(&self) -> <F::Sample as Sample>::Float {
(**self).wet()
}
}
| dry | identifier_name |
node.rs | use crate::{Frame, Sample};
/// Types to be used as a **Node** within the DSP **Graph**.
pub trait Node<F>
where
F: Frame,
{
/// Request audio from the **Node** given some `sample_hz` (aka sample rate in hertz).
/// If the **Node** has no inputs, the `buffer` will be zeroed.
/// If the **Node** has som... |
#[inline]
fn wet(&self) -> <F::Sample as Sample>::Float {
(**self).wet()
}
}
| {
(**self).dry()
} | identifier_body |
textencoder.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/. */
use crate::dom::bindings::codegen::Bindings::TextEncoderBinding;
use crate::dom::bindings::codegen::Bindings::Tex... |
}
impl TextEncoderMethods for TextEncoder {
// https://encoding.spec.whatwg.org/#dom-textencoder-encoding
fn Encoding(&self) -> DOMString {
DOMString::from("utf-8")
}
#[allow(unsafe_code)]
// https://encoding.spec.whatwg.org/#dom-textencoder-encode
fn Encode(&self, cx: JSContext, inpu... | {
Ok(TextEncoder::new(global))
} | identifier_body |
textencoder.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/. */
use crate::dom::bindings::codegen::Bindings::TextEncoderBinding;
use crate::dom::bindings::codegen::Bindings::Tex... | }
impl TextEncoder {
fn new_inherited() -> TextEncoder {
TextEncoder {
reflector_: Reflector::new(),
}
}
pub fn new(global: &GlobalScope) -> DomRoot<TextEncoder> {
reflect_dom_object(
Box::new(TextEncoder::new_inherited()),
global,
Te... | pub struct TextEncoder {
reflector_: Reflector, | random_line_split |
textencoder.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/. */
use crate::dom::bindings::codegen::Bindings::TextEncoderBinding;
use crate::dom::bindings::codegen::Bindings::Tex... | {
reflector_: Reflector,
}
impl TextEncoder {
fn new_inherited() -> TextEncoder {
TextEncoder {
reflector_: Reflector::new(),
}
}
pub fn new(global: &GlobalScope) -> DomRoot<TextEncoder> {
reflect_dom_object(
Box::new(TextEncoder::new_inherited()),
... | TextEncoder | identifier_name |
dispnew.rs | //! Updating of data structures for redisplay.
use std::{cmp, ptr};
use remacs_macros::lisp_fn;
use remacs_sys::{current_timespec, dtotimespec, timespec_add, timespec_sub,
wait_reading_process_output};
use remacs_sys::WAIT_READING_MAX;
use floatfns::extract_float;
use lisp::LispObject;
use lisp::def... |
LispObject::constant_nil()
}
include!(concat!(env!("OUT_DIR"), "/dispnew_exports.rs"));
| {
let mut t = unsafe { dtotimespec(duration) };
let tend = unsafe { timespec_add(current_timespec(), t) };
while !t.tv_sec < 0 && (t.tv_sec > 0 || t.tv_nsec > 0) {
unsafe {
wait_reading_process_output(
cmp::min(t.tv_sec as i64, WAIT_READING_MAX),
... | conditional_block |
dispnew.rs | //! Updating of data structures for redisplay.
use std::{cmp, ptr};
use remacs_macros::lisp_fn;
use remacs_sys::{current_timespec, dtotimespec, timespec_add, timespec_sub,
wait_reading_process_output};
use remacs_sys::WAIT_READING_MAX;
use floatfns::extract_float;
use lisp::LispObject;
use lisp::def... | cmp::min(t.tv_sec as i64, WAIT_READING_MAX),
t.tv_nsec as i32,
0,
true,
LispObject::constant_nil().to_raw(),
ptr::null(),
0,
)
};
t = unsafe... | let mut t = unsafe { dtotimespec(duration) };
let tend = unsafe { timespec_add(current_timespec(), t) };
while !t.tv_sec < 0 && (t.tv_sec > 0 || t.tv_nsec > 0) {
unsafe {
wait_reading_process_output( | random_line_split |
dispnew.rs | //! Updating of data structures for redisplay.
use std::{cmp, ptr};
use remacs_macros::lisp_fn;
use remacs_sys::{current_timespec, dtotimespec, timespec_add, timespec_sub,
wait_reading_process_output};
use remacs_sys::WAIT_READING_MAX;
use floatfns::extract_float;
use lisp::LispObject;
use lisp::def... | (seconds: LispObject, milliseconds: LispObject) -> LispObject {
let mut duration = extract_float(seconds.to_raw());
if milliseconds.is_not_nil() {
let milliseconds = milliseconds.as_fixnum_or_error() as f64;
duration += milliseconds / 1000.0;
}
if duration > 0.0 {
let mut t = uns... | sleep_for | identifier_name |
dispnew.rs | //! Updating of data structures for redisplay.
use std::{cmp, ptr};
use remacs_macros::lisp_fn;
use remacs_sys::{current_timespec, dtotimespec, timespec_add, timespec_sub,
wait_reading_process_output};
use remacs_sys::WAIT_READING_MAX;
use floatfns::extract_float;
use lisp::LispObject;
use lisp::def... | };
t = unsafe { timespec_sub(tend, current_timespec()) };
}
}
LispObject::constant_nil()
}
include!(concat!(env!("OUT_DIR"), "/dispnew_exports.rs"));
| {
let mut duration = extract_float(seconds.to_raw());
if milliseconds.is_not_nil() {
let milliseconds = milliseconds.as_fixnum_or_error() as f64;
duration += milliseconds / 1000.0;
}
if duration > 0.0 {
let mut t = unsafe { dtotimespec(duration) };
let tend = unsafe { tim... | identifier_body |
compression_dict.rs | // Copyright (c) 2020-present, Gregory Szorc
// All rights reserved.
//
// This software may be modified and distributed under the terms
// of the BSD license. See the LICENSE file for details.
use {
crate::{
compression_parameters::{get_cctx_parameter, int_to_strategy, ZstdCompressionParameters},
... | ;
(d, steps, level)
} else {
(d, steps, level)
};
let params = zstd_sys::ZDICT_fastCover_params_t {
k,
d,
f,
steps,
nbThreads: threads,
splitPoint: split_point,
accel,
shrinkDict: 0,
shrinkDictMaxRegression: 0,
... | { 3 } | conditional_block |
compression_dict.rs | // Copyright (c) 2020-present, Gregory Szorc
// All rights reserved.
//
// This software may be modified and distributed under the terms
// of the BSD license. See the LICENSE file for details.
use {
crate::{
compression_parameters::{get_cctx_parameter, int_to_strategy, ZstdCompressionParameters},
... | (&mut self, dctx: &DCtx) -> PyResult<()> {
self.ensure_ddict()?;
dctx.load_prepared_dict(self.ddict.as_ref().unwrap())
.map_err(|msg| {
ZstdError::new_err(format!("unable to reference prepared dictionary: {}", msg))
})
}
}
#[pymethods]
impl ZstdCompressionDic... | load_into_dctx | identifier_name |
compression_dict.rs | // Copyright (c) 2020-present, Gregory Szorc
// All rights reserved.
//
// This software may be modified and distributed under the terms
// of the BSD license. See the LICENSE file for details.
use {
crate::{
compression_parameters::{get_cctx_parameter, int_to_strategy, ZstdCompressionParameters},
... | {
Ok(zstd_sys::ZSTD_dictContentType_e::ZSTD_dct_auto)
} else if dict_type == Some(zstd_sys::ZSTD_dictContentType_e::ZSTD_dct_fullDict as u32) {
Ok(zstd_sys::ZSTD_dictContentType_e::ZSTD_dct_fullDict)
} else if dict_type == Some(zstd_sys::ZSTD_dictContentType_e::ZSTD_dct_r... | #[args(data, dict_type = "None")]
fn new(py: Python, buffer: PyBuffer<u8>, dict_type: Option<u32>) -> PyResult<Self> {
let dict_type = if dict_type == Some(zstd_sys::ZSTD_dictContentType_e::ZSTD_dct_auto as u32) | random_line_split |
compression_dict.rs | // Copyright (c) 2020-present, Gregory Szorc
// All rights reserved.
//
// This software may be modified and distributed under the terms
// of the BSD license. See the LICENSE file for details.
use {
crate::{
compression_parameters::{get_cctx_parameter, int_to_strategy, ZstdCompressionParameters},
... | let min_match =
get_cctx_parameter(source_params, zstd_sys::ZSTD_cParameter::ZSTD_c_minMatch)?;
let target_length = get_cctx_parameter(
source_params,
zstd_sys::ZSTD_cParameter::ZSTD_c_targetLength,
)?;
let strategy =
... | {
let params = if let Some(level) = level {
if compression_params.is_some() {
return Err(PyValueError::new_err(
"must only specify one of level or compression_params",
));
}
unsafe { zstd_sys::ZSTD_getCParams(level, 0, self... | identifier_body |
op.rs | pub const HALT: u8 = 0b111111;
pub const PUSHENV: u8 = 1;
pub const POPENV: u8 = 1;
pub const GETVAR: u8 = 2;
pub const SETVAR: u8 = 3;
pub const NEWENV: u8 = 4;
pub const GETELEM: u8 = 5;
pub const SETELEM: u8 = 6;
pub const PUSHLIT: u8 = 7;
pub const CALL: u8 = 8;
pub const RET: u8 = 9;
pub const POPVAL: u8 = 10;
pu... | pub const JT: u8 = 33;
pub const JF: u8 = 34; | pub const TEST: u8 = 20;
pub const JMP: u8 = 32; | random_line_split |
key_value_split.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the F... | () {
let s = String::from("foo='bar'").into_kv().unwrap();
assert_eq!(KeyValue::new(String::from("foo"), String::from("\'bar\'")), s);
}
#[test]
fn test_double_quoted() {
let s = String::from("foo=\"bar\"").into_kv().unwrap();
assert_eq!(KeyValue::new(String::from("foo"), St... | test_single_quoted | identifier_name |
key_value_split.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the F... | }
#[test]
fn test_not_quoted() {
let s = String::from("foo=bar").into_kv().unwrap();
assert_eq!(KeyValue::new(String::from("foo"), String::from("bar")), s);
}
} | #[test]
fn test_single_and_double_quoted() {
let s = String::from("foo=\'bar\"").into_kv().unwrap();
assert_eq!(KeyValue::new(String::from("foo"), String::from("\'bar\"")), s); | random_line_split |
key_value_split.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the F... |
#[test]
fn test_single_and_double_quoted() {
let s = String::from("foo=\'bar\"").into_kv().unwrap();
assert_eq!(KeyValue::new(String::from("foo"), String::from("\'bar\"")), s);
}
#[test]
fn test_not_quoted() {
let s = String::from("foo=bar").into_kv().unwrap();
ass... | {
let s = String::from("foo=\"bar\'").into_kv().unwrap();
assert_eq!(KeyValue::new(String::from("foo"), String::from("\"bar\'")), s);
} | identifier_body |
lib.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... | //! Example usage for creating a network service and adding an IO handler:
//!
//! ```rust
//! extern crate ethcore_io;
//! use ethcore_io::*;
//! use std::sync::Arc;
//!
//! struct MyHandler;
//!
//! #[derive(Clone)]
//! struct MyMessage {
//! data: u32
//! }
//!
//! impl IoHandler<MyMessage> for MyHandler {
//! fn ... | //! | random_line_split |
lib.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... |
/// Called when an IO stream can be written to
fn stream_writable(&self, _io: &IoContext<Message>, _stream: StreamToken) {}
/// Register a new stream with the event loop
fn register_stream(&self, _stream: StreamToken, _reg: Token, _event_loop: &mut EventLoop<IoManager<Message>>) {}
/// Re-register a stream with t... | {} | identifier_body |
lib.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... | (err: ::std::io::Error) -> IoError {
IoError::StdIo(err)
}
}
impl<Message> From<NotifyError<service::IoMessage<Message>>> for IoError where Message: Send + Clone {
fn from(_err: NotifyError<service::IoMessage<Message>>) -> IoError {
IoError::Mio(::std::io::Error::new(::std::io::ErrorKind::ConnectionAborted, "Net... | from | identifier_name |
lib.rs | //! xz-decom
//!
//! XZ Decompression using xz-embedded
//!
//! This crate provides XZ decompression using the xz-embedded library.
//! This means that compression and perhaps some advanced features are not supported.
//!
extern crate xz_embedded_sys as raw;
use std::error::Error;
use std::fmt;
/// Error type for p... | <'a>(&'a self) -> Option<&'a Error> {
if let Some(ref e) = self.code {
Some(e)
} else {
None
}
}
}
impl fmt::Display for XZError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", self)
}
}
/// Decompress some data
///
/// The... | cause | identifier_name |
lib.rs | //! xz-decom
//!
//! XZ Decompression using xz-embedded
//!
//! This crate provides XZ decompression using the xz-embedded library.
//! This means that compression and perhaps some advanced features are not supported.
//!
extern crate xz_embedded_sys as raw;
use std::error::Error;
use std::fmt;
/// Error type for p... | in_size: compressed_data.len() as u64,
in_pos:0,
out: out_buf.as_mut_ptr(),
out_pos: 0,
out_size: out_size as u64,
};
loop {
let ret = unsafe { raw::xz_dec_run(state, &mut buf) };
//println!("Decomp returned {:?}", ret);
if ret == raw::xz_ret::XZ... | let mut out_buf = Vec::with_capacity(out_size);
out_buf.resize(out_size, 0);
let mut buf = raw::xz_buf {
_in: compressed_data.as_ptr(), | random_line_split |
lib.rs | //! xz-decom
//!
//! XZ Decompression using xz-embedded
//!
//! This crate provides XZ decompression using the xz-embedded library.
//! This means that compression and perhaps some advanced features are not supported.
//!
extern crate xz_embedded_sys as raw;
use std::error::Error;
use std::fmt;
/// Error type for p... | _in: compressed_data.as_ptr(),
in_size: compressed_data.len() as u64,
in_pos:0,
out: out_buf.as_mut_ptr(),
out_pos: 0,
out_size: out_size as u64,
};
loop {
let ret = unsafe { raw::xz_dec_run(state, &mut buf) };
//println!("Decomp returned {:?}", ... | {
unsafe {
// Note that these return void, and can't fail
raw::xz_crc32_init();
raw::xz_crc64_init();
}
let state = unsafe {
raw::xz_dec_init(raw::xz_mode::XZ_DYNALLOC, 1 << 26)
};
if state.is_null() {
return Err(XZError{msg: "Failed to initialize", code: Non... | identifier_body |
lib.rs | //! xz-decom
//!
//! XZ Decompression using xz-embedded
//!
//! This crate provides XZ decompression using the xz-embedded library.
//! This means that compression and perhaps some advanced features are not supported.
//!
extern crate xz_embedded_sys as raw;
use std::error::Error;
use std::fmt;
/// Error type for p... |
if buf.in_pos == buf.in_size {
// if we're reached the end of out input buffer, but we didn't hit
// XZ_STREAM_END, i think this is an error
return Err(XZError{msg: "Reached end of input buffer", code: None})
}
}
unsafe { raw::xz_dec_end(state) };
Ok(ou... | {
return Err(XZError{msg: "Decompressing error", code: Some(raw::XZRawError::from(ret))})
} | conditional_block |
message.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/. */
use crate::rpc::LayoutRPC;
use crate::{OpaqueStyleAndLayoutData, PendingImage, TrustedNodeAddress};
use app_units... |
#[derive(Debug, PartialEq)]
pub enum QueryMsg {
ContentBoxQuery(OpaqueNode),
ContentBoxesQuery(OpaqueNode),
NodeGeometryQuery(OpaqueNode),
NodeScrollGeometryQuery(OpaqueNode),
OffsetParentQuery(OpaqueNode),
TextIndexQuery(OpaqueNode, Point2D<f32>),
NodesFromPointQuery(Point2D<f32>, NodesFro... | All,
Topmost,
} | random_line_split |
message.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/. */
use crate::rpc::LayoutRPC;
use crate::{OpaqueStyleAndLayoutData, PendingImage, TrustedNodeAddress};
use app_units... | {
All,
Topmost,
}
#[derive(Debug, PartialEq)]
pub enum QueryMsg {
ContentBoxQuery(OpaqueNode),
ContentBoxesQuery(OpaqueNode),
NodeGeometryQuery(OpaqueNode),
NodeScrollGeometryQuery(OpaqueNode),
OffsetParentQuery(OpaqueNode),
TextIndexQuery(OpaqueNode, Point2D<f32>),
NodesFromPointQ... | NodesFromPointQueryType | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.