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 |
|---|---|---|---|---|
ac97_mixer.rs | // Copyright 2018 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use crate::pci::ac97_regs::*;
// AC97 Vendor ID
const AC97_VENDOR_ID1: u16 = 0x8086;
const AC97_VENDOR_ID2: u16 = 0x8086;
// Extented Audio ID
const A... | (&mut self, offset: u64, val: u16) {
match offset {
MIXER_RESET_00 => self.reset(),
MIXER_MASTER_VOL_MUTE_02 => self.set_master_reg(val),
MIXER_MIC_VOL_MUTE_0E => self.set_mic_volume(val),
MIXER_PCM_OUT_VOL_MUTE_18 => self.set_pcm_out_volume(val),
MIXE... | writew | identifier_name |
ac97_mixer.rs | // Copyright 2018 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use crate::pci::ac97_regs::*;
// AC97 Vendor ID
const AC97_VENDOR_ID1: u16 = 0x8086;
const AC97_VENDOR_ID2: u16 = 0x8086;
// Extented Audio ID
const A... |
// Sets the mic input mute, boost, and volume settings (0x0e).
fn set_mic_volume(&mut self, val: u16) {
self.mic_volume = (val & MIXER_VOL_MASK) as u8;
self.mic_muted = val & MUTE_REG_BIT!= 0;
self.mic_20db = val & MIXER_MIC_20DB!= 0;
}
// Returns the value read in the Mic vol... | {
let mut reg = u16::from(self.mic_volume);
if self.mic_muted {
reg |= MUTE_REG_BIT;
}
if self.mic_20db {
reg |= MIXER_MIC_20DB;
}
reg
} | identifier_body |
homebrew.rs | // Copyright 2015-2017 Intecture Developers.
//
// Licensed under the Mozilla Public License 2.0 <LICENSE or
// https://www.tldrlegal.com/l/mpl-2.0>. This file may not be copied,
// modified, or distributed except according to those terms.
use command::Child;
use error_chain::ChainedError;
use errors::*;
use futures::... | (&self, host: &Local, name: &str) -> Box<Future<Item = (), Error = Error>> {
self.inner.enable(host, name)
}
fn disable(&self, host: &Local, name: &str) -> Box<Future<Item = (), Error = Error>> {
self.inner.disable(host, name)
}
}
| enable | identifier_name |
homebrew.rs | // Copyright 2015-2017 Intecture Developers.
//
// Licensed under the Mozilla Public License 2.0 <LICENSE or
// https://www.tldrlegal.com/l/mpl-2.0>. This file may not be copied,
// modified, or distributed except according to those terms.
use command::Child;
use error_chain::ChainedError;
use errors::*;
use futures::... | let path = format!("/usr/local/opt/{}/homebrew.mxcl.{0}.plist", name);
self.inner.install_plist(path)
};
match result {
Ok(_) => self.inner.action(host, name, action),
Err(e) => future::err(format!("{}", e.display_chain()).into())
}
}
fn ... | let result = if action == "stop" {
self.inner.uninstall_plist(name)
} else { | random_line_split |
homebrew.rs | // Copyright 2015-2017 Intecture Developers.
//
// Licensed under the Mozilla Public License 2.0 <LICENSE or
// https://www.tldrlegal.com/l/mpl-2.0>. This file may not be copied,
// modified, or distributed except according to those terms.
use command::Child;
use error_chain::ChainedError;
use errors::*;
use futures::... |
fn enable(&self, host: &Local, name: &str) -> Box<Future<Item = (), Error = Error>> {
self.inner.enable(host, name)
}
fn disable(&self, host: &Local, name: &str) -> Box<Future<Item = (), Error = Error>> {
self.inner.disable(host, name)
}
}
| {
self.inner.enabled(host, name)
} | identifier_body |
command.rs | // Copyright 2015 The Gfx-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 ag... | (&mut self, start: c::VertexCount,
count: c::VertexCount, instances: draw::InstanceOption) {
self.buf.push(Command::Draw(self.cache.primitive, start, count, instances));
}
fn call_draw_indexed(&mut self, start: c::VertexCount,
count: c::VertexCount, base: c::Ve... | call_draw | identifier_name |
command.rs | // Copyright 2015 The Gfx-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 ag... | fn set_ref_values(&mut self, rv: s::RefValues) {
self.buf.push(Command::SetStencilState(self.cache.stencil, rv.stencil, self.cache.cull_face));
self.buf.push(Command::SetBlendColor(rv.blend));
}
fn update_buffer(&mut self, buf: Buffer, data: &[u8], offset_bytes: usize) {
let ptr = s... | if self.cache.scissor {Some(rect)} else {None}
));
}
| random_line_split |
command.rs | // Copyright 2015 The Gfx-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 ag... | else {None}
));
}
fn set_ref_values(&mut self, rv: s::RefValues) {
self.buf.push(Command::SetStencilState(self.cache.stencil, rv.stencil, self.cache.cull_face));
self.buf.push(Command::SetBlendColor(rv.blend));
}
fn update_buffer(&mut self, buf: Buffer, data: &[u8], offset_byt... | {Some(rect)} | conditional_block |
command.rs | // Copyright 2015 The Gfx-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 ag... |
pub type Access = gl::types::GLenum;
#[derive(Clone, Copy, Debug)]
pub struct RawOffset(pub *const gl::types::GLvoid);
unsafe impl Send for RawOffset {}
/// The place of some data in the data buffer.
#[derive(Clone, Copy, PartialEq, Debug)]
pub struct DataPointer {
offset: u32,
size: u32,
}
pub struct Data... | {
use gfx_core::Primitive::*;
match primitive {
PointList => gl::POINTS,
LineList => gl::LINES,
LineStrip => gl::LINE_STRIP,
TriangleList => gl::TRIANGLES,
TriangleStrip => gl::TRIANGLE_STRIP,
//TriangleFan => gl::TRIANGLE_FAN,
}
} | identifier_body |
alignment-gep-tup-like-2.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 ... | (&self) -> (A, B) {
(self.a.clone(), self.b.clone())
}
}
fn f<A:Send + Clone +'static,
B:Send + Clone +'static>(
a: A,
b: B)
-> @Invokable<A,B> {
@Invoker {
a: a,
b: b,
} as @Invokable<A,B>
}
pub fn main() {
let x = 22_u8;
let y = 44_u64;
let z = f(~... | f | identifier_name |
alignment-gep-tup-like-2.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 ... | -> @Invokable<A,B> {
@Invoker {
a: a,
b: b,
} as @Invokable<A,B>
}
pub fn main() {
let x = 22_u8;
let y = 44_u64;
let z = f(~x, y);
make_cycle(z);
let (a, b) = z.f();
info!("a={} b={}", *a as uint, b as uint);
assert_eq!(*a, x);
assert_eq!(b, y);
} | B:Send + Clone + 'static>(
a: A,
b: B) | random_line_split |
hmacsha256.rs | //! `HMAC-SHA-256` `HMAC-SHA-256` is conjectured to meet the standard notion of
//! unforgeability.
use ffi::{crypto_auth_hmacsha256,
crypto_auth_hmacsha256_verify,
crypto_auth_hmacsha256_KEYBYTES,
crypto_auth_hmacsha256_BYTES
};
use crypto::verify::verify_32;
auth_module!(crypto_auth_hma... |
}
| {
// corresponding to tests/auth2.c from NaCl
let key = Key([0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08
,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f,0x10
,0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18
,0x19,0x1a,0x1b,0x1c,0x1d,0x1e,0x1f,0x20]);
let... | identifier_body |
hmacsha256.rs | //! `HMAC-SHA-256` `HMAC-SHA-256` is conjectured to meet the standard notion of
//! unforgeability.
use ffi::{crypto_auth_hmacsha256,
crypto_auth_hmacsha256_verify,
crypto_auth_hmacsha256_KEYBYTES,
crypto_auth_hmacsha256_BYTES
};
use crypto::verify::verify_32;
auth_module!(crypto_auth_hma... | () {
// corresponding to tests/auth2.c from NaCl
let key = Key([0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08
,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f,0x10
,0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18
,0x19,0x1a,0x1b,0x1c,0x1d,0x1e,0x1f,0x20]);
let... | test_vector_1 | identifier_name |
hmacsha256.rs | //! `HMAC-SHA-256` `HMAC-SHA-256` is conjectured to meet the standard notion of
//! unforgeability.
use ffi::{crypto_auth_hmacsha256,
crypto_auth_hmacsha256_verify,
crypto_auth_hmacsha256_KEYBYTES,
crypto_auth_hmacsha256_BYTES
};
use crypto::verify::verify_32;
auth_module!(crypto_auth_hma... | ,0x7b,0xb1,0x56,0xd3,0xd7,0xb3,0x0d,0x3f]);
let a = authenticate(&c, &key);
assert!(a == a_expected);
}
} | ,0x11,0x5b,0x13,0x46,0x90,0x3d,0x2e,0xf4
,0x2f,0xce,0xd4,0x6f,0x08,0x46,0xe7,0x25 | random_line_split |
lines.rs | use super::{HorizontalAlign, SectionGlyph, SectionText, VerticalAlign};
use crate::{linebreak::LineBreaker, words::*};
use ab_glyph::*;
use std::iter::{FusedIterator, Iterator, Peekable};
/// A line of `Word`s limited to a max width bound.
#[derive(Default)]
pub(crate) struct | {
pub glyphs: Vec<SectionGlyph>,
pub max_v_metrics: VMetrics,
pub rightmost: f32,
}
impl Line {
#[inline]
pub(crate) fn line_height(&self) -> f32 {
self.max_v_metrics.ascent - self.max_v_metrics.descent + self.max_v_metrics.line_gap
}
/// Returns line glyphs positioned on the scre... | Line | identifier_name |
lines.rs | use super::{HorizontalAlign, SectionGlyph, SectionText, VerticalAlign};
use crate::{linebreak::LineBreaker, words::*};
use ab_glyph::*;
use std::iter::{FusedIterator, Iterator, Peekable};
/// A line of `Word`s limited to a max width bound.
#[derive(Default)]
pub(crate) struct Line {
pub glyphs: Vec<SectionGlyph>,
... | /// `Line` iterator.
///
/// Will iterator through `Word` until the next word would break the `width_bound`.
///
/// Note: Will always have at least one word, if possible, even if the word itself
/// breaks the `width_bound`.
pub(crate) struct Lines<'a, 'b, L, F, S>
where
L: LineBreaker,
F: Font,
S: Iterato... | }
| random_line_split |
lines.rs | use super::{HorizontalAlign, SectionGlyph, SectionText, VerticalAlign};
use crate::{linebreak::LineBreaker, words::*};
use ab_glyph::*;
use std::iter::{FusedIterator, Iterator, Peekable};
/// A line of `Word`s limited to a max width bound.
#[derive(Default)]
pub(crate) struct Line {
pub glyphs: Vec<SectionGlyph>,
... | line.rightmost = word_right;
if (line.glyphs.is_empty() ||!word.glyphs.is_empty())
&& word.max_v_metrics.height() > line.max_v_metrics.height()
{
let diff_y = word.max_v_metrics.ascent - caret.y;
caret.y += diff_y;
// ... | {
let mut caret = point(0.0, 0.0);
let mut line = Line::default();
let mut progressed = false;
while let Some(word) = self.words.peek() {
let word_right = caret.x + word.layout_width_no_trail;
// Reduce float errors by using relative "<= width bound" check
... | identifier_body |
interfaces.rs | // Copyright 2020 Google LLC
//
// Use of this source code is governed by an MIT-style license that can be found
// in the LICENSE file or at https://opensource.org/licenses/MIT.
//! A handler and associated types for the interfaces action.
//!
//! The interfaces action lists all network interfaces available on the cl... | fn ip_to_proto(ip_network: IpNetwork) -> NetworkAddress {
use rrg_proto::network_address::Family;
use std::net::IpAddr::{V4, V6};
match ip_network.ip() {
V4(ipv4) => NetworkAddress {
address_type: Some(Family::Inet.into()),
packed_bytes: Some(ipv4.octets().to_vec()),
... | /// corresponding to an IP address.
///
/// [ip_network]: ../../../ipnetwork/enum.IpNetwork.html | random_line_split |
interfaces.rs | // Copyright 2020 Google LLC
//
// Use of this source code is governed by an MIT-style license that can be found
// in the LICENSE file or at https://opensource.org/licenses/MIT.
//! A handler and associated types for the interfaces action.
//!
//! The interfaces action lists all network interfaces available on the cl... | (ips: Vec<IpNetwork>) -> Vec<NetworkAddress> {
ips.into_iter().map(ip_to_proto).collect()
}
impl super::Response for Response {
const RDF_NAME: Option<&'static str> = Some("Interface");
type Proto = Interface;
fn into_proto(self) -> Interface {
let mac = match self.interface.mac {
... | ips_to_protos | identifier_name |
interfaces.rs | // Copyright 2020 Google LLC
//
// Use of this source code is governed by an MIT-style license that can be found
// in the LICENSE file or at https://opensource.org/licenses/MIT.
//! A handler and associated types for the interfaces action.
//!
//! The interfaces action lists all network interfaces available on the cl... |
impl super::Response for Response {
const RDF_NAME: Option<&'static str> = Some("Interface");
type Proto = Interface;
fn into_proto(self) -> Interface {
let mac = match self.interface.mac {
Some(mac) => Some(mac_to_vec(mac)),
None => {
error!(
... | {
ips.into_iter().map(ip_to_proto).collect()
} | identifier_body |
htmlpreelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLPreElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLPreElem... |
}
impl HTMLPreElement {
fn new_inherited(localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> HTMLPreElement {
HTMLPreElement {
htmlelement:
HTMLElement::new_inherited(HTMLElementTypeId::HTMLPreElement, localName, pr... | {
*self.type_id() ==
EventTargetTypeId::Node(
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLPreElement)))
} | identifier_body |
htmlpreelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
| use dom::bindings::codegen::Bindings::HTMLPreElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLPreElementDerived;
use dom::bindings::js::Root;
use dom::document::Document;
use dom::eventtarget::{EventTarget, EventTargetTypeId};
use dom::element::ElementTypeId;
use dom::htmlelement::{HTMLElement, HTMLElement... | random_line_split | |
htmlpreelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLPreElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLPreElem... | (localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLPreElement> {
let element = HTMLPreElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLPreElementBinding::Wrap)
}
}
| new | identifier_name |
close.rs | use futures_core::future::Future;
use futures_core::task::{Context, Poll};
use futures_io::AsyncWrite;
use std::io;
use std::pin::Pin;
/// Future for the [`close`](super::AsyncWriteExt::close) method.
#[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct Close<'a, W:?Sized> {
... |
}
impl<W: AsyncWrite +?Sized + Unpin> Future for Close<'_, W> {
type Output = io::Result<()>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
Pin::new(&mut *self.writer).poll_close(cx)
}
}
| {
Close { writer }
} | identifier_body |
close.rs | use futures_core::future::Future;
use futures_core::task::{Context, Poll};
use futures_io::AsyncWrite;
use std::io;
use std::pin::Pin;
/// Future for the [`close`](super::AsyncWriteExt::close) method.
#[derive(Debug)] | #[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct Close<'a, W:?Sized> {
writer: &'a mut W,
}
impl<W:?Sized + Unpin> Unpin for Close<'_, W> {}
impl<'a, W: AsyncWrite +?Sized + Unpin> Close<'a, W> {
pub(super) fn new(writer: &'a mut W) -> Self {
Close { writer }
}
}
imp... | random_line_split | |
close.rs | use futures_core::future::Future;
use futures_core::task::{Context, Poll};
use futures_io::AsyncWrite;
use std::io;
use std::pin::Pin;
/// Future for the [`close`](super::AsyncWriteExt::close) method.
#[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct | <'a, W:?Sized> {
writer: &'a mut W,
}
impl<W:?Sized + Unpin> Unpin for Close<'_, W> {}
impl<'a, W: AsyncWrite +?Sized + Unpin> Close<'a, W> {
pub(super) fn new(writer: &'a mut W) -> Self {
Close { writer }
}
}
impl<W: AsyncWrite +?Sized + Unpin> Future for Close<'_, W> {
type Output = io::Res... | Close | identifier_name |
mod.rs | extern crate android_glue;
use libc;
use std::ffi::{CString};
use std::sync::mpsc::{Receiver, channel};
use {CreationError, Event, MouseCursor};
use CreationError::OsError;
use events::ElementState::{Pressed, Released};
use events::Event::{MouseInput, MouseMoved};
use events::MouseButton;
use std::collections::VecDeq... |
(major, minor)
};
android_glue::write_log("eglInitialize succeeded");
let use_gles2 = match builder.gl_version {
GlRequest::Specific(Api::OpenGlEs, (2, _)) => true,
GlRequest::Specific(Api::OpenGlEs, _) => false,
GlRequest::Specific(_, _) => pa... | {
return Err(OsError(format!("eglInitialize failed")))
} | conditional_block |
mod.rs | extern crate android_glue;
use libc;
use std::ffi::{CString};
use std::sync::mpsc::{Receiver, channel};
use {CreationError, Event, MouseCursor};
use CreationError::OsError;
use events::ElementState::{Pressed, Released};
use events::Event::{MouseInput, MouseMoved};
use events::MouseButton;
use std::collections::VecDeq... |
}
#[cfg(feature = "headless")]
pub struct HeadlessContext(i32);
#[cfg(feature = "headless")]
impl HeadlessContext {
/// See the docs in the crate root file.
pub fn new(_builder: BuilderAttribs) -> Result<HeadlessContext, CreationError> {
unimplemented!()
}
/// See the docs in the crate root ... | {
unimplemented!()
} | identifier_body |
mod.rs | extern crate android_glue;
use libc;
use std::ffi::{CString};
use std::sync::mpsc::{Receiver, channel};
use {CreationError, Event, MouseCursor};
use CreationError::OsError;
use events::ElementState::{Pressed, Released};
use events::Event::{MouseInput, MouseMoved};
use events::MouseButton;
use std::collections::VecDeq... | <'a> {
window: &'a Window,
}
impl<'a> Iterator for PollEventsIterator<'a> {
type Item = Event;
fn next(&mut self) -> Option<Event> {
match self.window.event_rx.try_recv() {
Ok(event) => {
match event {
android_glue::Event::EventDown => Some(MouseInpu... | PollEventsIterator | identifier_name |
mod.rs | extern crate android_glue;
use libc;
use std::ffi::{CString};
use std::sync::mpsc::{Receiver, channel};
use {CreationError, Event, MouseCursor};
use CreationError::OsError;
use events::ElementState::{Pressed, Released};
use events::Event::{MouseInput, MouseMoved};
use events::MouseButton;
use std::collections::VecDeq... | #[cfg(feature = "window")]
#[derive(Clone)]
pub struct WindowProxy;
impl WindowProxy {
pub fn wakeup_event_loop(&self) {
unimplemented!()
}
}
#[unsafe_destructor]
impl Drop for Window {
fn drop(&mut self) {
use std::ptr;
unsafe {
// we don't call MakeCurrent(0, 0) beca... | random_line_split | |
wc.rs | /**
* wc (word count) implementation in Rust
*
* The purpose is to learn Rust a bit
*
* author: michal.vyskocil@gmail.com
*
* TODO:
* * word splitting is done on space only, where manual page claims whitespace
* * it is twelve times slower than GNU wc, needs profiling!
*/
use std::io::{BufferedReader,... |
else {
assert_eq!(is_pwr_ten(i), false);
}
}
}
fn wc<'r, T: Buffer>(lines : &'r mut Lines<'r, T>) -> Result<WordCount, IoError> {
let mut ret : WordCount = WordCount { lines: 0u, words: 0u, chars: 0u, bytes: 0u };
for res in lines {
let line = try!(res);
let sl... | {
assert_eq!(is_pwr_ten(i), true);
} | conditional_block |
wc.rs | /**
* wc (word count) implementation in Rust
*
* The purpose is to learn Rust a bit
*
* author: michal.vyskocil@gmail.com
*
* TODO:
* * word splitting is done on space only, where manual page claims whitespace
* * it is twelve times slower than GNU wc, needs profiling!
*/
use std::io::{BufferedReader,... | <'r, T: Buffer>(lines : &'r mut Lines<'r, T>) -> Result<WordCount, IoError> {
let mut ret : WordCount = WordCount { lines: 0u, words: 0u, chars: 0u, bytes: 0u };
for res in lines {
let line = try!(res);
let slice: &str = line.as_slice();
ret.lines += 1;
ret.words += slice.split... | wc | identifier_name |
wc.rs | /**
* wc (word count) implementation in Rust
*
* The purpose is to learn Rust a bit
*
* author: michal.vyskocil@gmail.com
*
* TODO:
* * word splitting is done on space only, where manual page claims whitespace
* * it is twelve times slower than GNU wc, needs profiling!
*/
use std::io::{BufferedReader,... |
while idx < args.len() {
match args[idx].as_slice() {
"--lines" => cfg.line_count = true,
"-l" => cfg.line_count = true,
"--bytes" => cfg.byte_count = true,
"-c" => cfg.byte_count = true,
"--chars" => cfg.char_count = true,
"... | fn parse_args(args: Vec<String>) -> (Cfg, Vec<String>) {
let mut cfg = Cfg{byte_count: false, char_count: false, line_count: false, word_count: false};
let mut idx = 1u;
let mut paths = Vec::new(); | random_line_split |
wc.rs | /**
* wc (word count) implementation in Rust
*
* The purpose is to learn Rust a bit
*
* author: michal.vyskocil@gmail.com
*
* TODO:
* * word splitting is done on space only, where manual page claims whitespace
* * it is twelve times slower than GNU wc, needs profiling!
*/
use std::io::{BufferedReader,... |
if!cfg.byte_count && (!cfg.char_count &&! cfg.line_count &&!cfg.word_count) {
cfg.char_count = true;
cfg.line_count = true;
cfg.word_count = true;
}
(cfg, paths)
}
fn spaces(n: uint) -> String {
let mut ret = String::with_capacity(n);
for _ in range(0, n) {
ret.pu... | {
let mut cfg = Cfg{byte_count: false, char_count: false, line_count: false, word_count: false};
let mut idx = 1u;
let mut paths = Vec::new();
while idx < args.len() {
match args[idx].as_slice() {
"--lines" => cfg.line_count = true,
"-l" => cfg.line_count = tru... | identifier_body |
net.rs | use color::Colorf32;
use fastup::{self, Node, parse_for_first_node, parse_color};
use stats_once::{NET_DOWNLOAD_SPEED, NET_UPLOAD_SPEED};
use super::error_node;
use std::mem::swap;
#[derive(Debug, Copy, Clone, Default)]
pub struct Widget;
impl super::Widget for Widget {
fn expand(&self, args: Vec<String>) -> Node... | fn net_node(
cold: Colorf32,
hot: Colorf32,
lo_speed_down: u64,
hi_speed_down: u64,
lo_speed_up: u64,
hi_speed_up: u64,
speed_down: u64,
speed_up: u64,
) -> Node
{
const BG_LIGHTNESS: f32 = 0.15;
const FG_LIGHTNESS: f32 = 0.4;
const IDLE_LIGHTNESS: f32 = 0.2;
const FAST_L... | }
| random_line_split |
net.rs | use color::Colorf32;
use fastup::{self, Node, parse_for_first_node, parse_color};
use stats_once::{NET_DOWNLOAD_SPEED, NET_UPLOAD_SPEED};
use super::error_node;
use std::mem::swap;
#[derive(Debug, Copy, Clone, Default)]
pub struct Widget;
impl super::Widget for Widget {
fn expand(&self, args: Vec<String>) -> Node... | : (f32, f32)) -> f32 {
let (a, b) = range;
(x - a) / (b - a)
}
fn nan_to_zero(x: f32) -> f32 {
if x.is_nan() { 0.0 } else { x }
}
| range | identifier_name |
net.rs | use color::Colorf32;
use fastup::{self, Node, parse_for_first_node, parse_color};
use stats_once::{NET_DOWNLOAD_SPEED, NET_UPLOAD_SPEED};
use super::error_node;
use std::mem::swap;
#[derive(Debug, Copy, Clone, Default)]
pub struct Widget;
impl super::Widget for Widget {
fn expand(&self, args: Vec<String>) -> Node... | return (size, unit);
}
}
(size, 'G')
}
fn unmix(x: f32, range: (f32, f32)) -> f32 {
let (a, b) = range;
(x - a) / (b - a)
}
fn nan_to_zero(x: f32) -> f32 {
if x.is_nan() { 0.0 } else { x }
}
| size /= 1024.0;
} else {
| conditional_block |
process.rs | // @lecorref - github.com/lecorref, @geam - github.com/geam,
// @adjivas - github.com/adjivas. See the LICENSE
// file at the top-level directory of this distribution and at
// https://github.com/adjivas/krpsim
//
// This file may not be copied, modified, or distributed
// except according to those terms.
extern crate... | Inventory::new(
vec!(
Ressource::new("silver-rupee".to_string(), 200),
) // need
),
Inventory::new(
vec!(
Ressource::new("heart".to_string(), 10),
) // result
),
)
),
"knight:(silver-rupee:200):(heart:10):10"
... | format!("{}",
Process::from_integer(
"knight".to_string(), // name
10, // cycle | random_line_split |
process.rs | // @lecorref - github.com/lecorref, @geam - github.com/geam,
// @adjivas - github.com/adjivas. See the LICENSE
// file at the top-level directory of this distribution and at
// https://github.com/adjivas/krpsim
//
// This file may not be copied, modified, or distributed
// except according to those terms.
extern crate... | () {
assert_eq!(
format!("{}",
Process::from_integer(
"knight".to_string(), // name
10, // cycle
Inventory::new(
vec!(
Ressource::new("silver-rupee".to_string(), 200),
) // need
),
Inventory::new(
vec!(
Ressource::... | test_process_constructor_new | identifier_name |
process.rs | // @lecorref - github.com/lecorref, @geam - github.com/geam,
// @adjivas - github.com/adjivas. See the LICENSE
// file at the top-level directory of this distribution and at
// https://github.com/adjivas/krpsim
//
// This file may not be copied, modified, or distributed
// except according to those terms.
extern crate... | }
| {
assert_eq!(
format!("{}",
Process::from_integer(
"knight".to_string(), // name
10, // cycle
Inventory::new(
vec!(
Ressource::new("silver-rupee".to_string(), 200),
) // need
),
Inventory::new(
vec!(
Ressource::new... | identifier_body |
resource-in-struct.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 ... | (&mut self) {
self.i.set(false);
}
}
fn close_res(i: closable) -> close_res {
close_res {
i: i
}
}
enum option<T> { none, some(T), }
fn sink(_res: option<close_res>) { }
pub fn main() {
let c = box(GC) Cell::new(true);
sink(none);
sink(some(close_res(c)));
assert!(!c.get(... | drop | identifier_name |
resource-in-struct.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 ... |
// Ensures that class dtors run if the object is inside an enum
// variant
use std::cell::Cell;
use std::gc::{Gc, GC};
type closable = Gc<Cell<bool>>;
struct close_res {
i: closable,
}
#[unsafe_destructor]
impl Drop for close_res {
fn drop(&mut self) {
self.i.set(false);
}
}
fn close_res(i: clo... | // except according to those terms.
#![feature(managed_boxes, unsafe_destructor)] | random_line_split |
resource-in-struct.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 ... |
enum option<T> { none, some(T), }
fn sink(_res: option<close_res>) { }
pub fn main() {
let c = box(GC) Cell::new(true);
sink(none);
sink(some(close_res(c)));
assert!(!c.get());
}
| {
close_res {
i: i
}
} | identifier_body |
font.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use color::Color;
use font_context::FontContext;
use geometry::Au;
use platform::font_context::FontContextHandle;
... | (&self) -> ~str {
unsafe {
let reversed = str::raw::from_buf_len(cast::transmute(self), 4);
return str::from_chars([reversed.char_at(3),
reversed.char_at(2),
reversed.char_at(1),
r... | tag_to_str | identifier_name |
font.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use color::Color;
use font_context::FontContext;
use geometry::Au;
use platform::font_context::FontContextHandle;
... |
// The ordering of font instances is mainly decided by the CSS
// 'font-family' property. The last font is a system fallback font.
pub struct FontGroup {
families: @str,
// style of the first western font in group, which is
// used for purposes of calculating text run metrics.
style: UsedFontStyle,
... | random_line_split | |
font.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use color::Color;
use font_context::FontContext;
use geometry::Au;
use platform::font_context::FontContextHandle;
... |
#[cfg(target_os="linux")]
priv fn create_azure_font(&self) -> ScaledFont {
let freetype_font = self.handle.face;
let size = self.style.pt_size as AzFloat;
ScaledFont::new(self.backend, freetype_font, size)
}
}
pub impl Font {
fn draw_text_into_context(&mut self,
... | {
let cg_font = self.handle.get_CGFont();
let size = self.style.pt_size as AzFloat;
ScaledFont::new(self.backend, &cg_font, size)
} | identifier_body |
init.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::RegisterBindings;
use crate::dom::bindings::proxyhandler;
use crate::script_ru... | () {}
#[allow(unsafe_code)]
pub fn init() -> JSEngineSetup {
unsafe {
proxyhandler::init();
// Create the global vtables used by the (generated) DOM
// bindings to implement JS proxies.
RegisterBindings::RegisterProxyHandlers();
}
perform_platform_specific_initialization()... | perform_platform_specific_initialization | identifier_name |
init.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::RegisterBindings;
use crate::dom::bindings::proxyhandler;
use crate::script_ru... | },
};
match libc::setrlimit(libc::RLIMIT_NOFILE, &rlim) {
0 => (),
_ => warn!("Failed to set file count limit"),
};
},
_ => warn!("Failed to get file count limit"),
};
}
}
#[c... | random_line_split | |
init.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::RegisterBindings;
use crate::dom::bindings::proxyhandler;
use crate::script_ru... |
#[allow(unsafe_code)]
pub fn init() -> JSEngineSetup {
unsafe {
proxyhandler::init();
// Create the global vtables used by the (generated) DOM
// bindings to implement JS proxies.
RegisterBindings::RegisterProxyHandlers();
}
perform_platform_specific_initialization();
... | {} | identifier_body |
init.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::RegisterBindings;
use crate::dom::bindings::proxyhandler;
use crate::script_ru... | ,
};
match libc::setrlimit(libc::RLIMIT_NOFILE, &rlim) {
0 => (),
_ => warn!("Failed to set file count limit"),
};
},
_ => warn!("Failed to get file count limit"),
};
}
}
#[cfg(not(target_os = "l... | {
if rlim.rlim_max < MAX_FILE_LIMIT {
rlim.rlim_max
} else {
MAX_FILE_LIMIT
}
} | conditional_block |
TowersOfHanoi.rs | use std::iter::repeat;
struct TowersOfHanoi {
_n: usize,
}
impl TowersOfHanoi {
fn new (n: usize) -> TowersOfHanoi {
TowersOfHanoi {
_n: n,
}
}
fn hanoi(&self, m: &usize, from: usize, to: usize, work: usize, s:&mut Vec<Vec<usize>>) | }
}
fn disp(&self, a: Vec<Vec<usize>>) -> String {
// println!("a:{:?}", &a);
if a[0].is_empty() && a[1].is_empty() && a[2].is_empty() {
// println!("disp\n");
// println!("{:?}", a);
return (vec!["-"; &self._n*2*3]).join("") + "\n"
} else {
... | {
if m.eq(&1) {
// println!("pre:{:?}", &s[from]);
// don't use swap_remove, because of swap_remove behave strange.
let head: usize = *s[from].first().unwrap();
s[from].remove(0);
// println!("post:{:?}", &s[from]);
s[to].insert(0, head); ... | identifier_body |
TowersOfHanoi.rs | use std::iter::repeat;
struct TowersOfHanoi {
_n: usize,
}
impl TowersOfHanoi {
fn new (n: usize) -> TowersOfHanoi {
TowersOfHanoi {
_n: n,
}
}
fn hanoi(&self, m: &usize, from: usize, to: usize, work: usize, s:&mut Vec<Vec<usize>>) {
if m.eq(&1) {
// p... | // println!("str_disp:{:?}", str_disp);
let tail = &self.disp(str_disp);
let head = a.iter()
.map(|x| {
Some(x).and_then(|tmp|
if tmp.len()==0 {Some(0)}
else {Some(*tm... | ).unwrap())
.collect::<Vec<Vec<usize>>>(); | random_line_split |
TowersOfHanoi.rs | use std::iter::repeat;
struct TowersOfHanoi {
_n: usize,
}
impl TowersOfHanoi {
fn new (n: usize) -> TowersOfHanoi {
TowersOfHanoi {
_n: n,
}
}
fn hanoi(&self, m: &usize, from: usize, to: usize, work: usize, s:&mut Vec<Vec<usize>>) {
if m.eq(&1) {
// p... | let s2 = (vec!["■■"; x]).join("");
let s3 = (vec![" "; &self._n-x]).join("");
return s1 + s2.as_str() + s3.as_str() + ""})
.collect::<Vec<String>>();
return tail.clone() + "\n" + (head.join("").as_str(... | {
let str_disp = a.iter()
.map(|x|
Some(x).and_then(
|tmp| if tmp.len()==0 {Some(vec![])}
// skip(k) skips k elements, not k-th element.
... | conditional_block |
TowersOfHanoi.rs | use std::iter::repeat;
struct TowersOfHanoi {
_n: usize,
}
impl TowersOfHanoi {
fn new (n: usize) -> TowersOfHanoi {
TowersOfHanoi {
_n: n,
}
}
fn | (&self, m: &usize, from: usize, to: usize, work: usize, s:&mut Vec<Vec<usize>>) {
if m.eq(&1) {
// println!("pre:{:?}", &s[from]);
// don't use swap_remove, because of swap_remove behave strange.
let head: usize = *s[from].first().unwrap();
s[from].remove(0);
... | hanoi | identifier_name |
build.rs | use bindgen::RustTarget;
use pkg_config::Error;
use std::env;
use std::io::Write;
use std::path::PathBuf;
fn main() | let stderr = String::from_utf8(output.stderr).unwrap();
if stderr.contains::<&str>(
format!(
"{} was not found in the pkg-config search path",
package_name
)
.as_ref(),
) {
let err_... | {
let package_name = "cfitsio";
match pkg_config::probe_library(package_name) {
Ok(_) => {
let bindings = bindgen::builder()
.header("wrapper.h")
.block_extern_crate(true)
.opaque_type("fitsfile")
.opaque_type("FITSfile")
... | identifier_body |
build.rs | use bindgen::RustTarget;
use pkg_config::Error;
use std::env;
use std::io::Write;
use std::path::PathBuf;
fn main() {
let package_name = "cfitsio";
match pkg_config::probe_library(package_name) {
Ok(_) => {
let bindings = bindgen::builder()
.header("wrapper.h")
... | );
std::io::stderr().write_all(err_msg.as_bytes()).unwrap();
std::process::exit(output.status.code().unwrap());
}
}
Err(e) => panic!("Unhandled error: {:?}", e),
};
}
| {
// Handle the case where the user has not installed cfitsio, and thusly it is not on
// the PKG_CONFIG_PATH
let stderr = String::from_utf8(output.stderr).unwrap();
if stderr.contains::<&str>(
format!(
"{} was not found in the pkg-conf... | conditional_block |
build.rs | use bindgen::RustTarget;
use pkg_config::Error;
use std::env;
use std::io::Write;
use std::path::PathBuf;
fn | () {
let package_name = "cfitsio";
match pkg_config::probe_library(package_name) {
Ok(_) => {
let bindings = bindgen::builder()
.header("wrapper.h")
.block_extern_crate(true)
.opaque_type("fitsfile")
.opaque_type("FITSfile")
... | main | identifier_name |
build.rs | use bindgen::RustTarget; |
fn main() {
let package_name = "cfitsio";
match pkg_config::probe_library(package_name) {
Ok(_) => {
let bindings = bindgen::builder()
.header("wrapper.h")
.block_extern_crate(true)
.opaque_type("fitsfile")
.opaque_type("FITSfile")... | use pkg_config::Error;
use std::env;
use std::io::Write;
use std::path::PathBuf; | random_line_split |
corsym.rs | // Copyright © 2015, Peter Atashian
// Licensed under the MIT License <LICENSE.md>
//! Common Language Runtime Debugging Symbol Reader/Writer/Binder Interfaces
DEFINE_GUID!(CorSym_LanguageType_C, 0x63a08714, 0xfc37, 0x11d2,
0x90, 0x4c, 0x0, 0xc0, 0x4f, 0xa3, 0x02, 0xa1);
DEFINE_GUID!(CorSym_LanguageType_CPlusPlus, ... | SymUnmanagedReader; | identifier_name | |
corsym.rs | // Copyright © 2015, Peter Atashian
// Licensed under the MIT License <LICENSE.md>
//! Common Language Runtime Debugging Symbol Reader/Writer/Binder Interfaces
DEFINE_GUID!(CorSym_LanguageType_C, 0x63a08714, 0xfc37, 0x11d2,
0x90, 0x4c, 0x0, 0xc0, 0x4f, 0xa3, 0x02, 0xa1);
DEFINE_GUID!(CorSym_LanguageType_CPlusPlus, ... | pub struct ISymUnmanagedReader; | );
#[derive(Clone, Copy)] | random_line_split |
home.rs | use iron::prelude::*;
use iron::middleware::Handler;
use iron::status;
use iron::headers::{ContentType};
use utils::Utils;
use rustview::view::View;
pub struct Index {
utils: Utils,
template: View,
}
impl Index {
pub fn | (utils: Utils, admin_template: View) -> Index {
Index {
utils: utils,
template: admin_template,
}
}
}
impl Handler for Index {
fn handle(&self, req: &mut Request) -> IronResult<Response> {
let model = json!({
"title": "Testing",
"newTitle"... | new | identifier_name |
home.rs | use iron::prelude::*;
use iron::middleware::Handler;
use iron::status;
use iron::headers::{ContentType};
use utils::Utils;
use rustview::view::View;
pub struct Index {
utils: Utils,
template: View,
}
impl Index {
pub fn new(utils: Utils, admin_template: View) -> Index {
Index {
utils:... | fn handle(&self, req: &mut Request) -> IronResult<Response> {
let model = json!({
"title": "Testing",
"newTitle": "New Cool Title here :)",
"helloUser": "Hi Andrei!",
"testText": "It's working!!!!!",
"user": "Andrei",
"child_user": "Hom... | }
impl Handler for Index { | random_line_split |
home.rs | use iron::prelude::*;
use iron::middleware::Handler;
use iron::status;
use iron::headers::{ContentType};
use utils::Utils;
use rustview::view::View;
pub struct Index {
utils: Utils,
template: View,
}
impl Index {
pub fn new(utils: Utils, admin_template: View) -> Index |
}
impl Handler for Index {
fn handle(&self, req: &mut Request) -> IronResult<Response> {
let model = json!({
"title": "Testing",
"newTitle": "New Cool Title here :)",
"helloUser": "Hi Andrei!",
"testText": "It's working!!!!!",
"user": "Andrei",
... | {
Index {
utils: utils,
template: admin_template,
}
} | identifier_body |
mod.rs | use std::fmt;
use std::str::FromStr;
use model::Strand;
use util;
#[derive(Clone,Debug)]
pub enum GtfFeature {
StartCodon, StopCodon, Exon, CDS, Intron, Gene, Transcript
}
#[derive(Clone,Debug,PartialEq)]
pub enum GtfAnnotation {
GeneId(String),
TranscriptId(String),
ExonNumber(usize),
Unknown(String,String)
}
... | (mut self, new_frame: usize) -> Self {
self.frame = Some(new_frame);
self
}
pub fn without_frame(mut self) -> Self {
self.frame = None;
self
}
pub fn has_annotations(&self) -> bool {
self.annotations.len() > 0
}
pub fn annotations(&self) -> Vec<GtfAnnotation> {
self.annotations.clone()
}
pub fn wi... | with_frame | identifier_name |
mod.rs | use std::fmt;
use std::str::FromStr;
use model::Strand;
use util;
#[derive(Clone,Debug)]
pub enum GtfFeature {
StartCodon, StopCodon, Exon, CDS, Intron, Gene, Transcript
}
#[derive(Clone,Debug,PartialEq)]
pub enum GtfAnnotation {
GeneId(String),
TranscriptId(String),
ExonNumber(usize),
Unknown(String,String)
}
... |
pub fn without_source(mut self) -> Self {
self.source = None;
self
}
pub fn has_feature(&self) -> bool {
self.feature.is_some()
}
pub fn feature(&self) -> Option<GtfFeature> {
self.feature.clone()
}
pub fn with_feature(mut self, new_feature: GtfFeature) -> Self {
self.feature = Some(new_feature);
... | {
self.source = Some(new_source.to_string());
self
} | identifier_body |
mod.rs | use std::fmt;
use std::str::FromStr;
use model::Strand;
use util;
#[derive(Clone,Debug)]
pub enum GtfFeature {
StartCodon, StopCodon, Exon, CDS, Intron, Gene, Transcript
}
#[derive(Clone,Debug,PartialEq)]
pub enum GtfAnnotation {
GeneId(String),
TranscriptId(String),
ExonNumber(usize),
Unknown(String,String)
}
... | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.clone() {
GtfFeature::Gene => write!(f, "gene"),
GtfFeature::Transcript => write!(f, "transcript"),
GtfFeature::CDS => write!(f, "CDS"),
GtfFeature::Exon => write!(f, "exon"),
GtfFeature::Intron => write!(f, "intron... | }
}
}
impl fmt::Display for GtfFeature { | random_line_split |
concat_idents.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | else {
match *e {
ast::tt_tok(_, token::IDENT(ident,_)) =>
res_str += cx.str_of(ident),
_ => cx.span_fatal(sp, ~"concat_idents! \
requires ident args.")
}
}
}
let res = cx.parse_sess().inter... | {
match *e {
ast::tt_tok(_, token::COMMA) => (),
_ => cx.span_fatal(sp, ~"concat_idents! \
expecting comma.")
}
} | conditional_block |
concat_idents.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 ... | let e = @ast::expr {
id: cx.next_id(),
callee_id: cx.next_id(),
node: ast::expr_path(
@ast::Path {
span: sp,
global: false,
idents: ~[res],
rp: None,
types: ~[],
}
),
... | {
let mut res_str = ~"";
for tts.eachi |i, e| {
if i & 1 == 1 {
match *e {
ast::tt_tok(_, token::COMMA) => (),
_ => cx.span_fatal(sp, ~"concat_idents! \
expecting comma.")
}
} else {
matc... | identifier_body |
concat_idents.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 ... | span: sp,
global: false,
idents: ~[res],
rp: None,
types: ~[],
}
),
span: sp,
};
MRExpr(e)
} | id: cx.next_id(),
callee_id: cx.next_id(),
node: ast::expr_path(
@ast::Path { | random_line_split |
concat_idents.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 ... | (cx: @ext_ctxt, sp: span, tts: &[ast::token_tree])
-> base::MacResult {
let mut res_str = ~"";
for tts.eachi |i, e| {
if i & 1 == 1 {
match *e {
ast::tt_tok(_, token::COMMA) => (),
_ => cx.span_fatal(sp, ~"concat_idents! \
... | expand_syntax_ext | identifier_name |
error.rs | use pyo3::{exceptions, PyErr};
use std::error::Error;
pub type BoxError = std::boxed::Box<dyn std::error:: Error + std::marker::Send + std::marker::Sync>;
macro_rules! estructurar {
($nombre: ident, $excepcion: path, $mensaje: expr) => {
pub struct $nombre {
pub source: Option<BoxError>
... | impl std::fmt::Debug for $nombre {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result{
<$nombre as std::fmt::Display>::fmt(self, f)
}
}
impl std::convert::From<$nombre> for PyErr {
fn from(error: $nombre) -> PyErr {
<$exc... | }
Ok(())
}
} | random_line_split |
win_impl.rs | use winapi;
use self::winapi::shared::windef::POINT;
use self::winapi::ctypes::c_int;
use self::winapi::um::winuser::*;
use crate::win::keycodes::*;
use crate::{Key, KeyboardControllable, MouseButton, MouseControllable};
use std::mem::*;
/// The main struct for handling the event emitting
#[derive(Default)]
pub stru... | (&mut self, key: Key) {
let scancode = self.key_to_scancode(key);
use std::{thread, time};
keybd_event(KEYEVENTF_SCANCODE, 0, scancode);
thread::sleep(time::Duration::from_millis(20));
keybd_event(KEYEVENTF_KEYUP | KEYEVENTF_SCANCODE, 0, scancode);
}
fn key_down(&mut sel... | key_click | identifier_name |
win_impl.rs | use winapi;
use self::winapi::shared::windef::POINT;
use self::winapi::ctypes::c_int;
use self::winapi::um::winuser::*;
use crate::win::keycodes::*;
use crate::{Key, KeyboardControllable, MouseButton, MouseControllable};
use std::mem::*;
/// The main struct for handling the event emitting
#[derive(Default)]
pub stru... |
}
}
fn key_click(&mut self, key: Key) {
let scancode = self.key_to_scancode(key);
use std::{thread, time};
keybd_event(KEYEVENTF_SCANCODE, 0, scancode);
thread::sleep(time::Duration::from_millis(20));
keybd_event(KEYEVENTF_KEYUP | KEYEVENTF_SCANCODE, 0, scancode... | {
for utf16_surrogate in result {
self.unicode_key_down(utf16_surrogate.clone());
}
// do i need to produce a keyup?
// self.unicode_key_up(0);
} | conditional_block |
win_impl.rs | use winapi;
use self::winapi::shared::windef::POINT;
use self::winapi::ctypes::c_int;
use self::winapi::um::winuser::*;
use crate::win::keycodes::*;
use crate::{Key, KeyboardControllable, MouseButton, MouseControllable};
use std::mem::*;
/// The main struct for handling the event emitting
#[derive(Default)]
pub stru... |
fn key_up(&mut self, key: Key) {
keybd_event(
KEYEVENTF_KEYUP | KEYEVENTF_SCANCODE,
0,
self.key_to_scancode(key),
);
}
}
impl Enigo {
/// Gets the (width, height) of the main display in screen coordinates (pixels).
///
/// # Example
///
... | {
keybd_event(KEYEVENTF_SCANCODE, 0, self.key_to_scancode(key));
} | identifier_body |
win_impl.rs | use winapi;
use self::winapi::shared::windef::POINT;
use self::winapi::ctypes::c_int;
use self::winapi::um::winuser::*;
use crate::win::keycodes::*;
use crate::{Key, KeyboardControllable, MouseButton, MouseControllable};
use std::mem::*;
/// The main struct for handling the event emitting
#[derive(Default)]
pub stru... | (point.x, point.y)
} else {
(0, 0)
}
}
fn unicode_key_click(&self, unicode_char: u16) {
use std::{thread, time};
self.unicode_key_down(unicode_char);
thread::sleep(time::Duration::from_millis(20));
self.unicode_key_up(unicode_char);
}
... | let mut point = POINT { x: 0, y: 0 };
let result = unsafe { GetCursorPos(&mut point) };
if result != 0 { | random_line_split |
mod.rs | use alloc::boxed::Box;
use schemes::{Result, KScheme, Resource, Url};
use syscall::{Error, O_CREAT, ENOENT};
pub use self::dsdt::DSDT;
pub use self::fadt::FADT;
pub use self::madt::MADT;
pub use self::rsdt::RSDT;
pub use self::sdt::SDTHeader;
pub use self::ssdt::SSDT;
pub mod aml;
pub mod dsdt;
pub mod fadt;
pub mod m... |
impl KScheme for Acpi {
fn scheme(&self) -> &str {
"acpi"
}
fn open(&mut self, url: &Url, flags: usize) -> Result<Box<Resource>> {
if url.reference() == "off" && flags & O_CREAT == O_CREAT {
match self.fadt {
Some(fadt) => {
debugln!("Powerin... | random_line_split | |
mod.rs | use alloc::boxed::Box;
use schemes::{Result, KScheme, Resource, Url};
use syscall::{Error, O_CREAT, ENOENT};
pub use self::dsdt::DSDT;
pub use self::fadt::FADT;
pub use self::madt::MADT;
pub use self::rsdt::RSDT;
pub use self::sdt::SDTHeader;
pub use self::ssdt::SSDT;
pub mod aml;
pub mod dsdt;
pub mod fadt;
pub mod m... |
fn open(&mut self, url: &Url, flags: usize) -> Result<Box<Resource>> {
if url.reference() == "off" && flags & O_CREAT == O_CREAT {
match self.fadt {
Some(fadt) => {
debugln!("Powering Off");
unsafe {
asm!("out dx, ... | {
"acpi"
} | identifier_body |
mod.rs | use alloc::boxed::Box;
use schemes::{Result, KScheme, Resource, Url};
use syscall::{Error, O_CREAT, ENOENT};
pub use self::dsdt::DSDT;
pub use self::fadt::FADT;
pub use self::madt::MADT;
pub use self::rsdt::RSDT;
pub use self::sdt::SDTHeader;
pub use self::ssdt::SSDT;
pub mod aml;
pub mod dsdt;
pub mod fadt;
pub mod m... | (&self) -> &str {
"acpi"
}
fn open(&mut self, url: &Url, flags: usize) -> Result<Box<Resource>> {
if url.reference() == "off" && flags & O_CREAT == O_CREAT {
match self.fadt {
Some(fadt) => {
debugln!("Powering Off");
unsafe {
... | scheme | identifier_name |
mod.rs | use alloc::boxed::Box;
use schemes::{Result, KScheme, Resource, Url};
use syscall::{Error, O_CREAT, ENOENT};
pub use self::dsdt::DSDT;
pub use self::fadt::FADT;
pub use self::madt::MADT;
pub use self::rsdt::RSDT;
pub use self::sdt::SDTHeader;
pub use self::ssdt::SSDT;
pub mod aml;
pub mod dsdt;
pub mod fadt;
pub mod m... | else if let Some(ssdt) = SSDT::new(header) {
// debugln!("SSDT:");
// aml::parse(ssdt.data);
acpi.ssdt = Some(ssdt);
} else if let Some(madt) = MADT::new(header) {
acpi.madt = Some(madt);
... | {
// Why does this hang? debugln!("{:#?}", fadt);
if let Some(dsdt) = DSDT::new(unsafe {
&*(fadt.dsdt as *const SDTHeader)
}) {
// debugln!("DSDT:");
// aml::parse(... | conditional_block |
lib.rs | // Copyright 2012-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-MI... |
for variant in &enum_def.variants {
match variant.node.kind {
ast::TupleVariantKind(ref args) => {
if!args.is_empty() {
cx.span_err(trait_span,
"`FromPrimitive` cannot be derived ... | {
if substr.nonself_args.len() != 1 {
cx.span_bug(trait_span, "incorrect number of arguments in `derive(FromPrimitive)`")
}
let n = &substr.nonself_args[0];
match *substr.fields {
StaticStruct(..) => {
cx.span_err(trait_span, "`FromPrimitive` cannot be derived for structs")... | identifier_body |
lib.rs | // Copyright 2012-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-MI... |
StaticEnum(enum_def, _) => {
if enum_def.variants.is_empty() {
cx.span_err(trait_span,
"`FromPrimitive` cannot be derived for enums with no variants");
return cx.expr_fail(trait_span, InternedString::new(""));
}
le... | {
cx.span_err(trait_span, "`FromPrimitive` cannot be derived for structs");
return cx.expr_fail(trait_span, InternedString::new(""));
} | conditional_block |
lib.rs | // Copyright 2012-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-MI... | if $cx.use_std {
pathvec!(std :: $($rest)::+)
} else {
pathvec!($first :: $($rest)::+)
}
)
}
macro_rules! path_std {
($($x:tt)*) => (
::syntax::ext::deriving::generic::ty::Path::new( pathvec_std!( $($x)* ) )
)
}
pub fn expand_deriving_from_primitive(... | }
macro_rules! pathvec_std {
($cx:expr, $first:ident :: $($rest:ident)::+) => ( | random_line_split |
lib.rs | // Copyright 2012-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-MI... | (cx: &mut ExtCtxt,
span: Span,
mitem: &MetaItem,
item: &Annotatable,
push: &mut FnMut(Annotatable))
{
let inline = cx.meta_word(span, InternedString::new("inline"))... | expand_deriving_from_primitive | identifier_name |
lib.rs | /* Copyright (C) 2017-2021 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY... | #[macro_use]
extern crate suricata_derive;
#[macro_use]
pub mod log;
#[macro_use]
pub mod core;
#[macro_use]
pub mod common;
pub mod conf;
pub mod jsonbuilder;
#[macro_use]
pub mod applayer;
/// cbindgen:ignore
pub mod frames;
pub mod filecontainer;
pub mod filetracker;
pub mod kerberos;
#[cfg(feature = "lua")]
pub... | extern crate kerberos_parser;
extern crate tls_parser;
extern crate x509_parser;
| random_line_split |
error.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 ... | (error: IoError) -> IoError { error }
}
impl Error for IoError {
fn description(&self) -> &str {
self.desc
}
fn detail(&self) -> Option<&str> {
self.detail.as_ref().map(|s| &s[])
}
}
//fn iter_map_err<T, U, E, I: Iterator<Result<T,E>>>(iter: I,
| from_err | identifier_name |
error.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 ... |
}
impl<'a> Error for &'a str {
fn description<'b>(&'b self) -> &'b str {
*self
}
}
impl Error for String {
fn description<'a>(&'a self) -> &'a str {
&self[]
}
}
impl<'a> Error for Box<Error + 'a> {
fn description(&self) -> &str { (**self).description() }
fn detail(&self) -> O... | {
box err as Box<Error>
} | identifier_body |
error.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | &self[]
}
}
impl<'a> Error for Box<Error + 'a> {
fn description(&self) -> &str { (**self).description() }
fn detail(&self) -> Option<&str> { (**self).detail() }
fn cause(&self) -> Option<&Error> { (**self).cause() }
}
impl FromError<()> for () {
fn from_err(_: ()) -> () { () }
}
impl From... | fn description<'a>(&'a self) -> &'a str { | random_line_split |
ls.rs | use std::env;
use std::fs::File;
use std::io;
use chrono::{DateTime, Local};
use fatfs::{FileSystem, FsOptions};
use fscommon::BufStream;
fn format_file_size(size: u64) -> String {
const KB: u64 = 1024;
const MB: u64 = 1024 * KB;
const GB: u64 = 1024 * MB;
if size < KB {
format!("{}B", size)
... | format!("{}KB", size / KB)
} else if size < GB {
format!("{}MB", size / MB)
} else {
format!("{}GB", size / GB)
}
}
fn main() -> io::Result<()> {
let file = File::open("resources/fat32.img")?;
let buf_rdr = BufStream::new(file);
let fs = FileSystem::new(buf_rdr, FsOption... | random_line_split | |
ls.rs | use std::env;
use std::fs::File;
use std::io;
use chrono::{DateTime, Local};
use fatfs::{FileSystem, FsOptions};
use fscommon::BufStream;
fn format_file_size(size: u64) -> String {
const KB: u64 = 1024;
const MB: u64 = 1024 * KB;
const GB: u64 = 1024 * MB;
if size < KB {
format!("{}B", size)
... | {
let file = File::open("resources/fat32.img")?;
let buf_rdr = BufStream::new(file);
let fs = FileSystem::new(buf_rdr, FsOptions::new())?;
let root_dir = fs.root_dir();
let dir = match env::args().nth(1) {
None => root_dir,
Some(ref path) if path == "." => root_dir,
Some(ref ... | identifier_body | |
ls.rs | use std::env;
use std::fs::File;
use std::io;
use chrono::{DateTime, Local};
use fatfs::{FileSystem, FsOptions};
use fscommon::BufStream;
fn format_file_size(size: u64) -> String {
const KB: u64 = 1024;
const MB: u64 = 1024 * KB;
const GB: u64 = 1024 * MB;
if size < KB | else if size < MB {
format!("{}KB", size / KB)
} else if size < GB {
format!("{}MB", size / MB)
} else {
format!("{}GB", size / GB)
}
}
fn main() -> io::Result<()> {
let file = File::open("resources/fat32.img")?;
let buf_rdr = BufStream::new(file);
let fs = FileSystem::... | {
format!("{}B", size)
} | conditional_block |
ls.rs | use std::env;
use std::fs::File;
use std::io;
use chrono::{DateTime, Local};
use fatfs::{FileSystem, FsOptions};
use fscommon::BufStream;
fn | (size: u64) -> String {
const KB: u64 = 1024;
const MB: u64 = 1024 * KB;
const GB: u64 = 1024 * MB;
if size < KB {
format!("{}B", size)
} else if size < MB {
format!("{}KB", size / KB)
} else if size < GB {
format!("{}MB", size / MB)
} else {
format!("{}GB", s... | format_file_size | identifier_name |
varint.rs | #![deny(missing_docs)]
use crate::error::*;
use std::io::Read;
const VARINT_MAX_BYTES: usize = 10;
pub fn decode_varint(read: &mut dyn Read) -> Result<u64> {
let mut varint_buf: Vec<u8> = Vec::new();
for i in 0..VARINT_MAX_BYTES {
varint_buf.push(0u8);
match read.read_exact(&mut varint_buf[i.... |
#[test]
fn test_delimiter_longer() {
assert_eq!(
300,
decode_varint(&mut Cursor::new(encode_varint(300))).unwrap()
);
}
}
| {
assert_eq!(
1,
decode_varint(&mut Cursor::new(encode_varint(1))).unwrap()
);
} | identifier_body |
varint.rs | #![deny(missing_docs)]
use crate::error::*;
use std::io::Read;
const VARINT_MAX_BYTES: usize = 10;
pub fn decode_varint(read: &mut dyn Read) -> Result<u64> {
let mut varint_buf: Vec<u8> = Vec::new();
for i in 0..VARINT_MAX_BYTES {
varint_buf.push(0u8);
match read.read_exact(&mut varint_buf[i.... | () {
assert_eq!(
1,
decode_varint(&mut Cursor::new(encode_varint(1))).unwrap()
);
}
#[test]
fn test_delimiter_longer() {
assert_eq!(
300,
decode_varint(&mut Cursor::new(encode_varint(300))).unwrap()
);
}
}
| test_simple | identifier_name |
varint.rs | #![deny(missing_docs)]
use crate::error::*;
use std::io::Read;
const VARINT_MAX_BYTES: usize = 10;
pub fn decode_varint(read: &mut dyn Read) -> Result<u64> {
let mut varint_buf: Vec<u8> = Vec::new();
for i in 0..VARINT_MAX_BYTES {
varint_buf.push(0u8);
match read.read_exact(&mut varint_buf[i.... |
pub fn encode_varint(mut value: u64) -> Vec<u8> {
let mut ret = vec![0u8; VARINT_MAX_BYTES];
let mut n = 0;
while value > 127 {
ret[n] = 0x80 | (value & 0x7F) as u8;
value >>= 7;
n += 1
}
ret[n] = value as u8;
n += 1;
ret[0..n].to_vec()
}
#[cfg(test)]
mod tests {
... | Err(StreamDelimitError::VarintDecodeMaxBytesError)
} | random_line_split |
job.rs | // FIXME: stolen from cargo. Should be extracted into a common crate.
//! Job management (mostly for windows)
//!
//! Most of the time when you're running cargo you expect Ctrl-C to actually
//! terminate the entire tree of processes in play, not just the one at the top
//! (cago). This currently works "by default" on... |
let job = Handle { inner: job };
// Indicate that when all handles to the job object are gone that all
// process in the object should be killed. Note that this includes our
// entire process tree by default because we've added ourselves and
// our children will reside in the j... | {
return None;
} | conditional_block |
job.rs | // FIXME: stolen from cargo. Should be extracted into a common crate.
//! Job management (mostly for windows)
//!
//! Most of the time when you're running cargo you expect Ctrl-C to actually
//! terminate the entire tree of processes in play, not just the one at the top
//! (cago). This currently works "by default" on... | {
job: Handle,
}
pub struct Handle {
inner: HANDLE,
}
fn last_err() -> io::Error {
io::Error::last_os_error()
}
pub unsafe fn setup() -> Option<Setup> {
// Creates a new job object for us to use and then adds ourselves to it.
// Note that all errors ar... | Setup | identifier_name |
job.rs | // FIXME: stolen from cargo. Should be extracted into a common crate.
//! Job management (mostly for windows)
//!
//! Most of the time when you're running cargo you expect Ctrl-C to actually
//! terminate the entire tree of processes in play, not just the one at the top
//! (cago). This currently works "by default" on... | mem::size_of_val(&info) as DWORD,
);
if r == 0 {
info!("failed to configure job object to defaults: {}", last_err());
}
}
}
}
impl Drop for Handle {
fn drop(&mut self) {
unsafe {
... | info = mem::zeroed();
let r = SetInformationJobObject(
self.job.inner,
JobObjectExtendedLimitInformation,
&mut info as *mut _ as LPVOID, | random_line_split |
job.rs | // FIXME: stolen from cargo. Should be extracted into a common crate.
//! Job management (mostly for windows)
//!
//! Most of the time when you're running cargo you expect Ctrl-C to actually
//! terminate the entire tree of processes in play, not just the one at the top
//! (cago). This currently works "by default" on... |
#[cfg(unix)]
mod imp {
pub type Setup = ();
pub unsafe fn setup() -> Option<()> {
Some(())
}
}
#[cfg(windows)]
mod imp {
use std::io;
use std::mem;
use std::ptr;
use winapi::shared::minwindef::*;
use winapi::um::handleapi::*;
use winapi::um::jobapi2::*;
use winapi::u... | {
unsafe { imp::setup() }
} | identifier_body |
group.rs | use std::slice;
use std::mem::{ transmute, size_of };
use libc::*;
use ::core::{ Tox, Friend, Group, Peer };
use super::{ ffi };
pub type AvGroupCallback = Fn(Group, Peer, &[i16], u32, u8, u32);
pub trait AvGroupCreate {
fn create_group_av(&self, cb: Box<AvGroupCallback>) -> Result<Group, ()>;
fn join_av(&se... | }
impl AvGroupCreate for Tox {
fn create_group_av(&self, cb: Box<AvGroupCallback>) -> Result<Group, ()> {
match unsafe { ffi::toxav_add_av_groupchat(
transmute(self.core),
on_group_av,
transmute(&cb)
) } {
-1 => Err(()),
num => Ok(Group::f... | random_line_split | |
group.rs | use std::slice;
use std::mem::{ transmute, size_of };
use libc::*;
use ::core::{ Tox, Friend, Group, Peer };
use super::{ ffi };
pub type AvGroupCallback = Fn(Group, Peer, &[i16], u32, u8, u32);
pub trait AvGroupCreate {
fn create_group_av(&self, cb: Box<AvGroupCallback>) -> Result<Group, ()>;
fn join_av(&se... | {
unsafe {
let group = Group::from(transmute(core), group_number);
let peer = Peer::from(&group, peer_number);
let callback: &Box<AvGroupCallback> = transmute(cb);
callback(
group,
peer,
slice::from_raw_parts(pcm, samples as usize * channels as usi... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.