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 |
|---|---|---|---|---|
main.rs | //! This expands upon the implementation defined on [Rosetta Code][element definition] and consists
//! of the relevant lines from the `LinkedList` implementation in the Rust standard library.
//!
//! [element definition]: http://rosettacode.org/wiki/Doubly-linked_list/Element_definition
#![allow(dead_code)]
use std:... |
}
fn main() {
use std::collections;
let mut list1 = collections::LinkedList::new();
list1.push_front(8);
let mut list2 = LinkedList::new();
list2.push_front(8);
}
| {
Self::new()
} | identifier_body |
main.rs | //! This expands upon the implementation defined on [Rosetta Code][element definition] and consists
//! of the relevant lines from the `LinkedList` implementation in the Rust standard library.
//!
//! [element definition]: http://rosettacode.org/wiki/Doubly-linked_list/Element_definition
#![allow(dead_code)]
use std:... | () {
use std::collections;
let mut list1 = collections::LinkedList::new();
list1.push_front(8);
let mut list2 = LinkedList::new();
list2.push_front(8);
}
| main | identifier_name |
output.rs | use escape_grapheme::{escape_grapheme, lang, CharEncoder, Named};
use std::io;
pub fn write_to<W: io::Write>(writer: &mut W, grapheme: &str) -> std::io::Result<()> {
writeln!(writer)?;
writeln!(writer, "{}", language_output(grapheme, lang::css::Css))?; | writeln!(writer)?;
writeln!(writer, "{}", language_output(grapheme, lang::html::Html))?;
writeln!(writer)?;
writeln!(writer, "{}", language_output(grapheme, lang::js::Js))?;
Ok(())
}
fn language_output<T: CharEncoder + Named>(grapheme: &str, t: T) -> String {
let grey = ansi_term::Colour::Blac... | random_line_split | |
output.rs | use escape_grapheme::{escape_grapheme, lang, CharEncoder, Named};
use std::io;
pub fn write_to<W: io::Write>(writer: &mut W, grapheme: &str) -> std::io::Result<()> {
writeln!(writer)?;
writeln!(writer, "{}", language_output(grapheme, lang::css::Css))?;
writeln!(writer)?;
writeln!(writer, "{}", language... | () -> &'static str {
"AlwaysHello"
}
}
let grey = ansi_term::Colour::Black.bold();
let actual = language_output("a", AlwaysHello);
let expected = format!(" hello {}", grey.paint("-- AlwaysHello"));
assert_eq!(actual, expected);
}
}
| name | identifier_name |
output.rs | use escape_grapheme::{escape_grapheme, lang, CharEncoder, Named};
use std::io;
pub fn write_to<W: io::Write>(writer: &mut W, grapheme: &str) -> std::io::Result<()> |
fn language_output<T: CharEncoder + Named>(grapheme: &str, t: T) -> String {
let grey = ansi_term::Colour::Black.bold();
let escape = escape_grapheme(grapheme, t);
let lang = grey.paint(format!("-- {}", T::name()));
format!(" {:<10} {}", escape, lang)
}
#[cfg(test)]
mod tests {
use super::langu... | {
writeln!(writer)?;
writeln!(writer, "{}", language_output(grapheme, lang::css::Css))?;
writeln!(writer)?;
writeln!(writer, "{}", language_output(grapheme, lang::html::Html))?;
writeln!(writer)?;
writeln!(writer, "{}", language_output(grapheme, lang::js::Js))?;
Ok(())
} | identifier_body |
flags.rs | // Copyright 2017 Jeremy Wall <jeremy@marzhillstudios.com>
//
// 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 ... |
&Val::Boolean(_) | &Val::Empty | &Val::Float(_) | &Val::Int(_) | &Val::Str(_) => {
self.write_flag_name(pfx, name, w)?;
self.write_simple_value(val, w)?;
}
}
}
Ok(())
}
}
impl Converter for FlagConverter {
fn c... | {
self.write_list_flag(pfx, name, def, w)?;
} | conditional_block |
flags.rs | // Copyright 2017 Jeremy Wall <jeremy@marzhillstudios.com>
//
// 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 ... | (&self, v: &Val, w: &mut dyn Write) -> ConvertResult {
match v {
&Val::Empty => {
// Empty is a noop.
return Ok(());
}
&Val::Boolean(b) => {
write!(w, "{} ", if b { "true" } else { "false" })?;
}
&Val::Fl... | write_simple_value | identifier_name |
flags.rs | // Copyright 2017 Jeremy Wall <jeremy@marzhillstudios.com>
//
// Licensed under the Apache License, Version 2.0 (the "License"); | // You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
... | // you may not use this file except in compliance with the License. | random_line_split |
get_filesystem_type.rs | // Copyright 2021 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::syscall;
use crate::Result;
use libc::fstatfs;
use std::fs::File;
use std::mem::MaybeUninit;
use std::os::unix::io::AsRawFd;
/// Obtain fil... |
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn simple_test() {
let file = File::open("/dev/null").unwrap();
let _fstype = get_filesystem_type(&file).unwrap();
}
}
| {
let mut statfs_buf = MaybeUninit::<libc::statfs>::uninit();
// Safe because we just got the memory space with exact required amount and
// passing that on.
syscall!(unsafe { fstatfs(file.as_raw_fd(), statfs_buf.as_mut_ptr()) })?;
// Safe because the kernel guarantees the struct is initialized.
... | identifier_body |
get_filesystem_type.rs | // Copyright 2021 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::syscall;
use crate::Result;
use libc::fstatfs;
use std::fs::File;
use std::mem::MaybeUninit;
use std::os::unix::io::AsRawFd;
/// Obtain fil... | () {
let file = File::open("/dev/null").unwrap();
let _fstype = get_filesystem_type(&file).unwrap();
}
}
| simple_test | identifier_name |
get_filesystem_type.rs | // Copyright 2021 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be | use crate::Result;
use libc::fstatfs;
use std::fs::File;
use std::mem::MaybeUninit;
use std::os::unix::io::AsRawFd;
/// Obtain file system type of the file system that the file is served from.
pub fn get_filesystem_type(file: &File) -> Result<i64> {
let mut statfs_buf = MaybeUninit::<libc::statfs>::uninit();
/... | // found in the LICENSE file.
use crate::syscall; | random_line_split |
display_list_builder.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/. */
//! Constructs display lists from boxes.
use layout::box_::Box;
use layout::context::LayoutContext;
use layout::u... |
}
/// A builder object that manages display list builder should mainly hold information about the
/// initial request and desired result--for example, whether the `DisplayList` is to be used for
/// painting or hit testing. This can affect which boxes are created.
///
/// Right now, the builder isn't used for much, b... | {
()
} | identifier_body |
display_list_builder.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/. */
//! Constructs display lists from boxes.
use layout::box_::Box;
use layout::context::LayoutContext;
use layout::u... | ()
}
}
/// A builder object that manages display list builder should mainly hold information about the
/// initial request and desired result--for example, whether the `DisplayList` is to be used for
/// painting or hit testing. This can affect which boxes are created.
///
/// Right now, the builder isn't ... | impl ExtraDisplayListData for Nothing {
fn new(_: &Box) -> Nothing { | random_line_split |
display_list_builder.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/. */
//! Constructs display lists from boxes.
use layout::box_::Box;
use layout::context::LayoutContext;
use layout::u... | (&self) -> gfx::color::Color {
gfx::color::rgba(self.red, self.green, self.blue, self.alpha)
}
}
| to_gfx_color | identifier_name |
object_safety.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 ... | // ```
//
// However, it is not as simple as allowing `Self` in a projected
// type, because there are illegal ways to use `Self` as well:
//
// ```rust
// trait Trait : SuperTrait {
// ...
// fn foo(&self) -> <Self as SomeOtherTrait>::X;
// }
// ```
//
// Here... | // fn foo(&self) -> Self::X // OK, desugars to next example
// fn foo(&self) -> <Self as SuperTrait>::X // OK
// } | random_line_split |
object_safety.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn generics_require_sized_self<'tcx>(tcx: &ty::ctxt<'tcx>,
generics: &ty::Generics<'tcx>,
predicates: &ty::GenericPredicates<'tcx>)
-> bool
{
let sized_def_id = match tcx.lang_items.sized_trait() {
... | {
let trait_def = tcx.lookup_trait_def(trait_def_id);
let trait_predicates = tcx.lookup_predicates(trait_def_id);
generics_require_sized_self(tcx, &trait_def.generics, &trait_predicates)
} | identifier_body |
object_safety.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 ... |
}
// We can't monomorphize things like `fn foo<A>(...)`.
if!method.generics.types.is_empty_in(subst::FnSpace) {
return Some(MethodViolationCode::Generic);
}
None
}
fn contains_illegal_self_type_reference<'tcx>(tcx: &ty::ctxt<'tcx>,
trait_def_... | {
return Some(MethodViolationCode::ReferencesSelf);
} | conditional_block |
object_safety.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 ... | <'tcx>(tcx: &ty::ctxt<'tcx>,
trait_def_id: ast::DefId)
-> bool
{
// Because we query yes/no results frequently, we keep a cache:
let def = tcx.lookup_trait_def(trait_def_id);
let result = def.object_safety().unwrap_or_else(|| {
let result = ob... | is_object_safe | identifier_name |
opeq.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 mut x: int = 1;
x *= 2;
info2!("{}", x);
assert_eq!(x, 2);
x += 3;
info2!("{}", x);
assert_eq!(x, 5);
x *= x;
info2!("{}", x);
assert_eq!(x, 25);
x /= 5;
info2!("{}", x);
assert_eq!(x, 5);
} | identifier_body | |
opeq.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 ... | } | assert_eq!(x, 5); | random_line_split |
opeq.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 mut x: int = 1;
x *= 2;
info2!("{}", x);
assert_eq!(x, 2);
x += 3;
info2!("{}", x);
assert_eq!(x, 5);
x *= x;
info2!("{}", x);
assert_eq!(x, 25);
x /= 5;
info2!("{}", x);
assert_eq!(x, 5);
}
| main | identifier_name |
xhci_backend_device.rs | // Copyright 2019 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 super::xhci_transfer::XhciTransfer;
use crate::usb::host_backend::error::Result;
/// Address of this usb device, as in Set Address standard usb de... | /// Reset the backend device.
fn reset(&mut self) -> Result<()>;
} | /// Submit a xhci transfer to backend.
fn submit_transfer(&mut self, transfer: XhciTransfer) -> Result<()>;
/// Set address of this backend.
fn set_address(&mut self, address: UsbDeviceAddress); | random_line_split |
xhci_backend_device.rs | // Copyright 2019 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 super::xhci_transfer::XhciTransfer;
use crate::usb::host_backend::error::Result;
/// Address of this usb device, as in Set Address standard usb de... | {
Usb2,
Usb3,
}
/// Xhci backend device is a virtual device connected to xHCI controller. It handles xhci transfers.
pub trait XhciBackendDevice: Send {
/// Returns the type of USB device provided by this device.
fn get_backend_type(&self) -> BackendType;
/// Get vendor id of this device.
fn g... | BackendType | identifier_name |
unix.rs | use std::io;
use std::os::raw::{c_int, c_void};
use std::os::unix::io::{AsRawFd, RawFd};
use ::{Rawv, Writev, Readv};
struct | (RawFd);
impl<T: AsRawFd> Rawv for T {
fn readv(&mut self, buffers: &[&mut [u8]]) -> io::Result<usize> {
UnixFd(self.as_raw_fd()).readv(buffers)
}
fn writev(&mut self, buffers: &[&[u8]]) -> io::Result<usize> {
UnixFd(self.as_raw_fd()).writev(buffers)
}
}
impl Writev for UnixFd {
f... | UnixFd | identifier_name |
unix.rs | use std::io;
use std::os::raw::{c_int, c_void};
use std::os::unix::io::{AsRawFd, RawFd};
use ::{Rawv, Writev, Readv};
struct UnixFd(RawFd);
impl<T: AsRawFd> Rawv for T {
fn readv(&mut self, buffers: &[&mut [u8]]) -> io::Result<usize> {
UnixFd(self.as_raw_fd()).readv(buffers)
}
fn writev(&mut sel... | else {
Ok(ret as usize)
}
}
}
}
#[repr(C)]
struct IoVec {
iov_base: *mut c_void,
iov_len: c_int,
}
extern {
fn readv(fd: RawFd, bufs: *const IoVec, count: c_int) -> c_int;
fn writev(fd: RawFd, bufs: *const IoVec, count: c_int) -> c_int;
}
#[test]
fn test_unix... | {
Err(io::Error::last_os_error())
} | conditional_block |
unix.rs | use std::io;
use std::os::raw::{c_int, c_void};
use std::os::unix::io::{AsRawFd, RawFd};
use ::{Rawv, Writev, Readv};
struct UnixFd(RawFd);
impl<T: AsRawFd> Rawv for T {
fn readv(&mut self, buffers: &[&mut [u8]]) -> io::Result<usize> {
UnixFd(self.as_raw_fd()).readv(buffers)
}
fn writev(&mut sel... | unsafe {
let ret = writev(self.0, buffers.as_ptr() as *const IoVec, buffers.len() as c_int);
if ret == -1 {
Err(io::Error::last_os_error())
} else {
Ok(ret as usize)
}
}
}
}
impl Readv for UnixFd {
fn readv(&mut se... | }
}
impl Writev for UnixFd {
fn writev(&mut self, buffers: &[&[u8]]) -> io::Result<usize> { | random_line_split |
unix.rs | use std::io;
use std::os::raw::{c_int, c_void};
use std::os::unix::io::{AsRawFd, RawFd};
use ::{Rawv, Writev, Readv};
struct UnixFd(RawFd);
impl<T: AsRawFd> Rawv for T {
fn readv(&mut self, buffers: &[&mut [u8]]) -> io::Result<usize> {
UnixFd(self.as_raw_fd()).readv(buffers)
}
fn writev(&mut sel... |
}
impl Readv for UnixFd {
fn readv(&mut self, buffers: &[&mut [u8]]) -> io::Result<usize> {
unsafe {
let ret = readv(self.0, buffers.as_ptr() as *const IoVec, buffers.len() as c_int);
if ret == -1 {
Err(io::Error::last_os_error())
} else {
... | {
unsafe {
let ret = writev(self.0, buffers.as_ptr() as *const IoVec, buffers.len() as c_int);
if ret == -1 {
Err(io::Error::last_os_error())
} else {
Ok(ret as usize)
}
}
} | identifier_body |
task.rs | use std::ffi::c_void;
use std::future::Future;
use std::pin::Pin;
use std::ptr;
use std::sync::{
atomic::{AtomicBool, Ordering},
Arc, Mutex, Weak,
};
use std::task::{Context, Poll};
use futures_util::stream::{FuturesUnordered, Stream};
use libc::c_int;
use super::error::hyper_code;
use super::UserDataPointer;... | {
waker: std::task::Waker,
}
/// A descriptor for what type a `hyper_task` value is.
#[repr(C)]
pub enum hyper_task_return_type {
/// The value of this task is null (does not imply an error).
HYPER_TASK_EMPTY,
/// The value of this task is `hyper_error *`.
HYPER_TASK_ERROR,
/// The value of th... | hyper_waker | identifier_name |
task.rs | use std::ffi::c_void;
use std::future::Future;
use std::pin::Pin;
use std::ptr;
use std::sync::{
atomic::{AtomicBool, Ordering},
Arc, Mutex, Weak,
};
use std::task::{Context, Poll};
use futures_util::stream::{FuturesUnordered, Stream};
use libc::c_int;
use super::error::hyper_code;
use super::UserDataPointer;... |
fn output_type(&self) -> hyper_task_return_type {
match self.output {
None => hyper_task_return_type::HYPER_TASK_EMPTY,
Some(ref val) => val.as_task_type(),
}
}
}
impl Future for TaskFuture {
type Output = Box<hyper_task>;
fn poll(mut self: Pin<&mut Self>, cx:... | {
Box::new(hyper_task {
future: Box::pin(async move { fut.await.into_dyn_task_type() }),
output: None,
userdata: UserDataPointer(ptr::null_mut()),
})
} | identifier_body |
task.rs | use std::ffi::c_void;
use std::future::Future;
use std::pin::Pin;
use std::ptr;
use std::sync::{
atomic::{AtomicBool, Ordering},
Arc, Mutex, Weak,
};
use std::task::{Context, Poll};
use futures_util::stream::{FuturesUnordered, Stream};
use libc::c_int;
use super::error::hyper_code;
use super::UserDataPointer;... | fn as_task_type(&self) -> hyper_task_return_type {
hyper_task_return_type::HYPER_TASK_EMPTY
}
}
unsafe impl AsTaskType for crate::Error {
fn as_task_type(&self) -> hyper_task_return_type {
hyper_task_return_type::HYPER_TASK_ERROR
}
}
impl<T> IntoDynTaskType for T
where
T: AsTaskTyp... | random_line_split | |
lib.rs | // DO NOT EDIT!
// This file was generated automatically from'src/mako/api/lib.rs.mako'
// DO NOT EDIT!
//! This documentation was generated from *DoubleClick Bid Manager* crate version *0.1.8+20150326*, where *20150326* is the exact revision of the *doubleclickbidmanager:v1* schema built by the [mako](http://www.mako... | //! retry on failure.
//!
//! The [delegate trait](trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort.
//!
//! ## Optional Parts in Server-Requests
//!
//! All structures provided by this library are made to be [enocodable](trait.RequestValue.html) and
//! [decodable](trai... | //! Respective methods will be called to provide progress information, as well as determine whether the system should | random_line_split |
typeck-unsafe-always-share.rs | // Verify that UnsafeCell is *always*!Sync regardless if `T` is sync.
#![feature(negative_impls)]
use std::cell::UnsafeCell;
use std::marker::Sync; | u: UnsafeCell<T>
}
struct NoSync;
impl!Sync for NoSync {}
fn test<T: Sync>(s: T) {}
fn main() {
let us = UnsafeCell::new(MySync{u: UnsafeCell::new(0)});
test(us);
//~^ ERROR `UnsafeCell<MySync<{integer}>>` cannot be shared between threads safely
let uns = UnsafeCell::new(NoSync);
test(uns);
... |
struct MySync<T> { | random_line_split |
typeck-unsafe-always-share.rs | // Verify that UnsafeCell is *always*!Sync regardless if `T` is sync.
#![feature(negative_impls)]
use std::cell::UnsafeCell;
use std::marker::Sync;
struct MySync<T> {
u: UnsafeCell<T>
}
struct NoSync;
impl!Sync for NoSync {}
fn | <T: Sync>(s: T) {}
fn main() {
let us = UnsafeCell::new(MySync{u: UnsafeCell::new(0)});
test(us);
//~^ ERROR `UnsafeCell<MySync<{integer}>>` cannot be shared between threads safely
let uns = UnsafeCell::new(NoSync);
test(uns);
//~^ ERROR `UnsafeCell<NoSync>` cannot be shared between threads sa... | test | identifier_name |
typeck-unsafe-always-share.rs | // Verify that UnsafeCell is *always*!Sync regardless if `T` is sync.
#![feature(negative_impls)]
use std::cell::UnsafeCell;
use std::marker::Sync;
struct MySync<T> {
u: UnsafeCell<T>
}
struct NoSync;
impl!Sync for NoSync {}
fn test<T: Sync>(s: T) {}
fn main() | {
let us = UnsafeCell::new(MySync{u: UnsafeCell::new(0)});
test(us);
//~^ ERROR `UnsafeCell<MySync<{integer}>>` cannot be shared between threads safely
let uns = UnsafeCell::new(NoSync);
test(uns);
//~^ ERROR `UnsafeCell<NoSync>` cannot be shared between threads safely [E0277]
let ms = MyS... | identifier_body | |
blkfile.rs | use std::collections::HashMap;
use std::convert::From;
use std::fs::{self, DirEntry, File};
use std::io::{self, BufReader, Seek, SeekFrom};
use std::path::{Path, PathBuf};
use byteorder::{LittleEndian, ReadBytesExt};
use crate::blockchain::parser::reader::BlockchainRead;
use crate::blockchain::proto::block::Block;
us... |
#[inline]
pub fn read_block(&self, offset: u64, version_id: u8) -> OpResult<Block> {
let mut f = BufReader::new(File::open(&self.path)?);
f.seek(SeekFrom::Start(offset - 4))?;
let block_size = f.read_u32::<LittleEndian>()?;
f.read_block(block_size, version_id)
}
/// Col... | #[inline]
fn new(path: PathBuf, size: u64) -> BlkFile {
BlkFile { path, size }
} | random_line_split |
blkfile.rs | use std::collections::HashMap;
use std::convert::From;
use std::fs::{self, DirEntry, File};
use std::io::{self, BufReader, Seek, SeekFrom};
use std::path::{Path, PathBuf};
use byteorder::{LittleEndian, ReadBytesExt};
use crate::blockchain::parser::reader::BlockchainRead;
use crate::blockchain::proto::block::Block;
us... | (path: PathBuf, size: u64) -> BlkFile {
BlkFile { path, size }
}
#[inline]
pub fn read_block(&self, offset: u64, version_id: u8) -> OpResult<Block> {
let mut f = BufReader::new(File::open(&self.path)?);
f.seek(SeekFrom::Start(offset - 4))?;
let block_size = f.read_u32::<Litt... | new | identifier_name |
blkfile.rs | use std::collections::HashMap;
use std::convert::From;
use std::fs::{self, DirEntry, File};
use std::io::{self, BufReader, Seek, SeekFrom};
use std::path::{Path, PathBuf};
use byteorder::{LittleEndian, ReadBytesExt};
use crate::blockchain::parser::reader::BlockchainRead;
use crate::blockchain::proto::block::Block;
us... |
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_blk_index() {
let prefix = "blk";
let ext = ".dat";
assert_eq!(
0,
BlkFile::parse_blk_index("blk00000.dat", prefix, ext).unwrap()
);
assert_eq!(
6,
BlkFi... | {
if file_name.starts_with(prefix) && file_name.ends_with(ext) {
// Parse blk_index, this means we extract 42 from blk000042.dat
file_name[prefix.len()..(file_name.len() - ext.len())]
.parse::<usize>()
.ok()
} else {
None
}
... | identifier_body |
blkfile.rs | use std::collections::HashMap;
use std::convert::From;
use std::fs::{self, DirEntry, File};
use std::io::{self, BufReader, Seek, SeekFrom};
use std::path::{Path, PathBuf};
use byteorder::{LittleEndian, ReadBytesExt};
use crate::blockchain::parser::reader::BlockchainRead;
use crate::blockchain::proto::block::Block;
us... |
}
/// Resolves a PathBuf for the given entry.
/// Also resolves symlinks if present.
fn resolve_path(entry: &DirEntry) -> io::Result<PathBuf> {
if entry.file_type()?.is_symlink() {
fs::read_link(entry.path())
} else {
Ok(entry.path())
}
}
/// Id... | {
Ok(collected)
} | conditional_block |
htmltablerowelement.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::HTMLTableRowElementBinding;
use dom::bindings::utils::{DOMString, ErrorResult};
use do... | }
}
pub fn new(localName: ~str, document: AbstractDocument) -> AbstractNode {
let element = HTMLTableRowElement::new_inherited(localName, document);
Node::reflect_node(@mut element, document, HTMLTableRowElementBinding::Wrap)
}
}
impl HTMLTableRowElement {
pub fn RowIndex(&self... |
impl HTMLTableRowElement {
pub fn new_inherited(localName: ~str, document: AbstractDocument) -> HTMLTableRowElement {
HTMLTableRowElement {
htmlelement: HTMLElement::new_inherited(HTMLTableRowElementTypeId, localName, document) | random_line_split |
htmltablerowelement.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::HTMLTableRowElementBinding;
use dom::bindings::utils::{DOMString, ErrorResult};
use do... | (&self, _bg_color: DOMString) -> ErrorResult {
Ok(())
}
}
| SetBgColor | identifier_name |
htmltablerowelement.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::HTMLTableRowElementBinding;
use dom::bindings::utils::{DOMString, ErrorResult};
use do... |
pub fn BgColor(&self) -> DOMString {
~""
}
pub fn SetBgColor(&self, _bg_color: DOMString) -> ErrorResult {
Ok(())
}
}
| {
Ok(())
} | identifier_body |
bug-2470-bounds-check-overflow.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 ... | }
| {
// This should cause a bounds-check panic, but may not if we do our
// bounds checking by comparing the scaled index to the vector's
// address-bounds, since we've scaled the index to wrap around to the
// address of the 0th cell in the array (even though the index is
// huge).
let x = vec![... | identifier_body |
bug-2470-bounds-check-overflow.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 ... | println!("ov1 idx * sizeof::<usize>() = 0x{:x}",
idx * mem::size_of::<usize>());
// This should panic.
println!("ov1 0x{:x}", x[idx]);
} | let base = x.as_ptr() as usize;
let idx = base / mem::size_of::<usize>();
println!("ov1 base = 0x{:x}", base);
println!("ov1 idx = 0x{:x}", idx);
println!("ov1 sizeof::<usize>() = 0x{:x}", mem::size_of::<usize>()); | random_line_split |
bug-2470-bounds-check-overflow.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 ... | () {
// This should cause a bounds-check panic, but may not if we do our
// bounds checking by comparing the scaled index to the vector's
// address-bounds, since we've scaled the index to wrap around to the
// address of the 0th cell in the array (even though the index is
// huge).
let x = ve... | main | identifier_name |
svgelement.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::inheritance::Castable;
use dom::bindings::str::DOMString;
use dom::document::Document;
use dom:... | (state: ElementState, tag_name: LocalName,
prefix: Option<DOMString>, document: &Document)
-> SVGElement {
SVGElement {
element:
Element::new_inherited_with_state(state, tag_name, ns!(svg), prefix, document),
... | new_inherited_with_state | identifier_name |
svgelement.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::inheritance::Castable;
use dom::bindings::str::DOMString;
use dom::document::Document;
use dom:... | Element::new_inherited_with_state(state, tag_name, ns!(svg), prefix, document),
}
}
}
impl VirtualMethods for SVGElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<Element>() as &VirtualMethods)
}
} | pub fn new_inherited_with_state(state: ElementState, tag_name: LocalName,
prefix: Option<DOMString>, document: &Document)
-> SVGElement {
SVGElement {
element: | random_line_split |
slice.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, index: Range<Foo>) -> &Foo {
unsafe { COUNT += 1; }
self
}
}
impl Index<RangeTo<Foo>> for Foo {
type Output = Foo;
fn index(&self, index: RangeTo<Foo>) -> &Foo {
unsafe { COUNT += 1; }
self
}
}
impl Index<RangeFrom<Foo>> for Foo {
type Output = Foo;
fn ind... | index | identifier_name |
slice.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 Index<RangeTo<Foo>> for Foo {
type Output = Foo;
fn index(&self, index: RangeTo<Foo>) -> &Foo {
unsafe { COUNT += 1; }
self
}
}
impl Index<RangeFrom<Foo>> for Foo {
type Output = Foo;
fn index(&self, index: RangeFrom<Foo>) -> &Foo {
unsafe { COUNT += 1; }
self... | {
unsafe { COUNT += 1; }
self
} | identifier_body |
slice.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn main() {
let mut x = Foo;
&x[..];
&x[Foo..];
&x[..Foo];
&x[Foo..Foo];
&mut x[..];
&mut x[Foo..];
&mut x[..Foo];
&mut x[Foo..Foo];
unsafe {
assert_eq!(COUNT, 8);
}
} | }
| random_line_split |
image.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/. */
//! Generic types for the handling of [images].
//!
//! [images]: https://drafts.csswg.org/css-images/#image-value... | dest.write_str(", ")?;
shape.to_css(dest)?;
}
}
false
}
,
};
for item in &self.items {
if!skip_comma {
dest.write_str(", ")?;
}
skip_comma =... | {
let omit_shape = match *shape {
EndingShape::Ellipse(Ellipse::Extent(ShapeExtent::Cover)) |
EndingShape::Ellipse(Ellipse::Extent(ShapeExtent::FarthestCorner)) => true,
_ => false,
};
if self.compat_mode == Comp... | conditional_block |
image.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/. */
//! Generic types for the handling of [images].
//!
//! [images]: https://drafts.csswg.org/css-images/#image-value... |
impl<L> ToCss for Circle<L>
where
L: ToCss,
{
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
match *self {
Circle::Extent(ShapeExtent::FarthestCorner) | Circle::Extent(ShapeExtent::Cover) => {
dest.write_str("circle")
... | /// Serialises this direction according to the compatibility mode.
fn to_css<W>(&self, dest: &mut CssWriter<W>, compat_mode: CompatMode) -> fmt::Result
where
W: Write;
} | random_line_split |
image.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/. */
//! Generic types for the handling of [images].
//!
//! [images]: https://drafts.csswg.org/css-images/#image-value... | <LineDirection, Length, LengthOrPercentage, Position, Angle> {
/// A linear gradient.
Linear(LineDirection),
/// A radial gradient.
Radial(
EndingShape<Length, LengthOrPercentage>,
Position,
Option<Angle>,
),
}
/// A radial gradient's ending shape.
#[derive(Clone, Copy, Debu... | GradientKind | identifier_name |
arm.rs | use PT_FIRSTMACH;
pub type c_long = i32;
pub type c_ulong = u32; | cfg_if! {
if #[cfg(libc_const_size_of)] {
#[doc(hidden)]
pub const _ALIGNBYTES: usize = ::mem::size_of::<::c_longlong>() - 1;
} else {
#[doc(hidden)]
pub const _ALIGNBYTES: usize = 8 - 1;
}
}
pub const PT_GETREGS: ::c_int = PT_FIRSTMACH + 1;
pub const PT_SETREGS: ::c_int = P... | pub type c_char = u8;
pub type __cpu_simple_lock_nv_t = ::c_int;
// should be pub(crate), but that requires Rust 1.18.0 | random_line_split |
lib.rs | #![allow(clippy::unnecessary_wraps)] // FIXME: Should get redone with better errors
use crate::types::QueueOperation;
use actix_web::{ | use anyhow::Result;
use hybrid_clocks::{Timestamp, WallT};
use lazy_static::lazy_static;
use log::{debug, info};
use potboiler_common::{clock, db, get_raw_timestamp, types::Log};
use serde_derive::Deserialize;
use serde_json::{self, Map, Value};
use std::{env, io::Cursor, ops::Deref};
use time::Duration;
use uuid::{sel... | http::{header, Method},
App, HttpResponse, Json, Path, State,
}; | random_line_split |
lib.rs | #![allow(clippy::unnecessary_wraps)] // FIXME: Should get redone with better errors
use crate::types::QueueOperation;
use actix_web::{
http::{header, Method},
App, HttpResponse, Json, Path, State,
};
use anyhow::Result;
use hybrid_clocks::{Timestamp, WallT};
use lazy_static::lazy_static;
use log::{debug, info};... |
fn create_queue(op: Json<types::QueueCreate>) -> actix_web::Result<HttpResponse> {
let name = op.name.clone();
match add_queue_operation(&QueueOperation::Create(op.into_inner())) {
Ok(_) => {
let new_url = format!("/queue/{}", &name);
Ok(HttpResponse::Created().header(header::L... | {
let client = reqwest::Client::new();
let mut res = client.post(SERVER_URL.deref()).json(op).send().expect("sender ok");
assert_eq!(res.status(), reqwest::StatusCode::CREATED);
Ok(res.json().unwrap())
} | identifier_body |
lib.rs | #![allow(clippy::unnecessary_wraps)] // FIXME: Should get redone with better errors
use crate::types::QueueOperation;
use actix_web::{
http::{header, Method},
App, HttpResponse, Json, Path, State,
};
use anyhow::Result;
use hybrid_clocks::{Timestamp, WallT};
use lazy_static::lazy_static;
use log::{debug, info};... | (state: AppState) -> Result<App<AppState>> {
Ok(App::with_state(state)
.resource("/create", |r| r.method(Method::POST).with(create_queue))
.resource("/event", |r| r.method(Method::POST).with(new_event))
.resource("/queue/{queue_name}", |r| {
r.method(Method::GET).with(get_queue_item... | app_router | identifier_name |
module_file.rs | // Copyright 2016 Pierre Talbot (IRCAM)
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to... | .open(output_path.clone())
.expect(&format!("Output file ({})", output_path.to_str().unwrap_or("<invalid UTF8>")));
file.write_fmt(format_args!("{}", output)).unwrap();
}
fn build_output_directory(&self, output_path: PathBuf) {
if let Some(dir_path) = output_path.parent() {
DirBuilder::new()
... | .truncate(true)
.create(true) | random_line_split |
module_file.rs | // Copyright 2016 Pierre Talbot (IRCAM)
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to... |
}
}
}
None
}
pub fn is_lib(&self) -> bool {
self.output_path.is_none()
}
fn core_file(config: &Config, file_path: PathBuf, mod_name: String) -> Self {
ModuleFile {
input_path: file_path.clone(),
output_path: Some(Self::build_output_path(config, file_path, mod_name.cl... | {
let mod_name = String::from(bonsai_file.file_stem().unwrap().to_str().unwrap());
return Some(mod_name);
} | conditional_block |
module_file.rs | // Copyright 2016 Pierre Talbot (IRCAM)
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to... | (config: &Config, file_path: PathBuf, mod_name: String) -> Self {
ModuleFile {
input_path: file_path.clone(),
output_path: Some(Self::build_output_path(config, file_path, mod_name.clone())),
module_name: mod_name
}
}
fn lib_file(file_path: PathBuf, mod_name: String) -> Self {
ModuleFi... | core_file | identifier_name |
module_file.rs | // Copyright 2016 Pierre Talbot (IRCAM)
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to... |
fn build_output_directory(&self, output_path: PathBuf) {
if let Some(dir_path) = output_path.parent() {
DirBuilder::new()
.recursive(true)
.create(dir_path)
.expect("Recursive creation of directory for the output file.");
}
}
}
| {
let output_path = self.output_path.clone().expect(
"Try to compile a library file (this is a bug).");
self.build_output_directory(output_path.clone());
let mut file = OpenOptions::new()
.write(true)
.truncate(true)
.create(true)
.open(output_path.clone())
.expect(&format!("O... | identifier_body |
branch.rs | //! Represents Git branches.
use object_id::ObjectId;
use object_database::find_object_by_id;
use error::GitError::CorruptRepository;
use error::GitError;
use repository::Repository;
use commit::Commit;
use commit;
use git_object::GitObject::GitCommit;
use commit_sort_strategy::CommitSortStrategy::MostRecent;
use comm... | (repository: &Repository, branch: &Branch) -> Result<Commit, GitError> {
match try!(find_object_by_id(repository, &branch.tip_id)) {
box GitCommit(c) => Ok(c),
_ => Err(CorruptRepository("Could not find the commit the branch points to".into_cow())),
}
}
pub fn commits(repository: &Repository, b... | tip | identifier_name |
branch.rs | //! Represents Git branches.
use object_id::ObjectId;
use object_database::find_object_by_id;
use error::GitError::CorruptRepository;
use error::GitError;
use repository::Repository;
use commit::Commit;
use commit;
use git_object::GitObject::GitCommit;
use commit_sort_strategy::CommitSortStrategy::MostRecent;
use comm... | {
let filter = CommitFilter {
since: Some(vec![branch.tip_id.clone()]),
until: None,
limit: -1,
offset: 0,
sort: MostRecent,
};
commit::find(repository, filter)
} | identifier_body | |
branch.rs | //! Represents Git branches.
use object_id::ObjectId;
use object_database::find_object_by_id;
use error::GitError::CorruptRepository;
use error::GitError; | use git_object::GitObject::GitCommit;
use commit_sort_strategy::CommitSortStrategy::MostRecent;
use commit_filter::CommitFilter;
pub struct Branch {
pub name: String,
pub canonical_name: String,
pub tip_id: ObjectId,
pub tracked_branch: Option<Box<Branch>>,
pub is_remote: bool,
pub is_detached:... | use repository::Repository;
use commit::Commit;
use commit; | random_line_split |
mod.rs | //! Bounding volumes.
#[doc(inline)]
pub use bounding_volume::bounding_volume::{HasBoundingVolume, BoundingVolume};
#[doc(inline)]
pub use bounding_volume::aabb::{HasAABB, AABB, aabb};
#[doc(inline)]
pub use bounding_volume::bounding_sphere::{HasBoundingSphere, BoundingSphere, bounding_sphere};
pub use bounding_volum... | pub type AABB3<N> = AABB<Pnt3<N>>; | random_line_split | |
error.rs | extern crate iron;
extern crate time;
use iron::prelude::*;
use iron::{Handler, BeforeMiddleware};
use iron::status;
use std::error::Error;
use std::fmt::{self, Debug};
struct ErrorHandler;
struct ErrorProducer;
#[derive(Debug)]
struct StringError(String);
impl fmt::Display for StringError {
fn fmt(&self, f: &... |
}
fn main() {
// Handler is attached here.
let mut chain = Chain::new(ErrorHandler);
// Link our error maker.
chain.link_before(ErrorProducer);
Iron::new(chain).http("localhost:3000").unwrap();
}
| {
Err(IronError::new(StringError("Error".to_string()), status::Ok))
} | identifier_body |
error.rs | extern crate iron;
extern crate time;
use iron::prelude::*;
use iron::{Handler, BeforeMiddleware};
use iron::status;
use std::error::Error;
use std::fmt::{self, Debug};
struct ErrorHandler;
struct ErrorProducer;
#[derive(Debug)]
struct StringError(String);
impl fmt::Display for StringError {
fn fmt(&self, f: &... | // Link our error maker.
chain.link_before(ErrorProducer);
Iron::new(chain).http("localhost:3000").unwrap();
} | let mut chain = Chain::new(ErrorHandler);
| random_line_split |
error.rs | extern crate iron;
extern crate time;
use iron::prelude::*;
use iron::{Handler, BeforeMiddleware};
use iron::status;
use std::error::Error;
use std::fmt::{self, Debug};
struct ErrorHandler;
struct ErrorProducer;
#[derive(Debug)]
struct StringError(String);
impl fmt::Display for StringError {
fn | (&self, f: &mut fmt::Formatter) -> fmt::Result {
Debug::fmt(self, f)
}
}
impl Error for StringError {
fn description(&self) -> &str { &*self.0 }
}
impl Handler for ErrorHandler {
fn handle(&self, _: &mut Request) -> IronResult<Response> {
Ok(Response::new())
}
}
impl BeforeMiddleware ... | fmt | identifier_name |
mod.rs | /*
TODO
Ass support for AOP (low proiroty)
*/
use token::Token as Token;
use common::ParseError as ParseError;
use type_name;
use type_name::TypeName as TypeName;
mod test;
pub struct | {
pub type_name: TypeName,
dependencies: Vec<TypeName>
}
impl Def {
pub fn accessor_at(&self, index: usize) -> &TypeName {
&self.dependencies[index]
}
}
pub fn get_def(tokens: &Vec<Token>, start: usize) -> (Result<Box<Def>, ParseError>, usize) {
let (type_name_result, seek) = type_name::g... | Def | identifier_name |
mod.rs | /*
TODO
Ass support for AOP (low proiroty)
*/
use token::Token as Token;
use common::ParseError as ParseError;
use type_name;
use type_name::TypeName as TypeName;
mod test;
pub struct Def {
pub type_name: TypeName,
dependencies: Vec<TypeName>
}
impl Def {
pub fn accessor_at(&self, index: usi... | fn dependency(tokens: &Vec<Token>, start: usize, mut def: Box<Def>) -> (Result<Box<Def>, ParseError>, usize) {
let (type_name_result, seek) = type_name::get_type_name(&tokens, start);
return match type_name_result {
Err(e) => (Err(e), seek),
Ok(type_name) => {
def.dependencies.push(*... | }
| random_line_split |
mod.rs | /*
TODO
Ass support for AOP (low proiroty)
*/
use token::Token as Token;
use common::ParseError as ParseError;
use type_name;
use type_name::TypeName as TypeName;
mod test;
pub struct Def {
pub type_name: TypeName,
dependencies: Vec<TypeName>
}
impl Def {
pub fn accessor_at(&self, index: usi... |
}
}
| {
def.dependencies.push(*type_name);
if tokens[seek].text == "," {
return dependency(&tokens, seek + 1, def);
} else {
(Ok(def), seek)
}
} | conditional_block |
mod.rs | /*
TODO
Ass support for AOP (low proiroty)
*/
use token::Token as Token;
use common::ParseError as ParseError;
use type_name;
use type_name::TypeName as TypeName;
mod test;
pub struct Def {
pub type_name: TypeName,
dependencies: Vec<TypeName>
}
impl Def {
pub fn accessor_at(&self, index: usi... | {
let (type_name_result, seek) = type_name::get_type_name(&tokens, start);
return match type_name_result {
Err(e) => (Err(e), seek),
Ok(type_name) => {
def.dependencies.push(*type_name);
if tokens[seek].text == "," {
return dependency(&tokens, seek + 1, de... | identifier_body | |
ipc_memory_mapper.rs | // Copyright 2022 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.
//! Provide utility to communicate with an iommu in another process
use std::ops::Deref;
use std::result;
use base::{AsRawDescriptor, AsRawDescriptor... | (&self, iova: u64, size: u64) -> Result<Vec<MemRegion>> {
let req = TranslateRequest {
endpoint_id: self.endpoint_id,
iova,
size,
};
self.request_tx.send(&req).map_err(Error::Tube)?;
let res: Option<Vec<MemRegion>> = self.response_rx.recv().map_err(Err... | translate | identifier_name |
ipc_memory_mapper.rs | // Copyright 2022 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.
//! Provide utility to communicate with an iommu in another process
use std::ops::Deref;
use std::result;
use base::{AsRawDescriptor, AsRawDescriptor... |
}
impl Translate for std::sync::MutexGuard<'_, IpcMemoryMapper> {
fn translate(&self, iova: u64, size: u64) -> Result<Vec<MemRegion>> {
self.deref().translate(iova, size)
}
}
pub struct CreateIpcMapperRet {
pub mapper: IpcMemoryMapper,
pub response_tx: Tube,
}
/// Returns a new `IpcMemoryMap... | {
vec![
self.request_tx.as_raw_descriptor(),
self.response_rx.as_raw_descriptor(),
]
} | identifier_body |
ipc_memory_mapper.rs | // Copyright 2022 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.
//! Provide utility to communicate with an iommu in another process
use std::ops::Deref;
use std::result;
use base::{AsRawDescriptor, AsRawDescriptor... | /// to respond to `TranslateRequest`s.
///
/// # Arguments
///
/// * `endpoint_id` - For the remote iommu to identify the device/ipc mapper.
/// * `request_tx` - A tube to send `TranslateRequest` to a remote iommu. This
/// should be cloned and shared between different ipc mappers
/// ... | random_line_split | |
send_txs.rs | // Copyright 2020 The Exonum Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... |
}
impl TimingStats {
fn push(&mut self, dur: Duration) {
if self.max_duration < dur {
self.max_duration = dur;
}
self.total_duration += dur;
self.samples += 1;
}
}
async fn transaction_task(
transaction: Verified<AnyTx>,
sender: ApiSender,
blockchain: B... | {
if self.samples == 0 {
formatter.write_str("(no samples)")
} else {
let avg_duration = self.total_duration.mul_f64(1.0 / (self.samples as f64));
write!(
formatter,
"avg: {} ms, max: {} ms",
avg_duration.as_millis(),
... | identifier_body |
send_txs.rs | // Copyright 2020 The Exonum Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... |
_ => Err(format_err!("Invalid pool flushing strategy")),
}
}
#[derive(Default)]
struct TimingStats {
total_duration: Duration,
max_duration: Duration,
samples: usize,
}
impl fmt::Display for TimingStats {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.s... | {
// 8 is the length of "timeout=".
let timeout: u64 = s[8..].parse()?;
Ok(FlushPoolStrategy::Timeout { timeout })
} | conditional_block |
send_txs.rs | // Copyright 2020 The Exonum Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... | let sender = nodes[0].blockchain().sender().to_owned();
let blockchain = nodes.last().unwrap().blockchain().to_owned();
let tx_task = transaction_task(
tx,
sender,
blockchain,
Arc::clone(×_to_pool),
Arc::clone(×_to_commit),
... | for i in 0..args.tx_count.unwrap_or_else(u64::max_value) {
let tx = keys.timestamp(MainService::INSTANCE_ID, Height(i)); | random_line_split |
send_txs.rs | // Copyright 2020 The Exonum Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... | () {
exonum::crypto::init();
exonum::helpers::init_logger().ok();
let args = Args::from_args();
println!("Running test with {:?}", args);
let config = MainConfig {
generate_tx_in_after_commit: false,
};
let main_service = Spec::new(MainService).with_instance(
MainService::I... | main | identifier_name |
dom.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/. */
//! Types and traits used to access the DOM from style calculation.
#![allow(unsafe_code)]
use data::PseudoStyle... | (&self) -> usize {
self.0
}
}
pub trait TRestyleDamage : Debug + PartialEq + BitOr<Output=Self> + Copy {
/// The source for our current computed values in the cascade. This is a
/// ComputedValues in Servo and a StyleContext in Gecko.
///
/// This is needed because Gecko has a few optimisat... | id | identifier_name |
dom.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/. */
//! Types and traits used to access the DOM from style calculation.
#![allow(unsafe_code)]
use data::PseudoStyle... | /// layout.
///
/// This should be obtained via TNode::existing_style_for_restyle_damage
type PreExistingComputedValues;
fn compute(old: &Self::PreExistingComputedValues,
new: &Arc<ComputedValues>) -> Self;
fn empty() -> Self;
fn rebuild_and_reflow() -> Self;
}
/// Simple ... | /// This is needed because Gecko has a few optimisations for the calculation
/// of the difference depending on which values have been used during | random_line_split |
dom.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/. */
//! Types and traits used to access the DOM from style calculation.
#![allow(unsafe_code)]
use data::PseudoStyle... | } else if hint.contains(RESTYLE_DESCENDANTS) {
unsafe { node.set_dirty_descendants(true); }
let mut current = node.first_child();
while let Some(node) = current {
unsafe { node.set_dirty(true); }
current = node.next_sibling();
}
... | {
// Bail early if there's no restyling to do.
if hint.is_empty() {
return;
}
// If the restyle hint is non-empty, we need to restyle either this element
// or one of its siblings. Mark our ancestor chain as having dirty descendants.
let node = self.as_node()... | identifier_body |
text_edit.rs | use crate::{TextUnit, TextRange, TextBuf, Text, tu};
use std::cmp::Ordering;
#[derive(Clone, Debug)]
pub struct TextEdit {
pub ops: Vec<TextEditOp>,
} |
#[derive(Clone, Debug)]
pub enum TextEditOp {
Copy(TextRange), // TODO: check for disjoint ranges
Insert(TextBuf),
}
impl TextEdit {
pub fn apply(&self, text: Text) -> TextBuf {
let mut result = String::new();
for s in self.ops.iter() {
match *s {
TextEditOp::C... | random_line_split | |
text_edit.rs | use crate::{TextUnit, TextRange, TextBuf, Text, tu};
use std::cmp::Ordering;
#[derive(Clone, Debug)]
pub struct TextEdit {
pub ops: Vec<TextEditOp>,
}
#[derive(Clone, Debug)]
pub enum TextEditOp {
Copy(TextRange), // TODO: check for disjoint ranges
Insert(TextBuf),
}
impl TextEdit {
pub fn apply(&se... | (&mut self, offset: TextUnit) {
let len = offset - self.last_offset;
self.copy_len(len)
}
fn copy_len(&mut self, len: TextUnit) {
let range = TextRange::from_len(self.last_offset, len);
self.segments.push(TextEditOp::Copy(range));
self.last_offset += len
}
fn in... | copy_up_to | identifier_name |
text_edit.rs | use crate::{TextUnit, TextRange, TextBuf, Text, tu};
use std::cmp::Ordering;
#[derive(Clone, Debug)]
pub struct TextEdit {
pub ops: Vec<TextEditOp>,
}
#[derive(Clone, Debug)]
pub enum TextEditOp {
Copy(TextRange), // TODO: check for disjoint ranges
Insert(TextBuf),
}
impl TextEdit {
pub fn apply(&se... |
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_edits() {
let text: TextBuf = "Hello, World!".into();
let edit = {
let mut e = TextEditBuilder::new(text.as_text());
e.replace(TextRange::from_len(tu(0), tu(5)), "Goodbye");
e.insert(tu(7), "cruel... | {
self.last_offset += len
} | identifier_body |
bounds-lifetime.rs | // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {} | identifier_body | |
bounds-lifetime.rs | // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {}
| main | identifier_name |
bounds-lifetime.rs | // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license | type A = for<'b, 'a: 'b> fn(); //~ ERROR lifetime bounds cannot be used in this context
type B = for<'b, 'a: 'b,> fn(); //~ ERROR lifetime bounds cannot be used in this context
type C = for<'b, 'a: 'b +> fn(); //~ ERROR lifetime bounds cannot be used in this context
type D = for<'a, T> fn(); //~ ERROR only lifetime par... | // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
| random_line_split |
nodeiterator.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::NodeIteratorBinding;
use dom::bindings::codegen::Bindings::NodeIteratorBindi... |
}
impl<'a> NodeIteratorMethods for JSRef<'a, NodeIterator> {
}
| {
reflect_dom_object(box NodeIterator::new_inherited(), global, NodeIteratorBinding::Wrap)
} | identifier_body |
nodeiterator.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::NodeIteratorBinding;
use dom::bindings::codegen::Bindings::NodeIteratorBindi... | {
reflector_: Reflector
}
impl NodeIterator {
fn new_inherited() -> NodeIterator {
NodeIterator {
reflector_: Reflector::new()
}
}
pub fn new(global: GlobalRef) -> Temporary<NodeIterator> {
reflect_dom_object(box NodeIterator::new_inherited(), global, NodeIteratorB... | NodeIterator | identifier_name |
nodeiterator.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::NodeIteratorBinding;
use dom::bindings::codegen::Bindings::NodeIteratorBindi... | fn new_inherited() -> NodeIterator {
NodeIterator {
reflector_: Reflector::new()
}
}
pub fn new(global: GlobalRef) -> Temporary<NodeIterator> {
reflect_dom_object(box NodeIterator::new_inherited(), global, NodeIteratorBinding::Wrap)
}
}
impl<'a> NodeIteratorMethods ... | pub struct NodeIterator {
reflector_: Reflector
}
impl NodeIterator { | random_line_split |
encode.rs | /// get three u8 characters and convert to 4 indexes of ALPHABET table
fn encode_block(block: &[u8]) -> [u8; 4] {
let mut bitvec: u32 = 0xff_00_00_00;
// first char place in second octet of bitvec
// second char to third, etc.
for (i, chr) in block.iter().enumerate() {
let x: u32 = (*chr as u32... | (table: &[u8], data: &[u8], out: &mut [u8]) -> usize {
let mut data = data.iter();
let mut block: [u8; 3] = [0; 3];
let mut done = false;
let mut count;
let mut out_size: usize = 0;
while!done {
count = 0;
// fill block with chars
// count only those symbols that were a... | encode | identifier_name |
encode.rs | /// get three u8 characters and convert to 4 indexes of ALPHABET table
fn encode_block(block: &[u8]) -> [u8; 4] | }
/// get translation table and input data buffer, output data buffer
/// and return count of encoded bytes
pub fn encode(table: &[u8], data: &[u8], out: &mut [u8]) -> usize {
let mut data = data.iter();
let mut block: [u8; 3] = [0; 3];
let mut done = false;
let mut count;
let mut out_size: usize ... | {
let mut bitvec: u32 = 0xff_00_00_00;
// first char place in second octet of bitvec
// second char to third, etc.
for (i, chr) in block.iter().enumerate() {
let x: u32 = (*chr as u32) << (8 * (2 - i));
bitvec |= x;
}
// <-----> six bits
let mut... | identifier_body |
encode.rs | /// get three u8 characters and convert to 4 indexes of ALPHABET table
fn encode_block(block: &[u8]) -> [u8; 4] {
let mut bitvec: u32 = 0xff_00_00_00;
// first char place in second octet of bitvec
// second char to third, etc.
for (i, chr) in block.iter().enumerate() {
let x: u32 = (*chr as u32... | ,
None => {
done = true;
0
},
}
}
// in case of empty iterator
if count == 0 {
break
}
for idx in &encode_block(&block) {
if count + 1!= 0 {
out[out_size]... | {
count += 1;
*chr
} | conditional_block |
encode.rs | /// get three u8 characters and convert to 4 indexes of ALPHABET table
fn encode_block(block: &[u8]) -> [u8; 4] {
let mut bitvec: u32 = 0xff_00_00_00;
// first char place in second octet of bitvec
// second char to third, etc.
for (i, chr) in block.iter().enumerate() {
let x: u32 = (*chr as u32... | Some(chr) => {
count += 1;
*chr
},
None => {
done = true;
0
},
}
}
// in case of empty iterator
if count == 0 {
break
}... | // fill block with chars
// count only those symbols that were actually added
for i in 0..3 {
block[i] = match data.next() { | random_line_split |
unit.rs | extern crate stratis_shared as shared;
extern crate uuid;
use ::uuid::Uuid;
use std::io::prelude::*;
use std::io::Cursor;
use shared::player::Player;
use shared::opcode;
use shared::chat;
/// recreate to appease type checker
fn cursor_transform (s: &mut Cursor<Vec<u8>>) -> Cursor<&mut [u8]> {
Cursor::new(&mut s.g... | () {
let p = Player::default();
let id = Uuid::new_v4();
let mut bytes = Player::to_bytes(Some(&id),&p);
let mut s = Cursor::new(&mut bytes[..]);
assert!(s.get_ref().len() > 0);
assert_opcode(&mut s,opcode::PLAYER);
let r = Player::from_stream(&mut s, true);
assert!(r.0.is_s... | player_uuid | identifier_name |
unit.rs | extern crate stratis_shared as shared;
extern crate uuid;
use ::uuid::Uuid;
use std::io::prelude::*;
use std::io::Cursor;
use shared::player::Player;
use shared::opcode;
use shared::chat;
/// recreate to appease type checker
fn cursor_transform (s: &mut Cursor<Vec<u8>>) -> Cursor<&mut [u8]> {
Cursor::new(&mut s.g... | {
let text = "test";
let mut s = Cursor::new(vec![]);
chat::write_text(&mut s, text);
let mut s = cursor_transform(&mut s);
assert!(s.get_ref().len() > 0);
assert_opcode(&mut s,opcode::CHAT);
let r = chat::read_text(&mut s);
assert!(r.is_some());
assert_eq!(text, r.unwrap(... | identifier_body | |
unit.rs | extern crate stratis_shared as shared;
extern crate uuid;
use ::uuid::Uuid;
use std::io::prelude::*;
use std::io::Cursor;
use shared::player::Player;
use shared::opcode;
use shared::chat;
/// recreate to appease type checker
fn cursor_transform (s: &mut Cursor<Vec<u8>>) -> Cursor<&mut [u8]> {
Cursor::new(&mut s.g... | }
#[test]
fn player_uuid () {
let p = Player::default();
let id = Uuid::new_v4();
let mut bytes = Player::to_bytes(Some(&id),&p);
let mut s = Cursor::new(&mut bytes[..]);
assert!(s.get_ref().len() > 0);
assert_opcode(&mut s,opcode::PLAYER);
let r = Player::from_stream(&mut s, tr... | s.set_position(0);
let mut b = [0u8];
let r = s.read_exact(&mut b);
assert!(r.is_ok());
assert_eq!(b[0], op); | random_line_split |
main.rs | extern crate chrono;
extern crate iron;
extern crate persistent;
extern crate r2d2;
extern crate r2d2_sqlite;
extern crate router;
extern crate rusqlite;
extern crate rustc_serialize;
extern crate sha2;
use chrono::*;
use iron::prelude::*;
use iron::Url;
use iron::modifiers::Redirect;
use iron::status::Status;
use ir... | }
/// Given a long URL, see if it already exists in the table, else create an entry and return
/// it.
///
/// A 200 means that a shortened URL already exists and has been returned. A 201
/// response means that a new shortened URL has been created.
fn check_or_shorten_url(db: &Connection, long_url: &str) -> IronResul... |
Ok(Response::with((Status::Created, [HOST, &locator[0..7]].join("")))) | random_line_split |
main.rs | extern crate chrono;
extern crate iron;
extern crate persistent;
extern crate r2d2;
extern crate r2d2_sqlite;
extern crate router;
extern crate rusqlite;
extern crate rustc_serialize;
extern crate sha2;
use chrono::*;
use iron::prelude::*;
use iron::Url;
use iron::modifiers::Redirect;
use iron::status::Status;
use ir... |
/// Given a long URL, see if it already exists in the table, else create an entry and return
/// it.
///
/// A 200 means that a shortened URL already exists and has been returned. A 201
/// response means that a new shortened URL has been created.
fn check_or_shorten_url(db: &Connection, long_url: &str) -> IronResult... | {
let mut d = Sha256::default();
d.input(long_url.as_bytes());
let locator = d.result().as_slice().to_hex();
let timestamp = Local::now().to_rfc3339();
db.execute("INSERT INTO urls VALUES (NULL, ?1, ?2, ?3)",
&[×tamp, &long_url, &&locator[0..7]]).unwrap();
Ok(Response::with((Statu... | identifier_body |
main.rs | extern crate chrono;
extern crate iron;
extern crate persistent;
extern crate r2d2;
extern crate r2d2_sqlite;
extern crate router;
extern crate rusqlite;
extern crate rustc_serialize;
extern crate sha2;
use chrono::*;
use iron::prelude::*;
use iron::Url;
use iron::modifiers::Redirect;
use iron::status::Status;
use ir... | else {
Ok(Response::with((Status::NotFound, "Not found")))
}
}
fn index_handler(_: &mut Request) -> IronResult<Response> {
Ok(Response::with((Status::Ok, "See https://github.com/gsquire/yaus for the API")))
}
fn main() {
let mut router = Router::new();
router.get("/shorten", shorten_handler, ... | {
let long_url = Url::parse(&u.unwrap()).unwrap();
Ok(Response::with((Status::MovedPermanently, Redirect(long_url))))
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.