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 |
|---|---|---|---|---|
buttons-input.rs | /*
* Copyright (c) 2018 Boucher, Antoni <bouanto@zoho.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy,... | prelude::LabelExt,
prelude::OrientableExt,
prelude::WidgetExt,
};
use gtk::Orientation::{Horizontal, Vertical};
use relm::{Relm, Widget};
use relm_derive::{Msg, widget};
use self::Msg::*;
pub struct Model {
left_text: String,
relm: Relm<Win>,
right_text: String,
text: String,
}
#[derive(C... | Inhibit,
prelude::ButtonExt,
prelude::EntryExt, | random_line_split |
buttons-input.rs | /*
* Copyright (c) 2018 Boucher, Antoni <bouanto@zoho.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy,... |
fn update(&mut self, event: Msg) {
match event {
Cancel => {
self.model.left_text = String::new();
self.model.right_text = String::new();
self.model.text = String::new();
self.model.relm.stream().emit(DataCleared);
},
... | {
Model {
left_text: String::new(),
right_text: String::new(),
relm: relm.clone(),
text: String::new(),
}
} | identifier_body |
basic.rs | #![feature(proc_macro)]
extern crate fn_mut;
use fn_mut::fn_mut;
struct Test1(u64);
impl Test1 {
#[fn_mut]
fn test1(&self, text: &str) -> u64 |
#[fn_mut(enable_attrs = "text")]
fn test2(&self, text: &str) -> Option<&u64> {
if_mut! {
println!("This is mut fn: {}", text);
}
if_const! {
println!("This is const fn: {}", text);
}
Some(ptr!(self.0))
}
}
#[test]
fn test1() {
let mut t =... | {
if_mut! {
self.0 + 10
}
if_const! {
self.0 + 20
}
} | identifier_body |
basic.rs | #![feature(proc_macro)]
extern crate fn_mut;
use fn_mut::fn_mut;
struct Test1(u64);
impl Test1 {
#[fn_mut]
fn | (&self, text: &str) -> u64 {
if_mut! {
self.0 + 10
}
if_const! {
self.0 + 20
}
}
#[fn_mut(enable_attrs = "text")]
fn test2(&self, text: &str) -> Option<&u64> {
if_mut! {
println!("This is mut fn: {}", text);
}
if_con... | test1 | identifier_name |
basic.rs | struct Test1(u64);
impl Test1 {
#[fn_mut]
fn test1(&self, text: &str) -> u64 {
if_mut! {
self.0 + 10
}
if_const! {
self.0 + 20
}
}
#[fn_mut(enable_attrs = "text")]
fn test2(&self, text: &str) -> Option<&u64> {
if_mut! {
pri... | #![feature(proc_macro)]
extern crate fn_mut;
use fn_mut::fn_mut;
| random_line_split | |
rtc.rs | use core::intrinsics::{volatile_load, volatile_store};
use crate::memory::Frame;
use crate::paging::{ActivePageTable, PhysicalAddress, Page, PageFlags, TableKind, VirtualAddress};
use crate::time;
static RTC_DR: u32 = 0x000;
static RTC_MR: u32 = 0x004;
static RTC_LR: u32 = 0x008;
static RTC_CR: u32 = 0x00c;
static RT... |
unsafe fn write(&mut self, reg: u32, value: u32) {
volatile_store((self.address + reg as usize) as *mut u32, value);
}
pub fn time(&mut self) -> u64 {
let seconds = unsafe { self.read(RTC_DR) } as u64;
seconds
}
}
| {
let val = volatile_load((self.address + reg as usize) as *const u32);
val
} | identifier_body |
rtc.rs | use core::intrinsics::{volatile_load, volatile_store};
use crate::memory::Frame;
use crate::paging::{ActivePageTable, PhysicalAddress, Page, PageFlags, TableKind, VirtualAddress};
use crate::time;
static RTC_DR: u32 = 0x000;
static RTC_MR: u32 = 0x004;
static RTC_LR: u32 = 0x008;
static RTC_CR: u32 = 0x00c;
static RT... | let result = active_table.map_to(page, frame, PageFlags::new().write(true));
result.flush();
}
self.address = crate::KERNEL_DEVMAP_OFFSET + 0x09010000;
}
unsafe fn read(&self, reg: u32) -> u32 {
let val = volatile_load((self.address + reg as usize) as *const u32... |
for frame in Frame::range_inclusive(start_frame, end_frame) {
let page = Page::containing_address(VirtualAddress::new(frame.start_address().data() + crate::KERNEL_DEVMAP_OFFSET)); | random_line_split |
rtc.rs | use core::intrinsics::{volatile_load, volatile_store};
use crate::memory::Frame;
use crate::paging::{ActivePageTable, PhysicalAddress, Page, PageFlags, TableKind, VirtualAddress};
use crate::time;
static RTC_DR: u32 = 0x000;
static RTC_MR: u32 = 0x004;
static RTC_LR: u32 = 0x008;
static RTC_CR: u32 = 0x00c;
static RT... | (&mut self) {
let mut active_table = ActivePageTable::new(TableKind::Kernel);
let start_frame = Frame::containing_address(PhysicalAddress::new(0x09010000));
let end_frame = Frame::containing_address(PhysicalAddress::new(0x09010000 + 0x1000 - 1));
for frame in Frame::range_inclusive(sta... | init | identifier_name |
iter.rs | use std::sync::atomic::Ordering;
use ::key::{hashkey_to_string};
use ::table::*;
use ::state::SlotState;
pub struct CounterIter<'a> {
pub slots: &'a VectorTable,
pub index: usize,
}
impl<'a> Iterator for CounterIter<'a> {
type Item = (String, usize);
fn | (&mut self) -> Option<Self::Item> {
let ret;
loop {
let slot_opt = self.slots.get_index(self.index);
match slot_opt {
Some(slot) => match slot.state.get() {
SlotState::Alive | SlotState::Copying | SlotState::Copied => {
... | next | identifier_name |
iter.rs | use std::sync::atomic::Ordering;
use ::key::{hashkey_to_string};
use ::table::*;
use ::state::SlotState;
pub struct CounterIter<'a> {
pub slots: &'a VectorTable,
pub index: usize,
}
impl<'a> Iterator for CounterIter<'a> {
type Item = (String, usize);
fn next(&mut self) -> Option<Self::Item> | },
None => {
self.slots.remove_thread();
ret = None;
break;
},
}
}
ret
}
}
| {
let ret;
loop {
let slot_opt = self.slots.get_index(self.index);
match slot_opt {
Some(slot) => match slot.state.get() {
SlotState::Alive | SlotState::Copying | SlotState::Copied => {
let key_ptr = slot.key.load(Orderi... | identifier_body |
iter.rs | use std::sync::atomic::Ordering;
use ::key::{hashkey_to_string};
use ::table::*;
use ::state::SlotState;
pub struct CounterIter<'a> {
pub slots: &'a VectorTable,
pub index: usize,
}
impl<'a> Iterator for CounterIter<'a> {
type Item = (String, usize);
fn next(&mut self) -> Option<Self::Item> {
... |
},
None => {
self.slots.remove_thread();
ret = None;
break;
},
}
}
ret
}
}
| {
self.index += 1;
} | conditional_block |
iter.rs | use std::sync::atomic::Ordering;
use ::key::{hashkey_to_string};
use ::table::*;
use ::state::SlotState;
pub struct CounterIter<'a> {
pub slots: &'a VectorTable,
pub index: usize,
}
impl<'a> Iterator for CounterIter<'a> {
type Item = (String, usize);
fn next(&mut self) -> Option<Self::Item> {
... | self.index += 1;
}
},
None => {
self.slots.remove_thread();
ret = None;
break;
},
}
}
ret
}
} | random_line_split | |
label.rs | use winapi::um::{
winuser::{WS_VISIBLE, WS_DISABLED, SS_WORDELLIPSIS},
wingdi::DeleteObject
};
use winapi::shared::windef::HBRUSH;
use crate::win32::window_helper as wh;
use crate::win32::base_helper::check_hwnd;
use crate::{Font, NwgError, HTextAlign, VTextAlign, RawEventHandler, unbind_raw_event_handler};
us... |
// Calculate NC area to center text.
let mut client: RECT = mem::zeroed();
let mut window: RECT = mem::zeroed();
GetClientRect(hwnd, &mut client);
GetWindowRect(hwnd, &mut window);
let window_height... | let client_height = r.bottom * newline_count;
SelectObject(dc, old);
ReleaseDC(hwnd, dc); | random_line_split |
label.rs | use winapi::um::{
winuser::{WS_VISIBLE, WS_DISABLED, SS_WORDELLIPSIS},
wingdi::DeleteObject
};
use winapi::shared::windef::HBRUSH;
use crate::win32::window_helper as wh;
use crate::win32::base_helper::check_hwnd;
use crate::{Font, NwgError, HTextAlign, VTextAlign, RawEventHandler, unbind_raw_event_handler};
us... | (mut self, align: VTextAlign) -> LabelBuilder<'a> {
self.v_align = align;
self
}
pub fn parent<C: Into<ControlHandle>>(mut self, p: C) -> LabelBuilder<'a> {
self.parent = Some(p.into());
self
}
pub fn build(self, out: &mut Label) -> Result<(), NwgError> {
use wi... | v_align | identifier_name |
label.rs | use winapi::um::{
winuser::{WS_VISIBLE, WS_DISABLED, SS_WORDELLIPSIS},
wingdi::DeleteObject
};
use winapi::shared::windef::HBRUSH;
use crate::win32::window_helper as wh;
use crate::win32::base_helper::check_hwnd;
use crate::{Font, NwgError, HTextAlign, VTextAlign, RawEventHandler, unbind_raw_event_handler};
us... |
/// Return the position of the label in the parent window
pub fn position(&self) -> (i32, i32) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_window_position(handle) }
}
/// Set the position of the label in the parent window
pub fn set_position(&s... | {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_window_size(handle, x, y, false) }
} | identifier_body |
label.rs | use winapi::um::{
winuser::{WS_VISIBLE, WS_DISABLED, SS_WORDELLIPSIS},
wingdi::DeleteObject
};
use winapi::shared::windef::HBRUSH;
use crate::win32::window_helper as wh;
use crate::win32::base_helper::check_hwnd;
use crate::{Font, NwgError, HTextAlign, VTextAlign, RawEventHandler, unbind_raw_event_handler};
us... | else {
for &c in buffer.iter() {
if c == b'\n' as u16 {
newline_count += 1;
}
}
DrawTextW(dc, buffer.as_ptr(), ... | {
let calc: [u16;2] = [75, 121];
DrawTextW(dc, calc.as_ptr(), 2, &mut r, DT_CALCRECT | DT_LEFT);
} | conditional_block |
complex_types_macros.rs | extern crate serde;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate rusted_cypher;
use rusted_cypher::GraphClient;
use rusted_cypher::cypher::result::Row;
const URI: &'static str = "http://neo4j:neo4j@127.0.0.1:7474/db/data";
#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct Language {
... | let lang: Language = row.get("n").unwrap();
assert_eq!(rust, lang);
graph.exec("MATCH (n:NTLY_INTG_TEST_MACROS_2) DELETE n").unwrap();
} | random_line_split | |
complex_types_macros.rs | extern crate serde;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate rusted_cypher;
use rusted_cypher::GraphClient;
use rusted_cypher::cypher::result::Row;
const URI: &'static str = "http://neo4j:neo4j@127.0.0.1:7474/db/data";
#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct Language {
... | () {
let graph = GraphClient::connect(URI).unwrap();
let stmt = cypher_stmt!("MATCH (n:NTLY_INTG_TEST_MACROS_1) RETURN n").unwrap();
let result = graph.exec(stmt);
assert!(result.is_ok());
}
#[test]
fn save_retrive_struct() {
let rust = Language {
name: "Rust".to_owned(),
level: "... | without_params | identifier_name |
eew.rs | use chrono::{DateTime, Utc};
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum IssuePattern { Cancel, IntensityOnly, LowAccuracy, HighAccuracy }
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum Source { Tokyo, Osaka }
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum Kind { Normal, Drill, Cancel, Drill... | {
pub issue_pattern: IssuePattern,
pub source: Source,
pub kind: Kind,
pub issued_at: DateTime<Utc>,
pub occurred_at: DateTime<Utc>,
pub id: String,
pub status: Status,
pub number: u32, // we don't accept an EEW which has no telegram number
pub detail: Option<EEWDetail>,
}
#[derive(PartialEq, Debug, Clone... | EEW | identifier_name |
eew.rs | use chrono::{DateTime, Utc};
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum IssuePattern { Cancel, IntensityOnly, LowAccuracy, HighAccuracy }
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum Source { Tokyo, Osaka }
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum Kind { Normal, Drill, Cancel, Drill... | #[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum Status { Normal, Correction, CancelCorrection, LastWithCorrection, Last, Unknown }
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum EpicenterAccuracy {
Single, Territory, GridSearchLow, GridSearchHigh,
NIEDLow, NIEDHigh, EPOSLow, EPOSHigh, Unknown
}
#[deriv... | random_line_split | |
fn_must_use.rs | // check-pass
#![warn(unused_must_use)]
#[derive(PartialEq, Eq)]
struct MyStruct {
n: usize,
}
impl MyStruct {
#[must_use]
fn need_to_use_this_method_value(&self) -> usize {
self.n
}
#[must_use]
fn need_to_use_this_associated_function_value() -> isize {
-1
}
}
trait Even... | m == n; //~ WARN unused comparison
}
| need_to_use_this_value(); //~ WARN unused return value
let mut m = MyStruct { n: 2 };
let n = MyStruct { n: 3 };
m.need_to_use_this_method_value(); //~ WARN unused return value
m.is_even(); // trait method!
//~^ WARN unused return value
MyStruct::need_to_use_this_associated_function_value... | identifier_body |
fn_must_use.rs | // check-pass
#![warn(unused_must_use)]
#[derive(PartialEq, Eq)]
struct MyStruct {
n: usize,
}
impl MyStruct {
#[must_use]
fn need_to_use_this_method_value(&self) -> usize { | }
#[must_use]
fn need_to_use_this_associated_function_value() -> isize {
-1
}
}
trait EvenNature {
#[must_use = "no side effects"]
fn is_even(&self) -> bool;
}
impl EvenNature for MyStruct {
fn is_even(&self) -> bool {
self.n % 2 == 0
}
}
trait Replaceable {
fn re... | self.n | random_line_split |
fn_must_use.rs | // check-pass
#![warn(unused_must_use)]
#[derive(PartialEq, Eq)]
struct MyStruct {
n: usize,
}
impl MyStruct {
#[must_use]
fn need_to_use_this_method_value(&self) -> usize {
self.n
}
#[must_use]
fn need_to_use_this_associated_function_value() -> isize {
-1
}
}
trait Even... | -> bool {
false
}
fn main() {
need_to_use_this_value(); //~ WARN unused return value
let mut m = MyStruct { n: 2 };
let n = MyStruct { n: 3 };
m.need_to_use_this_method_value(); //~ WARN unused return value
m.is_even(); // trait method!
//~^ WARN unused return value
MyStruct::need_t... | ed_to_use_this_value() | identifier_name |
main.rs | #[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
| fn main() {
let rect1 = Rectangle {
width: 30,
height: 50,
};
let rect2 = Rectangle {
width: 10,
height: 40,
};
let rect3 = Rectangle {
width: 60,
height: 45,
};
println!(
"The area of the rectangle is {} square pixels.",
rect1... | fn can_hold(&self, other: &Rectangle) -> bool {
self.width > other.width && self.height > other.height
}
}
| random_line_split |
main.rs | #[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
fn can_hold(&self, other: &Rectangle) -> bool |
}
fn main() {
let rect1 = Rectangle {
width: 30,
height: 50,
};
let rect2 = Rectangle {
width: 10,
height: 40,
};
let rect3 = Rectangle {
width: 60,
height: 45,
};
println!(
"The area of the rectangle is {} square pixels.",
r... | {
self.width > other.width && self.height > other.height
} | identifier_body |
main.rs | #[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
fn | (&self, other: &Rectangle) -> bool {
self.width > other.width && self.height > other.height
}
}
fn main() {
let rect1 = Rectangle {
width: 30,
height: 50,
};
let rect2 = Rectangle {
width: 10,
height: 40,
};
let rect3 = Rectangle {
width: 60,
... | can_hold | identifier_name |
lib.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may... | //! ```
//! # use datafusion::prelude::*;
//! # use datafusion::error::Result;
//! # use arrow::record_batch::RecordBatch;
//!
//! # #[tokio::main]
//! # async fn main() -> Result<()> {
//! let mut ctx = ExecutionContext::new();
//!
//! ctx.register_csv("example", "tests/example.csv", CsvReadOptions::new())?;
//!
//! /... | //! and how to execute a query against a CSV using SQL:
//! | random_line_split |
media_queries.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/. */
//! Servo's media-query device and expression representation.
use app_units::Au;
use context::QuirksMode;
use css... | /// The kind of expression we're, just for unit testing.
///
/// Eventually this will become servo-only.
pub fn kind_for_testing(&self) -> &ExpressionKind {
&self.0
}
/// Parse a media expression of the form:
///
/// ```
/// (media-feature: media-value)
/// ```
///
... | random_line_split | |
media_queries.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/. */
//! Servo's media-query device and expression representation.
use app_units::Au;
use context::QuirksMode;
use css... | {
/// <http://dev.w3.org/csswg/mediaqueries-3/#width>
Width(Range<specified::Length>),
}
/// A single expression a per:
///
/// <http://dev.w3.org/csswg/mediaqueries-3/#media1>
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "servo", derive(MallocSizeOf))]
pub struct Expression(pub ExpressionKind);
i... | ExpressionKind | identifier_name |
test.rs | // Copyright 2013 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 ... |
/// Get a unique IPv6 localhost:port pair starting at 9600
pub fn next_test_ip6() -> SocketAddr {
SocketAddr { ip: Ipv6Addr(0, 0, 0, 0, 0, 0, 0, 1), port: next_test_port() }
}
/*
XXX: Welcome to MegaHack City.
The bots run multiple builds at the same time, and these builds
all want to use ports. This function f... | {
SocketAddr { ip: Ipv4Addr(127, 0, 0, 1), port: next_test_port() }
} | identifier_body |
test.rs | // Copyright 2013 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 ... | () -> SocketAddr {
SocketAddr { ip: Ipv6Addr(0, 0, 0, 0, 0, 0, 0, 1), port: next_test_port() }
}
/*
XXX: Welcome to MegaHack City.
The bots run multiple builds at the same time, and these builds
all want to use ports. This function figures out which workspace
it is running in and assigns a port range based on it.... | next_test_ip6 | identifier_name |
test.rs | // Copyright 2013 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 {
Path::new(format!("{}{}", r"\\.\pipe\", string))
}
}
/// Get a temporary path which could be the location of a unix socket
#[cfg(target_os = "ios")]
pub fn next_test_unix() -> Path {
Path::new(format!("/var/tmp/{}", next_test_unix_socket()))
}
/// Get a unique IPv4 localhost:port pair starting... | {
env::temp_dir().join(string)
} | conditional_block |
test.rs | // Copyright 2013 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 ... | if path_s.contains(dir) {
final_base = base;
break;
}
}
return final_base;
}
/// Raises the file descriptor limit when running tests if necessary
pub fn raise_fd_limit() {
unsafe { darwin_fd_limit::raise_fd_limit() }
}
/// darwin_fd_limit exists to work around an i... | random_line_split | |
deriving-span-Zero-tuple-struct.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {}
| main | identifier_name |
or_stack.rs | use l3::ast::*;
use std::ops::{Index, IndexMut};
use std::vec::Vec;
pub struct Frame {
pub global_index: usize,
pub e: usize,
pub cp: CodePtr,
pub b: usize,
pub bp: CodePtr,
pub tr: usize,
pub h: usize,
args: Vec<Addr>
}
impl Frame {
fn new(global_index: usize,
e: usize... | (&self, index: usize) -> &Self::Output {
self.args.index(index - 1)
}
}
impl IndexMut<usize> for Frame {
fn index_mut(&mut self, index: usize) -> &mut Self::Output {
self.args.index_mut(index - 1)
}
}
| index | identifier_name |
or_stack.rs | use l3::ast::*;
use std::ops::{Index, IndexMut};
use std::vec::Vec;
pub struct Frame {
pub global_index: usize,
pub e: usize,
pub cp: CodePtr,
pub b: usize,
pub bp: CodePtr,
pub tr: usize,
pub h: usize,
args: Vec<Addr>
}
impl Frame {
fn new(global_index: usize,
e: usize... | fn index_mut(&mut self, index: usize) -> &mut Self::Output {
self.0.index_mut(index)
}
}
impl Index<usize> for Frame {
type Output = Addr;
fn index(&self, index: usize) -> &Self::Output {
self.args.index(index - 1)
}
}
impl IndexMut<usize> for Frame {
fn index_mut(&mut self, i... | }
impl IndexMut<usize> for OrStack { | random_line_split |
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/. */
#![crate_name = "skia"]
#![crate_type = "rlib"]
#![feature(libc)]
extern crate libc;
| SkiaGrContextRef,
SkiaGrGLSharedSurfaceRef,
SkiaGrGLNativeContextRef,
SkiaSkNativeSharedGLContextCreate,
SkiaSkNativeSharedGLContextRetain,
SkiaSkNativeSharedGLContextRelease,
SkiaSkNativeSharedGLContextGetFBOID,
SkiaSkNativeSharedGLContextStealSurface,
SkiaSkNativeSharedGLContextGet... | pub use skia::{
SkiaSkNativeSharedGLContextRef, | random_line_split |
i2c.rs | // Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
use anyhow::Result;
use erased_serde::Serialize;
use std::any::Any;
use structopt::StructOpt;
use opentitanlib::app::command::CommandDispatch;
use opentitanlib::app::Tr... | {
#[structopt(flatten)]
params: I2cParams,
#[structopt(short, long, help = "7-bit address of I2C device (0..0x7F).")]
addr: u8,
#[structopt(subcommand)]
command: InternalI2cCommand,
}
impl CommandDispatch for I2cCommand {
fn run(
&self,
_context: &dyn Any,
transpo... | I2cCommand | identifier_name |
i2c.rs | // Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
use anyhow::Result;
use erased_serde::Serialize;
use std::any::Any;
use structopt::StructOpt;
use opentitanlib::app::command::CommandDispatch;
use opentitanlib::app::Tr... | transport: &TransportWrapper,
) -> Result<Option<Box<dyn Serialize>>> {
transport.capabilities()?.request(Capability::I2C).ok()?;
let context = context.downcast_ref::<I2cCommand>().unwrap();
let i2c_bus = context.params.create(transport)?;
i2c_bus.run_transaction(
... | context: &dyn Any, | random_line_split |
i2c.rs | // Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
use anyhow::Result;
use erased_serde::Serialize;
use std::any::Any;
use structopt::StructOpt;
use opentitanlib::app::command::CommandDispatch;
use opentitanlib::app::Tr... |
}
/// Write plain data bytes to a I2C device.
#[derive(Debug, StructOpt)]
pub struct I2cRawWrite {
#[structopt(short, long, help = "Hex data bytes to write.")]
hexdata: String,
}
impl CommandDispatch for I2cRawWrite {
fn run(
&self,
context: &dyn Any,
transport: &TransportWrapper,... | {
transport.capabilities()?.request(Capability::I2C).ok()?;
let context = context.downcast_ref::<I2cCommand>().unwrap();
let i2c_bus = context.params.create(transport)?;
let mut v = vec![0u8; self.length];
i2c_bus.run_transaction(context.addr, &mut [Transfer::Read(&mut v)])?;
... | identifier_body |
from_other_type_slice.rs | use malachite_base::named::Named;
use malachite_base::num::basic::unsigneds::PrimitiveUnsigned;
use malachite_base::num::conversion::traits::FromOtherTypeSlice;
use malachite_base_test_util::bench::bucketers::vec_len_bucketer;
use malachite_base_test_util::bench::{run_benchmark, BenchmarkType};
use malachite_base_test_... | <T: Display + FromOtherTypeSlice<U> + Named, U: PrimitiveUnsigned>(
gm: GenMode,
config: GenConfig,
limit: usize,
) {
for xs in unsigned_vec_gen::<U>().get(gm, &config).take(limit) {
println!(
"{}::from_other_type_slice({:?}) = {}",
T::NAME,
xs,
T:... | demo_from_other_type_slice | identifier_name |
from_other_type_slice.rs | use malachite_base::named::Named;
use malachite_base::num::basic::unsigneds::PrimitiveUnsigned;
use malachite_base::num::conversion::traits::FromOtherTypeSlice;
use malachite_base_test_util::bench::bucketers::vec_len_bucketer;
use malachite_base_test_util::bench::{run_benchmark, BenchmarkType};
use malachite_base_test_... | );
} | random_line_split | |
from_other_type_slice.rs | use malachite_base::named::Named;
use malachite_base::num::basic::unsigneds::PrimitiveUnsigned;
use malachite_base::num::conversion::traits::FromOtherTypeSlice;
use malachite_base_test_util::bench::bucketers::vec_len_bucketer;
use malachite_base_test_util::bench::{run_benchmark, BenchmarkType};
use malachite_base_test_... | {
run_benchmark(
&format!("{}.from_other_type_slice(&[{}])", T::NAME, U::NAME),
BenchmarkType::Single,
unsigned_vec_gen::<U>().get(gm, &config),
gm.name(),
limit,
file_name,
&vec_len_bucketer(),
&mut [("Malachite", &mut |xs| {
no_out!(T::fr... | identifier_body | |
fs.rs | /*
Rust - Std Misc Filesystem Operation
Licence : GNU GPL v3 or later
Author : Aurélien DESBRIÈRES
Mail : aurelien(at)hackers(dot)camp
Created on : June 2017
Write with Emacs-nox ───────────────┐
Rust ───────────────────────────────┘
*/
// fs.rs | use std::io::prelude::*;
use std::os::unix;
use std::path::Path;
// A simple implementation of `% cat path`
fn cat(path: &Path) -> io::Result<String> {
let mut f = try!(File::open(path));
let mut s = String::new();
match f.read_to_string(&mut s) {
Ok(_) => Ok(s),
Err(e) => Err(e),
}
}
... |
use std::fs;
use std::fs::{File, OpenOptions};
use std::io; | random_line_split |
fs.rs | /*
Rust - Std Misc Filesystem Operation
Licence : GNU GPL v3 or later
Author : Aurélien DESBRIÈRES
Mail : aurelien(at)hackers(dot)camp
Created on : June 2017
Write with Emacs-nox ───────────────┐
Rust ───────────────────────────────┘
*/
// fs.rs
use std::fs;
use std::fs::{File, OpenOptions};
use std::io... | atch fs::create_dir("a") {
Err(why) => println!("! {:?}", why.kind()),
Ok(_) => {},
}
println!("`echo hello > a/b.txt`");
// The previous match can be simplified using the `unwrap_or_else` method
echo("hello", &Path::new("a/b.txt")).unwrap_or_else(|why| {
println!("! {:?}", why.... | Err(e) => Err(e),
}
}
fn main() {
println!("`mkdir a`");
// Create a directory, returns `io::Result<()>`
m | identifier_body |
fs.rs | /*
Rust - Std Misc Filesystem Operation
Licence : GNU GPL v3 or later
Author : Aurélien DESBRIÈRES
Mail : aurelien(at)hackers(dot)camp
Created on : June 2017
Write with Emacs-nox ───────────────┐
Rust ───────────────────────────────┘
*/
// fs.rs
use std::fs;
use std::fs::{File, OpenOptions};
use std::io... | {
Ok(_) => Ok(()),
Err(e) => Err(e),
}
}
fn main() {
println!("`mkdir a`");
// Create a directory, returns `io::Result<()>`
match fs::create_dir("a") {
Err(why) => println!("! {:?}", why.kind()),
Ok(_) => {},
}
println!("`echo hello > a/b.txt`");
// The pre... | path) | identifier_name |
loops.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | <'this>(&'this mut self) -> NestedVisitorMap<'this, 'hir> {
NestedVisitorMap::OnlyBodies(&self.hir_map)
}
fn visit_item(&mut self, i: &'hir hir::Item) {
self.with_context(Normal, |v| intravisit::walk_item(v, i));
}
fn visit_impl_item(&mut self, i: &'hir hir::ImplItem) {
self.wi... | nested_visit_map | identifier_name |
loops.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | Normal | AnonConst => {
struct_span_err!(self.sess, span, E0268, "`{}` outside of loop", name)
.span_label(span, "cannot break outside of a loop")
.emit();
}
}
}
fn require_label_in_labeled_block(&mut self, span: Span, label: &Destin... | Closure => {
struct_span_err!(self.sess, span, E0267, "`{}` inside of a closure", name)
.span_label(span, "cannot break inside of a closure")
.emit();
} | random_line_split |
loops.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
impl<'a, 'hir> Visitor<'hir> for CheckLoopVisitor<'a, 'hir> {
fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'hir> {
NestedVisitorMap::OnlyBodies(&self.hir_map)
}
fn visit_item(&mut self, i: &'hir hir::Item) {
self.with_context(Normal, |v| intravisit::walk_item(v, ... | {
let krate = map.krate();
krate.visit_all_item_likes(&mut CheckLoopVisitor {
sess,
hir_map: map,
cx: Normal,
}.as_deep_visitor());
} | identifier_body |
lib.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.
*/
#![deny(warnings)]
use anyhow::{anyhow, Error, Result};
use cloned::cloned;
use context::CoreContext;
use derived_data_manager::Derivation... |
}
}
Ok(sources)
}
});
future::try_join_all(sources_futs)
.map_ok(|unodes| unodes.into_iter().flatten().collect())
.await
}
/// Given bonsai changeset find unodes for all renames that happened in this changesest.
///
/// Returns mapping from paths ... | {
for to_path in to_paths {
sources.push((
to_path.clone(),
UnodeRenameSource {
parent_index,
from_path: from_path.clone(),
... | conditional_block |
lib.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.
*/
#![deny(warnings)]
use anyhow::{anyhow, Error, Result};
use cloned::cloned;
use context::CoreContext;
use derived_data_manager::Derivation... | .collect::<HashMap<_, _>>()
})
.await
});
future::try_join_all(unodes)
.map_ok(|unodes| unodes.into_iter().flatten().collect())
.await
}
#[cfg(test)]
mod tests {
use anyhow::Result;
use blobrepo::BlobRepo;
use blobstore::Loadable;
use bor... | .filter_map(|(from_path, unode_id)| Some((paths.remove(&from_path)?, unode_id))) | random_line_split |
lib.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.
*/
#![deny(warnings)]
use anyhow::{anyhow, Error, Result};
use cloned::cloned;
use context::CoreContext;
use derived_data_manager::Derivation... | {
/// Index of the parent changeset in the list of parents in the bonsai
/// changeset.
pub parent_index: usize,
/// Path of the file in the parent changeset (i.e., the path it was
/// renamed from).
pub from_path: MPath,
/// Unode ID of the file in the parent changeset.
pub unode_id:... | UnodeRenameSource | identifier_name |
lib.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.
*/
#![deny(warnings)]
use anyhow::{anyhow, Error, Result};
use cloned::cloned;
use context::CoreContext;
use derived_data_manager::Derivation... | anyhow!(
"bonsai changeset {} contains invalid copy from parent: {}",
bonsai.get_changeset_id(),
csid
)
})?;
let mf_root = derivation_ctx
.derive_dependency::<RootUnodeManifestId>(ctx, csid... | {
// Collect together a map of (source_path -> [dest_paths]) for each parent
// changeset.
let mut references: HashMap<ChangesetId, HashMap<&MPath, Vec<&MPath>>> = HashMap::new();
for (to_path, file_change) in bonsai.file_changes() {
if let Some((from_path, csid)) = file_change.copy_from() {
... | identifier_body |
seventeen.rs | use std::string::ToString;
fn singler<'a>(digit: u32) -> &'a str {
match digit {
0 => "zero",
1 => "one",
2 => "two",
3 => "three",
4 => "four",
5 => "five",
6 => "six",
7 => "seven",
8 => "eight",
9 => "nine",
_ => "",
}
}
fn twentor<'a>(num: u32) -> &'a str {
matc... | }
fn thouse(num: u32) -> String {
match num {
0...99 => hunnert(num).to_string(),
100 => "one hundred".to_string(),
101...199 => format!("one hundred and {}", hunnert(num % 100)),
200 => "two hundred".to_string(),
201...299 => format!("two hundred and {}", hunnert(num % 100)),
... | 81...89 => format!("eighty-{}", singler(num % 80)),
90 => "ninety".to_string(),
91...99 => format!("ninety-{}", singler(num % 90)),
_ => "".to_string(),
} | random_line_split |
seventeen.rs | use std::string::ToString;
fn singler<'a>(digit: u32) -> &'a str {
match digit {
0 => "zero",
1 => "one",
2 => "two",
3 => "three",
4 => "four",
5 => "five",
6 => "six",
7 => "seven",
8 => "eight",
9 => "nine",
_ => "",
}
}
fn twentor<'a>(num: u32) -> &'a str |
fn hunnert<'a>(num: u32) -> String {
match num {
0...19 => twentor(num).to_string(),
20 => "twenty".to_string(),
21...29 => format!("twenty-{}", singler(num % 20)),
30 => "thirty".to_string(),
31...39 => format!("thirty-{}", singler(num % 30)),
40 => "forty".to_string(),
... | {
match num {
0...9 => singler(num),
10 => "ten",
11 => "eleven",
12 => "twelve",
13 => "thirteen",
14 => "fourteen",
15 => "fifteen",
16 => "sixteen",
17 => "seventeen",
18 => "eighteen",
19 => "nineteen",
_ => "",
}
} | identifier_body |
seventeen.rs | use std::string::ToString;
fn singler<'a>(digit: u32) -> &'a str {
match digit {
0 => "zero",
1 => "one",
2 => "two",
3 => "three",
4 => "four",
5 => "five",
6 => "six",
7 => "seven",
8 => "eight",
9 => "nine",
_ => "",
}
}
fn twentor<'a>(num: u32) -> &'a str {
matc... | (s: String) -> u32 {
s.chars().fold(0, |memo, ch| {
memo + match ch {
'a'...'z' => 1,
_ => 0,
}
})
}
pub fn run() {
let sum: u32 = (1..1001).map(|i| count(thouse(i))).sum();
println!("Sum of number words: {}", sum);
} | count | identifier_name |
build.rs | // Copyright 2016 Joe Wilm, The Alacritty Project Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required b... | use std::fs::File;
use std::path::Path;
fn main() {
let dest = env::var("OUT_DIR").unwrap();
let mut file = File::create(&Path::new(&dest).join("gl_bindings.rs")).unwrap();
Registry::new(Api::Gl, (4, 5), Profile::Core, Fallbacks::All, [
"GL_ARB_blend_func_extended"
])
.write_bin... | use std::env; | random_line_split |
build.rs | // Copyright 2016 Joe Wilm, The Alacritty Project Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required b... | {
let dest = env::var("OUT_DIR").unwrap();
let mut file = File::create(&Path::new(&dest).join("gl_bindings.rs")).unwrap();
Registry::new(Api::Gl, (4, 5), Profile::Core, Fallbacks::All, [
"GL_ARB_blend_func_extended"
])
.write_bindings(GlobalGenerator, &mut file)
.unwrap(... | identifier_body | |
build.rs | // Copyright 2016 Joe Wilm, The Alacritty Project Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required b... | () {
let dest = env::var("OUT_DIR").unwrap();
let mut file = File::create(&Path::new(&dest).join("gl_bindings.rs")).unwrap();
Registry::new(Api::Gl, (4, 5), Profile::Core, Fallbacks::All, [
"GL_ARB_blend_func_extended"
])
.write_bindings(GlobalGenerator, &mut file)
.unwrap... | main | identifier_name |
blob_storage.rs | use services::blob_storage::BlobStorageService;
use std::rc::Rc;
use errors::prelude::*;
pub enum BlobStorageCommand {
OpenReader(
String, // type
String, // config
Box<Fn(IndyResult<i32 /* handle */>) + Send>), | Box<Fn(IndyResult<i32 /* handle */>) + Send>),
}
pub struct BlobStorageCommandExecutor {
blob_storage_service: Rc<BlobStorageService>
}
impl BlobStorageCommandExecutor {
pub fn new(blob_storage_service: Rc<BlobStorageService>) -> BlobStorageCommandExecutor {
BlobStorageCommandExecutor {
... | OpenWriter(
String, // writer type
String, // writer config JSON | random_line_split |
blob_storage.rs | use services::blob_storage::BlobStorageService;
use std::rc::Rc;
use errors::prelude::*;
pub enum BlobStorageCommand {
OpenReader(
String, // type
String, // config
Box<Fn(IndyResult<i32 /* handle */>) + Send>),
OpenWriter(
String, // writer type
String, // writer confi... | (&self, command: BlobStorageCommand) {
match command {
BlobStorageCommand::OpenReader(type_, config, cb) => {
info!("OpenReader command received");
cb(self.open_reader(&type_, &config));
}
BlobStorageCommand::OpenWriter(writer_type, writer_conf... | execute | identifier_name |
blob_storage.rs | use services::blob_storage::BlobStorageService;
use std::rc::Rc;
use errors::prelude::*;
pub enum BlobStorageCommand {
OpenReader(
String, // type
String, // config
Box<Fn(IndyResult<i32 /* handle */>) + Send>),
OpenWriter(
String, // writer type
String, // writer confi... |
fn open_writer(&self, type_: &str, config: &str) -> IndyResult<i32> {
debug!("open_writer >>> type_: {:?}, config: {:?}", type_, config);
let res = self.blob_storage_service.open_writer(type_, config).map_err(IndyError::from);
debug!("open_writer << res: {:?}", res);
res
}
}... | {
debug!("open_reader >>> type_: {:?}, config: {:?}", type_, config);
let res = self.blob_storage_service.open_reader(type_, config).map_err(IndyError::from);
debug!("open_reader << res: {:?}", res);
res
} | identifier_body |
lib.rs | #![crate_type="dylib"]
#![feature(plugin_registrar)]
#![deny(warnings)]
#![allow(unstable)]
extern crate syntax;
extern crate sodiumoxide;
#[macro_use] extern crate rustc;
use std::borrow::ToOwned;
use std::io::File;
use syntax::ast;
use syntax::visit;
use syntax::attr::AttrMetaMethods;
use syntax::codemap::Span;
use... | (&self, cx: &Context, span: Span, id: ast::NodeId) {
if match self.authenticated_parent {
None => true,
Some(p) =>!child_of(cx, id, p),
} {
cx.span_lint(UNAUTHORIZED_UNSAFE, span, "unauthorized unsafe block");
}
}
// Check a function's #[launch_code] ... | authorize | identifier_name |
lib.rs | #![crate_type="dylib"]
#![feature(plugin_registrar)]
#![deny(warnings)]
#![allow(unstable)]
extern crate syntax;
extern crate sodiumoxide;
#[macro_use] extern crate rustc;
use std::borrow::ToOwned;
use std::io::File;
use syntax::ast;
use syntax::visit;
use syntax::attr::AttrMetaMethods;
use syntax::codemap::Span;
use... |
let launch_code = match launch_code {
Some(c) => c,
None => return,
};
// Authenticate the function arguments and body.
val.write(snip(cx, span).as_slice());
if val.verify(launch_code.1.as_slice(), &self.pubkey) {
self.authenticated_parent =... | }
} | random_line_split |
archive.rs | use rustc_data_structures::temp_dir::MaybeTempDir;
use rustc_session::cstore::DllImport;
use rustc_session::Session;
use rustc_span::symbol::Symbol;
use std::io;
use std::path::{Path, PathBuf}; | search_paths: &[PathBuf],
sess: &Session,
) -> PathBuf {
// On Windows, static libraries sometimes show up as libfoo.a and other
// times show up as foo.lib
let oslibname = if verbatim {
name.to_string()
} else {
format!("{}{}{}", sess.target.staticlib_prefix, name, sess.target.s... |
pub(super) fn find_library(
name: Symbol,
verbatim: bool, | random_line_split |
archive.rs | use rustc_data_structures::temp_dir::MaybeTempDir;
use rustc_session::cstore::DllImport;
use rustc_session::Session;
use rustc_span::symbol::Symbol;
use std::io;
use std::path::{Path, PathBuf};
pub(super) fn find_library(
name: Symbol,
verbatim: bool,
search_paths: &[PathBuf],
sess: &Session,
) -> Pat... | ;
let unixlibname = format!("lib{}.a", name);
for path in search_paths {
debug!("looking for {} inside {:?}", name, path);
let test = path.join(&oslibname);
if test.exists() {
return test;
}
if oslibname!= unixlibname {
let test = path.join(&unixl... | {
format!("{}{}{}", sess.target.staticlib_prefix, name, sess.target.staticlib_suffix)
} | conditional_block |
archive.rs | use rustc_data_structures::temp_dir::MaybeTempDir;
use rustc_session::cstore::DllImport;
use rustc_session::Session;
use rustc_span::symbol::Symbol;
use std::io;
use std::path::{Path, PathBuf};
pub(super) fn | (
name: Symbol,
verbatim: bool,
search_paths: &[PathBuf],
sess: &Session,
) -> PathBuf {
// On Windows, static libraries sometimes show up as libfoo.a and other
// times show up as foo.lib
let oslibname = if verbatim {
name.to_string()
} else {
format!("{}{}{}", sess.targ... | find_library | identifier_name |
archive.rs | use rustc_data_structures::temp_dir::MaybeTempDir;
use rustc_session::cstore::DllImport;
use rustc_session::Session;
use rustc_span::symbol::Symbol;
use std::io;
use std::path::{Path, PathBuf};
pub(super) fn find_library(
name: Symbol,
verbatim: bool,
search_paths: &[PathBuf],
sess: &Session,
) -> Pat... | }
}
}
sess.fatal(&format!(
"could not find native static library `{}`, \
perhaps an -L flag is missing?",
name
));
}
pub trait ArchiveBuilder<'a> {
fn new(sess: &'a Session, output: &Path, input: Option<&Path>) -> Self;
fn add_file(&mut... | {
// On Windows, static libraries sometimes show up as libfoo.a and other
// times show up as foo.lib
let oslibname = if verbatim {
name.to_string()
} else {
format!("{}{}{}", sess.target.staticlib_prefix, name, sess.target.staticlib_suffix)
};
let unixlibname = format!("lib{}.a"... | identifier_body |
lib.rs | use std::path::Path;
use std::sync::{Arc, Mutex};
use std::{fs::create_dir_all, path::PathBuf};
use anyhow::{bail, Result};
use crossbeam_channel::{unbounded, Sender};
use log::{error, warn};
use pueue_lib::network::certificate::create_certificates;
use pueue_lib::network::message::{Message, Shutdown};
use pueue_lib:... |
std::thread::spawn(move || {
task_handler.run();
});
accept_incoming(sender, state.clone()).await?;
Ok(())
}
/// Initialize all directories needed for normal operation.
fn init_directories(pueue_dir: &Path) {
// Pueue base path
if!pueue_dir.exists() {
if let Err(error) = cre... | {
setup_signal_panic_handling(&settings, &sender)?;
} | conditional_block |
lib.rs | use std::path::Path;
use std::sync::{Arc, Mutex};
use std::{fs::create_dir_all, path::PathBuf};
use anyhow::{bail, Result};
use crossbeam_channel::{unbounded, Sender};
use log::{error, warn};
use pueue_lib::network::certificate::create_certificates;
use pueue_lib::network::message::{Message, Shutdown};
use pueue_lib:... | }
std::thread::spawn(move || {
task_handler.run();
});
accept_incoming(sender, state.clone()).await?;
Ok(())
}
/// Initialize all directories needed for normal operation.
fn init_directories(pueue_dir: &Path) {
// Pueue base path
if!pueue_dir.exists() {
if let Err(error) ... | // Don't set ctrlc and panic handlers during testing.
// This is necessary for multithreaded integration testing, since multiple listener per process
// aren't prophibited. On top of this, ctrlc also somehow breaks test error output.
if !test {
setup_signal_panic_handling(&settings, &sender)?; | random_line_split |
lib.rs | use std::path::Path;
use std::sync::{Arc, Mutex};
use std::{fs::create_dir_all, path::PathBuf};
use anyhow::{bail, Result};
use crossbeam_channel::{unbounded, Sender};
use log::{error, warn};
use pueue_lib::network::certificate::create_certificates;
use pueue_lib::network::message::{Message, Shutdown};
use pueue_lib:... | (config_path: Option<PathBuf>, profile: Option<String>, test: bool) -> Result<()> {
// Try to read settings from the configuration file.
let (mut settings, config_found) = Settings::read(&config_path)?;
// We couldn't find a configuration file.
// This probably means that Pueue has been started for the... | run | identifier_name |
lib.rs | use std::path::Path;
use std::sync::{Arc, Mutex};
use std::{fs::create_dir_all, path::PathBuf};
use anyhow::{bail, Result};
use crossbeam_channel::{unbounded, Sender};
use log::{error, warn};
use pueue_lib::network::certificate::create_certificates;
use pueue_lib::network::message::{Message, Shutdown};
use pueue_lib:... | // Cleanup the pid file
if let Err(error) = pid::cleanup_pid_file(&settings_clone.shared.pueue_directory()) {
println!("Failed to cleanup pid after panic.");
println!("{error}");
}
// Remove the unix socket.
if let Err(error) = socket_cleanup(&settings_cl... | {
let sender_clone = sender.clone();
// This section handles Shutdown via SigTerm/SigInt process signals
// Notify the TaskHandler, so it can shutdown gracefully.
// The actual program exit will be done via the TaskHandler.
ctrlc::set_handler(move || {
// Notify the task handler
sen... | identifier_body |
locked_env_var.rs | //! Unit test helpers for dealing with environment variables.
//!
//! A lot of our functionality can change depending on how certain
//! environment variables are set. This complicates unit testing,
//! because Rust runs test cases in parallel on separate threads, but
//! environment variables are shared across threads... |
}
impl Drop for LockedEnvVar {
fn drop(&mut self) {
match self.original_value {
Some(ref val) => {
env::set_var(&*self.lock, val);
}
None => {
env::remove_var(&*self.lock);
}
}
}
}
/// Create a static thread-safe ... | { env::remove_var(&*self.lock); } | identifier_body |
locked_env_var.rs | //! Unit test helpers for dealing with environment variables.
//!
//! A lot of our functionality can change depending on how certain
//! environment variables are set. This complicates unit testing,
//! because Rust runs test cases in parallel on separate threads, but
//! environment variables are shared across threads... | assert_eq!(env::var("HAB_TESTING_LOCKED_ENV_VAR"),
Ok(String::from("foo")));
lock.set("bar");
assert_eq!(env::var("HAB_TESTING_LOCKED_ENV_VAR"),
Ok(String::from("bar")));
lock.set("foobar");
assert_eq!(env::var("HA... |
{
let lock = lock_var();
lock.set("foo"); | random_line_split |
locked_env_var.rs | //! Unit test helpers for dealing with environment variables.
//!
//! A lot of our functionality can change depending on how certain
//! environment variables are set. This complicates unit testing,
//! because Rust runs test cases in parallel on separate threads, but
//! environment variables are shared across threads... | <V>(&self, value: V)
where V: AsRef<OsStr>
{
env::set_var(&*self.lock, value.as_ref());
}
/// Unsets an environment variable.
pub fn unset(&self) { env::remove_var(&*self.lock); }
}
impl Drop for LockedEnvVar {
fn drop(&mut self) {
match self.original_value {
So... | set | identifier_name |
legendre.rs | //compute Jacobi symbol of a number
use super::Mod;
use std::collections::HashSet;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum Jacobi {
Value(i8), // -1, 0, 1
Frac{pos: bool, numer: u64, denom: u64},
}
impl Jacobi {
fn from_val(a: i8) -> Jacobi {
Jacobi::Value(a)
}
fn from_frac(s: ... | }
}
fn two_numer(&self) -> Option<Jacobi> {
// J((ab)/n) = J(a/n)*J(b/n)
// J(2/n) = { 1 iff n≡±1(mod 8), -1 iff n≡ٍ±3(mod 8) }
if let &Jacobi::Frac{pos: p, numer: n, denom: d} = self {
let z = n.trailing_zeros();
let n_ = n / 2u64.pow(z);
let ... | } else {
None | random_line_split |
legendre.rs | //compute Jacobi symbol of a number
use super::Mod;
use std::collections::HashSet;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum Jacobi {
Value(i8), // -1, 0, 1
Frac{pos: bool, numer: u64, denom: u64},
}
impl Jacobi {
fn from_val(a: i8) -> Jacobi {
Jacobi::Value(a)
}
fn | (s: bool, a: u64, b: u64) -> Jacobi {
Jacobi::Frac{pos: s, numer: a, denom: b}
}
fn print(&self) {
if let &Jacobi::Frac{pos: p, numer: n, denom: d} = self {
println!(" {} J( {} / {} )",
if p { '+' } else { '-' }, n, d);
} else if let &Jacobi::Value(v) = ... | from_frac | identifier_name |
legendre.rs | //compute Jacobi symbol of a number
use super::Mod;
use std::collections::HashSet;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum Jacobi {
Value(i8), // -1, 0, 1
Frac{pos: bool, numer: u64, denom: u64},
}
impl Jacobi {
fn from_val(a: i8) -> Jacobi {
Jacobi::Value(a)
}
fn from_frac(s: ... | None
}
}
}
| if n.modulo(4) == 3 && d.modulo(4) == 3 {
Some(Jacobi::from_frac(!p, d, n))
} else {
None
}
} else {
| conditional_block |
issue-13698.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 ... | // except according to those terms.
// aux-build:issue-13698.rs
// ignore-cross-compile
extern crate issue_13698;
pub struct Foo;
// @!has issue_13698/struct.Foo.html '//*[@id="method.foo"]' 'fn foo'
impl issue_13698::Foo for Foo {}
pub trait Bar {
#[doc(hidden)]
fn bar(&self) {}
}
// @!has issue_13698/str... | // option. This file may not be copied, modified, or distributed | random_line_split |
issue-13698.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 ... |
}
// @!has issue_13698/struct.Foo.html '//*[@id="method.foo"]' 'fn bar'
impl Bar for Foo {}
| {} | identifier_body |
issue-13698.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 ... | ;
// @!has issue_13698/struct.Foo.html '//*[@id="method.foo"]' 'fn foo'
impl issue_13698::Foo for Foo {}
pub trait Bar {
#[doc(hidden)]
fn bar(&self) {}
}
// @!has issue_13698/struct.Foo.html '//*[@id="method.foo"]' 'fn bar'
impl Bar for Foo {}
| Foo | identifier_name |
hoit.rs | pub extern fn run(instance: lv2::Lv2handle, n_samples: u32) {
unsafe{
let synth = instance as *mut Lv2SynthPlugin;
let uris = &mut (*synth).uris;
let seq = (*synth).in_port;
let output = (*synth).output;
// pointer to 1st event body
let mut ev: *const lv2::Lv2AtomEven... | (instance: lv2::Lv2handle, n_samples: u32) {
unsafe{
let synth = instance as *mut Synth;
// frameindex of eventstart. In jalv this is relative to currently processed buffer chunk of length n_samples
let istart = (*ev).time_in_frames as u32;
match lv2::lv2_mi... | run | identifier_name |
hoit.rs | pub extern fn run(instance: lv2::Lv2handle, n_samples: u32) {
unsafe{
let synth = instance as *mut Lv2SynthPlugin;
let uris = &mut (*synth).uris;
let seq = (*synth).in_port;
let output = (*synth).output;
// pointer to 1st event body
let mut ev: *const lv2::Lv2AtomEven... | // TODO don't set fs here
(*synth).OscBLIT.reset((*synth).fs);
(*synth).OscBLIT.set_f0fn(f0);
for i in istart-1..n_samples {
// let amp = (*synth).osc.get() as f32;
le... | {
unsafe{
let synth = instance as *mut Synth;
// frameindex of eventstart. In jalv this is relative to currently processed buffer chunk of length n_samples
let istart = (*ev).time_in_frames as u32;
match lv2::lv2_midi_message_type(msg) {
... | identifier_body |
hoit.rs | pub extern fn run(instance: lv2::Lv2handle, n_samples: u32) {
unsafe{
let synth = instance as *mut Lv2SynthPlugin;
let uris = &mut (*synth).uris;
let seq = (*synth).in_port;
let output = (*synth).output;
// pointer to 1st event body
let mut ev: *const lv2::Lv2AtomEven... | (*synth).osc.set_dphase(f0,(*synth).fs);
// TODO don't set fs here
(*synth).OscBLIT.reset((*synth).fs);
(*synth).OscBLIT.set_f0fn(f0);
for i in istart-1..n_samples {
// l... | (*synth).f0 = f0;
(*synth).currentmidivel = *msg.offset(2);
let coef = 1.0 as f32;
(*synth).osc.reset(); | random_line_split |
lib.rs | extern crate rusty_c_sys;
use rusty_c_sys as ffi;
trait Pika2 {
fn next_pika2(&mut self) -> i32;
}
impl Pika2 for i32 {
fn next_pika2(&mut self) -> i32 {
let raw = self as *mut i32;
unsafe {
ffi::next_pika2(raw)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
... | () {
let mut x = ffi::defend;
let p = x.next_pika2();
assert_eq!(x, ffi::attack);
assert_eq!(p, ffi::attack);
}
}
| from_defend | identifier_name |
lib.rs | extern crate rusty_c_sys;
use rusty_c_sys as ffi;
trait Pika2 {
fn next_pika2(&mut self) -> i32;
}
impl Pika2 for i32 {
fn next_pika2(&mut self) -> i32 {
let raw = self as *mut i32;
unsafe {
ffi::next_pika2(raw)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
... | let mut x = ffi::defend;
let p = x.next_pika2();
assert_eq!(x, ffi::attack);
assert_eq!(p, ffi::attack);
}
} | random_line_split | |
lib.rs | extern crate rusty_c_sys;
use rusty_c_sys as ffi;
trait Pika2 {
fn next_pika2(&mut self) -> i32;
}
impl Pika2 for i32 {
fn next_pika2(&mut self) -> i32 {
let raw = self as *mut i32;
unsafe {
ffi::next_pika2(raw)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
... |
#[test]
fn from_defend() {
let mut x = ffi::defend;
let p = x.next_pika2();
assert_eq!(x, ffi::attack);
assert_eq!(p, ffi::attack);
}
}
| {
let mut x = ffi::attack;
let p = x.next_pika2();
assert_eq!(x, ffi::defend);
assert_eq!(p, ffi::defend);
} | identifier_body |
wrapping_sub_mul.rs | use num::arithmetic::traits::{
WrappingMul, WrappingSub, WrappingSubAssign, WrappingSubMul, WrappingSubMulAssign,
};
fn | <T: WrappingMul<T, Output = T> + WrappingSub<T, Output = T>>(
x: T,
y: T,
z: T,
) -> T {
x.wrapping_sub(y.wrapping_mul(z))
}
fn wrapping_sub_mul_assign<T: WrappingMul<T, Output = T> + WrappingSubAssign<T>>(
x: &mut T,
y: T,
z: T,
) {
x.wrapping_sub_assign(y.wrapping_mul(z));
}
macro_ru... | wrapping_sub_mul | identifier_name |
wrapping_sub_mul.rs | use num::arithmetic::traits::{
WrappingMul, WrappingSub, WrappingSubAssign, WrappingSubMul, WrappingSubMulAssign,
};
| ) -> T {
x.wrapping_sub(y.wrapping_mul(z))
}
fn wrapping_sub_mul_assign<T: WrappingMul<T, Output = T> + WrappingSubAssign<T>>(
x: &mut T,
y: T,
z: T,
) {
x.wrapping_sub_assign(y.wrapping_mul(z));
}
macro_rules! impl_wrapping_sub_mul {
($t:ident) => {
impl WrappingSubMul<$t> for $t {
... | fn wrapping_sub_mul<T: WrappingMul<T, Output = T> + WrappingSub<T, Output = T>>(
x: T,
y: T,
z: T, | random_line_split |
wrapping_sub_mul.rs | use num::arithmetic::traits::{
WrappingMul, WrappingSub, WrappingSubAssign, WrappingSubMul, WrappingSubMulAssign,
};
fn wrapping_sub_mul<T: WrappingMul<T, Output = T> + WrappingSub<T, Output = T>>(
x: T,
y: T,
z: T,
) -> T |
fn wrapping_sub_mul_assign<T: WrappingMul<T, Output = T> + WrappingSubAssign<T>>(
x: &mut T,
y: T,
z: T,
) {
x.wrapping_sub_assign(y.wrapping_mul(z));
}
macro_rules! impl_wrapping_sub_mul {
($t:ident) => {
impl WrappingSubMul<$t> for $t {
type Output = $t;
/// Com... | {
x.wrapping_sub(y.wrapping_mul(z))
} | identifier_body |
task_basic_info.rs | // Copyright 2014 The Servo Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at ... | let mut resident_size: size_t = 0;
let rv = unsafe {
TaskBasicInfoResidentSize(&mut resident_size)
};
if rv == 0 { Some(resident_size as usize) } else { None }
}
extern {
fn TaskBasicInfoVirtualSize(virtual_size: *mut size_t) -> c_int;
fn TaskBasicInfoResidentSize(resident_size: *mut si... |
/// Obtains task_basic_info::resident_size.
pub fn resident_size() -> Option<usize> { | random_line_split |
task_basic_info.rs | // Copyright 2014 The Servo Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at ... |
extern {
fn TaskBasicInfoVirtualSize(virtual_size: *mut size_t) -> c_int;
fn TaskBasicInfoResidentSize(resident_size: *mut size_t) -> c_int;
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_stuff() {
// In theory these can fail to return a value, but in practice they
// do... | {
let mut resident_size: size_t = 0;
let rv = unsafe {
TaskBasicInfoResidentSize(&mut resident_size)
};
if rv == 0 { Some(resident_size as usize) } else { None }
} | identifier_body |
task_basic_info.rs | // Copyright 2014 The Servo Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at ... | else { None }
}
/// Obtains task_basic_info::resident_size.
pub fn resident_size() -> Option<usize> {
let mut resident_size: size_t = 0;
let rv = unsafe {
TaskBasicInfoResidentSize(&mut resident_size)
};
if rv == 0 { Some(resident_size as usize) } else { None }
}
extern {
fn TaskBasicInfo... | { Some(virtual_size as usize) } | conditional_block |
task_basic_info.rs | // Copyright 2014 The Servo Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at ... | () {
// In theory these can fail to return a value, but in practice they
// don't unless something really bizarre has happened with the OS. So
// assume they succeed. The returned values are non-deterministic, but
// check they're non-zero as a basic sanity test.
assert!(virtual_... | test_stuff | identifier_name |
inherited.rs | use super::callee::DeferredCallResolution;
use super::MaybeInProgressTables;
use rustc_hir as hir;
use rustc_hir::def_id::{DefIdMap, LocalDefId};
use rustc_hir::HirIdMap;
use rustc_infer::infer;
use rustc_infer::infer::{InferCtxt, InferOk, TyCtxtInferExt};
use rustc_middle::ty::fold::TypeFoldable;
use rustc_middle::ty... | RefCell<Vec<(Ty<'tcx>, Span, traits::ObligationCauseCode<'tcx>)>>,
// When we process a call like `c()` where `c` is a closure type,
// we may not have decided yet whether `c` is a `Fn`, `FnMut`, or
// `FnOnce` closure. In that case, we defer full resolution of the
// call until upvar inference... | // These obligations are added in a later stage of typeck.
pub(super) deferred_sized_obligations: | random_line_split |
inherited.rs | use super::callee::DeferredCallResolution;
use super::MaybeInProgressTables;
use rustc_hir as hir;
use rustc_hir::def_id::{DefIdMap, LocalDefId};
use rustc_hir::HirIdMap;
use rustc_infer::infer;
use rustc_infer::infer::{InferCtxt, InferOk, TyCtxtInferExt};
use rustc_middle::ty::fold::TypeFoldable;
use rustc_middle::ty... |
pub(super) fn register_predicates<I>(&self, obligations: I)
where
I: IntoIterator<Item = traits::PredicateObligation<'tcx>>,
{
for obligation in obligations {
self.register_predicate(obligation);
}
}
pub(super) fn register_infer_ok_obligations<T>(&self, infer_o... | {
debug!("register_predicate({:?})", obligation);
if obligation.has_escaping_bound_vars() {
span_bug!(obligation.cause.span, "escaping bound vars in predicate {:?}", obligation);
}
self.fulfillment_cx.borrow_mut().register_predicate_obligation(self, obligation);
} | identifier_body |
inherited.rs | use super::callee::DeferredCallResolution;
use super::MaybeInProgressTables;
use rustc_hir as hir;
use rustc_hir::def_id::{DefIdMap, LocalDefId};
use rustc_hir::HirIdMap;
use rustc_infer::infer;
use rustc_infer::infer::{InferCtxt, InferOk, TyCtxtInferExt};
use rustc_middle::ty::fold::TypeFoldable;
use rustc_middle::ty... | (&self) -> &Self::Target {
&self.infcx
}
}
/// Helper type of a temporary returned by `Inherited::build(...)`.
/// Necessary because we can't write the following bound:
/// `F: for<'b, 'tcx> where 'tcx FnOnce(Inherited<'b, 'tcx>)`.
pub struct InheritedBuilder<'tcx> {
infcx: infer::InferCtxtBuilder<'tcx... | deref | identifier_name |
inherited.rs | use super::callee::DeferredCallResolution;
use super::MaybeInProgressTables;
use rustc_hir as hir;
use rustc_hir::def_id::{DefIdMap, LocalDefId};
use rustc_hir::HirIdMap;
use rustc_infer::infer;
use rustc_infer::infer::{InferCtxt, InferOk, TyCtxtInferExt};
use rustc_middle::ty::fold::TypeFoldable;
use rustc_middle::ty... |
self.fulfillment_cx.borrow_mut().register_predicate_obligation(self, obligation);
}
pub(super) fn register_predicates<I>(&self, obligations: I)
where
I: IntoIterator<Item = traits::PredicateObligation<'tcx>>,
{
for obligation in obligations {
self.register_predicate... | {
span_bug!(obligation.cause.span, "escaping bound vars in predicate {:?}", obligation);
} | conditional_block |
global.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/. */
//! Abstractions for global scopes.
//!
//! This module contains smart pointers to global scopes, to simplify writ... | (&self) -> GlobalRoot {
match *self {
GlobalField::Window(ref window) => GlobalRoot::Window(window.root()),
GlobalField::Worker(ref worker) => GlobalRoot::Worker(worker.root()),
}
}
}
impl GlobalUnrooted {
/// Create a stack-bounded root for this reference.
pub fn ro... | root | identifier_name |
global.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/. */
//! Abstractions for global scopes.
//!
//! This module contains smart pointers to global scopes, to simplify writ... | match *self {
GlobalRef::Window(ref window) => window.new_script_pair(),
GlobalRef::Worker(ref worker) => worker.new_script_pair(),
}
}
/// Process a single event as if it were the next event in the task queue for
/// this global.
pub fn process_event(&self, msg:... | /// Create a new sender/receiver pair that can be used to implement an on-demand
/// event loop. Used for implementing web APIs that require blocking semantics
/// without resorting to nested event loops.
pub fn new_script_pair(&self) -> (Box<ScriptChan+Send>, Box<ScriptPort+Send>) { | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.